使用https://github.com/riptideio/pymodbuspymodbus
中的示例
它工作正常并连接到 PLC 并读取保持寄存器。但我有一个问题。当 PLC 关闭时,代码无法捕获断开连接的错误。
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
UNIT = 0x1
def run_sync_client():
client = ModbusClient('192.168.1.190', port=502)
client.connect()
rr = client.read_holding_registers(1, 4, unit=UNIT)
# follwoing will write value 10 or 20 to address 1
rq = client.write_register(4, 20, unit=UNIT)
client.close()
print (rr)
print (rr.registers) ## This reads from input registers of the Modbus Slave / Server
if __name__ == "__main__":
run_sync_client()
我试过了,试试..然后如果client.connect()。有人可以建议如何做到这一点。谢谢