你需要的是什么 更新服务器 ,您可以用来填充寄存器。你将不得不专注于功能 def updating_writer 并执行串行读取,处理它们并写入您选择的寄存器。这个例子很难在第一时间阅读和理解。我修改了 例 满足您的需求。但是这里有一些关键概念可以方便地理解代码。
def updating_writer
ModbusSlaveContext
BinaryPayloadBuilder
另请注意,该示例使用基于twisted的异步服务器,如果您是新手,或者有一些限制,不允许您在目标上使用扭曲,您也可以通过简单的线程实现相同。设计大致是这样的。
# Complete gist here --> https://gist.github.com/dhoomakethu/540b15781c62de6d1f7c318c3fc8ae22 def updating_writer(context, device, baudrate): """ A worker process that runs every so often and updates live values of the context. It should be noted that there is a race condition for the update. :param arguments: The input arguments to the call """ log.debug("updating the context") log.debug("device - {}, baudrate-{}".format(device, baudrate)) data = serial_reader(device, baudrate) # Implement your serial reads, return list of floats. if data: # We can not directly write float values to registers, Use BinaryPayloadBuilder to convert float to IEEE-754 hex integer for d in data: builder.add_32bit_float(d) registers = builder.to_registers() context = context register = 3 # Modbus function code (3) read holding registers. Just to uniquely identify what we are reading from /writing in to. slave_id = 0x01 # Device Unit address , refer ModbusSlaveContext below address = 0x00 # starting offset of register to write (0 --> 40001) log.debug("new values: " + str(registers)) context[slave_id].setValues(register, address, registers)
一旦服务器运行并且值正在更新,您可以使用客户端读取值并将其解析回浮动。
from pymodbus.client.sync import ModbusTcpClient as Client from pymodbus.payload import BinaryPayloadDecoder, Endian client = Client(<IP-ADDRESS>, port=5020) # Each 32 bit float is stored in 2 words, so we will read 10 registers raw_values = client.read_holding_registers(0, 10, unit=1) if not registers.isError(): registers = raw_values.registers decoder = BinaryPayloadDecoder.fromRegisters(registers, wordorder=Endian.Big, byteorder=Endian.Big) for _ in range(5): print(decoder.decode_32bit_float())