ModbusTcpClient Connection is closed unexpectedly

asked 2021-05-12 11:09:00 -0500

rluque gravatar image

In this example script, the modbus connection works properly when I call the service the first time, but it is closed unexpectedly when I call the service the second time, raising the following error:

Error processing request: Modbus Error: [Connection] ModbusTcpClient({ip}): Connection unexpectedly closed 0.000089 seconds into read of 8 bytes without response from unit before it closed connection

#!/usr/bin/env python3

import rospy 
from pymodbus.client.sync import ModbusTcpClient 
from std_srvs.srv import Empty

driver = ModbusTcpClient("ip", port)

def srv_cb(req):
    status = driver.read_holding_registers(0, 4).registers
    print(status)

def close():
    driver.close()

if __name__ == '__main__':
    node_name = 'node'
    rospy.init_node(node_name)

    serv  = rospy.Service('srv', Empty, srv_cb)
    rospy.on_shutdown(close)
    rospy.spin()

Could someone help me to understand what is happening?

edit retag flag offensive close merge delete