0

使用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()。有人可以建议如何做到这一点。谢谢

4

2 回答 2

1

试试下面的代码而不是client.connect()and print(rr.registers)

if client.connect():
    ...  # do stuff

    if not rr.isError():
        print(rr.registers)
    else:
        print(rr)
else:
    print('Connection problem')
于 2019-12-09T13:56:11.913 回答
0

好的,通过更多的阅读和试​​验,我让它按如下方式工作。我可能错了。但我想分享我的代码来帮助像我这样的新手有一个起点。代码如下



import logging
UNIT = 0x1


def run_sync_client():
    try:
        #client = ModbusClient('192.168.1.190', port=502)  
        client = ModbusClient('localhost', port=502)  
        client.connect()
        #connected =1

    except:
        print("modbus error")
   # "Read write registeres simulataneously")
    try:
            rr = client.read_holding_registers(1, 4, unit=UNIT)
            # following will write value 10 or 20 to address 1 
            rq = client.write_register(4, 20, unit=UNIT)  
            # close the client
            client.close()
            print (rr)
            print (rr.registers) 
    except Exception as e:
            print ("Modbus Connection returned Error ",e)
if __name__ == "__main__":
    run_sync_client()

这工作正常,并通过 tcp 从 plc 获取值。现在我正在处理异步连接。会带着一些疑问和答案(如果有的话)回来;)

于 2019-12-12T05:26:53.150 回答