#!/usr/bin/env python
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.payload import BinaryPayloadBuilder
from pymodbus.client.sync import ModbusTcpClient
import struct
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)
ip_address = "192.168.1.55"
client = ModbusTcpClient(ip_address)
if client.connect(): # connection is OK
# write float
#builder = BinaryPayloadBuilder(endian=Endian.Little)
#builder.add_32bit_float(77.77)
#payload = builder.build()
#result = client.write_registers(1, payload, skip_encode=True)
# read floats
result = client.read_holding_registers(28, 2)
decoder = BinaryPayloadDecoder.fromRegisters(result.registers,
endian=Endian.Big)
print str(decoder.decode_32bit_float())
client.close()
var1 = str(decoder.decode_32bit_float())
我正在使用PyModbus库从PLC读取浮点值。我从str(decoder.decode_32bit_float())
获取正确的值,但未能将其放入变量var1
中。它显示错误(在decode 32 bit float return unpack(string, handle)[0] struct.error: unpack requires a string argument of length 4
中)。
预先感谢