Skip to content

Commit

Permalink
fix(cmd/modbus-cli): fix byte write function to also work with floats
Browse files Browse the repository at this point in the history
  • Loading branch information
dammarco committed Mar 8, 2023
1 parent 888f05e commit 2371399
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions cmd/modbus-cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -432,33 +432,44 @@ func newHandler(o option) (modbus.ClientHandler, error) {
return nil, fmt.Errorf("unsupported scheme: %s", u.Scheme)
}

type binaryWriter interface {
PutUint32(b []byte, v uint32)
PutUint16(b []byte, v uint16)
PutFloat32(b []byte, v float32)
PutFloat64(b []byte, v float64)
}

func newWriter(o binary.ByteOrder) *writer {
return &writer{o}
return &writer{order: o}
}

type writer struct {
binary.ByteOrder
order binary.ByteOrder
}

func (w *writer) ToUint16(v uint16) []byte {
var buf bytes.Buffer
w.to(&buf, v)
b, _ := io.ReadAll(&buf)
return b
}

func (w *writer) ToUint32(v uint32) []byte {
var buf bytes.Buffer
w.to(&buf, v)
b, _ := io.ReadAll(&buf)
return b
}

func (w *writer) PutFloat32(b []byte, v float32) {
buf := bytes.NewBuffer(b)
w.to(buf, v)
func (w *writer) ToFloat32(v float32) []byte {
var buf bytes.Buffer
w.to(&buf, v)
b, _ := io.ReadAll(&buf)
return b
}

func (w *writer) PutFloat64(b []byte, v float64) {
buf := bytes.NewBuffer(b)
w.to(buf, v)
func (w *writer) ToFloat64(v float64) []byte {
var buf bytes.Buffer
w.to(&buf, v)
b, _ := io.ReadAll(&buf)
return b
}

func (w *writer) to(buf io.Writer, f interface{}) {
if err := binary.Write(buf, w.ByteOrder, f); err != nil {
if err := binary.Write(buf, w.order, f); err != nil {
panic(fmt.Sprintf("binary.Write failed: %s", err.Error()))
}
}

0 comments on commit 2371399

Please sign in to comment.