我正在尝试使用 Synchronous Server Example 实现一个简单的同步 TCP 服务器.但是,我不明白文档中的语法解释。该示例包括以下代码块:
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17]*100),
co=ModbusSequentialDataBlock(0, [17]*100),
hr=ModbusSequentialDataBlock(0, [17]*100),
ir=ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
假设我想将 152 的值存储到 Input Register (ir) 地址 30001 和 276 到地址 30002?我应该如何修改上面的代码?
请您参考如下方法:
Suppose I want to store a value of 152 to 'Input Register (ir)' address 30001 and a value of 276 to address 30002? How should I adapt the above code?
下面的代码就是你想要的:
from pymodbus.server.sync import StartTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s'
' %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
def run_server():
store = ModbusSlaveContext(
ir=ModbusSequentialDataBlock(30001, [152, 276]),
zero_mode=True
)
context = ModbusServerContext(slaves=store, single=True)
StartTcpServer(context, address=("localhost", 5020))
if __name__ == "__main__":
run_server()
测试用例:
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
cli = ModbusClient('127.0.0.1', port=5020)
assert cli.connect()
res = cli.read_input_registers(30001, count=2, unit=1)
assert not res.isError()
print(res.registers)
输出:
[152, 276]
