Python pymodbus tcp同步客户端无法在连接失败时捕获错误
使用来自的Python pymodbus tcp同步客户端无法在连接失败时捕获错误,python,connection,modbus,pymodbus,Python,Connection,Modbus,Pymodbus,使用来自的pymodbus示例 它工作正常,连接到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 = cli
pymodbus
示例
它工作正常,连接到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()。有人能建议怎么做吗。
谢谢请尝试下面的代码,而不是
client.connect()
和print(rr.registers)
:
好的,通过更多的阅读和试验,我让它工作如下。我可能错了。但我想分享我的代码,以帮助像我这样的新手有一个起点。 代码如下所示
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获取值。现在我正在研究异步连接。会带着一些疑问回来,然后会有一些答案(如果有的话);)
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()