报错内容
pymodbus.exceptions.ConnectionException: Modbus Error: [Connection] ModbusTcpClient 192.168.2.99:502: Connection unexpectedly closed 0.000 seconds into read of unbounded read bytes without response from slave before it closed connection
背景
- 使用摄像头对下位机持续控制, 第一次发信后成功, 第二次就报错
解决办法
- 每次发信后关闭链接
控制代码
python
import time
from pymodbus.client import ModbusTcpClient
class WorkstationControl:
def __init__(self, host, port):
self.ip_address = host
self.port = port
self.client = ModbusTcpClient(host=host, port=port)
self.delay_time = 2
def is_connect(self):
return self.client.connect()
def start(self):
self.client.write_register(address=0, value=1)
# Wait for 2 seconds
time.sleep(self.delay_time)
self.client.write_register(address=1, value=0)
self.client.close()
def update_speed(self, speed):
self.client.connect()
self.client.write_register(address=1, value=speed)
self.client.close()
def stop(self):
self.client.write_register(address=1, value=0)
# Wait for 2 seconds
time.sleep(self.delay_time)
self.client.write_register(address=0, value=2)
self.client.close()
def close(self):
"""关闭与 Modbus 服务器的连接"""
self.client.close()
# 示例用法
if __name__ == '__main__':
workstation = WorkstationControl(host='192.168.2.99', port=502)
if workstation.is_connect():
workstation.start()
workstation.update_speed(speed=2)
time.sleep(5)
workstation.update_speed(speed=3)
time.sleep(5)
workstation.stop()
else:
print('Failed to connect to the workstation')