【问题标题】:pymodbus tcp synchronous client unable to trap error when connection failspymodbus tcp 同步客户端在连接失败时无法捕获错误
【发布时间】:2019-12-06 14:32:42
【问题描述】:

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

【问题讨论】:

    标签: python connection modbus pymodbus


    【解决方案1】:

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

    if client.connect():
        ...  # do stuff
    
        if not rr.isError():
            print(rr.registers)
        else:
            print(rr)
    else:
        print('Connection problem')
    

    【讨论】:

      【解决方案2】:

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

      
      
      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 获取值。现在我正在处理异步连接。会带着一些疑问回来,然后是一些答案(如果有的话);)

      【讨论】:

        猜你喜欢
        • 2021-03-13
        • 2015-01-26
        • 1970-01-01
        • 1970-01-01
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多