sungrow/modbus.go

37 lines
904 B
Go
Raw Normal View History

2021-01-01 16:51:16 +11:00
package main
2021-01-11 10:21:53 +11:00
import (
"encoding/binary"
"fmt"
)
2021-01-01 16:51:16 +11:00
// Helpers for converting straight from modbus data to floats.
2021-01-11 10:21:53 +11:00
func u16(data []byte) (float64, error) {
n := binary.BigEndian.Uint16(data)
if n == 0xFFFF {
// probably a misread
return 0, fmt.Errorf("likely misread: u16 read %v", n)
}
return float64(n), nil
2021-01-01 16:51:16 +11:00
}
2021-01-11 10:21:53 +11:00
func s16(data []byte) (float64, error) {
return float64(int16(binary.BigEndian.Uint16(data))), nil
2021-01-01 16:51:16 +11:00
}
2021-01-11 10:21:53 +11:00
func u32(data []byte) (float64, error) {
2021-01-01 16:51:16 +11:00
// Little-endian big-endian :#
2021-01-11 10:21:53 +11:00
n := uint32(binary.BigEndian.Uint16(data)) + uint32(binary.BigEndian.Uint16(data[2:]))<<16
if n == 0xFFFFFFFF {
// probably a misread
return 0, fmt.Errorf("likely misread: u32 read %v", n)
}
return float64(n), nil
2021-01-01 16:51:16 +11:00
}
2021-01-11 10:21:53 +11:00
func s32(data []byte) (float64, error) {
2021-01-01 16:51:16 +11:00
// Little-endian big-endian :#
2021-01-11 10:21:53 +11:00
return float64(int32(binary.BigEndian.Uint16(data)) + int32(binary.BigEndian.Uint16(data[2:]))<<16), nil
2021-01-01 16:51:16 +11:00
}