我正在尝试使用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?我应该如何修改以上代码?

最佳答案

假设我要将值152存储到“输入寄存器(ir)”地址30001,并将值276存储到地址30002?我应该如何修改以上代码?


以下代码是您想要的:

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]

关于python - 将值分配给TCP服务器寄存器的pymodbus语法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55528137/

10-13 04:35