modbus_codec.py 580 B

12345678910111213141516171819
  1. """Encode point values to Modbus registers."""
  2. import struct
  3. def encode_registers(value: object, data_type: str) -> list[int]:
  4. if value is None:
  5. value = 0
  6. if data_type == "int16":
  7. packed = struct.pack(">h", int(value))
  8. elif data_type == "int32":
  9. packed = struct.pack(">i", int(value))
  10. elif data_type == "float32":
  11. packed = struct.pack(">f", float(value))
  12. else:
  13. raise ValueError(f"unsupported data_type: {data_type}")
  14. return [int.from_bytes(packed[index:index + 2], "big") for index in range(0, len(packed), 2)]