Currently, I'm using pymodbus to read data from a few slave devices. I discovered that even if the connecting fails, the script would still continue regardless instead of just failing. I want it to just fail properly so that I can catch the error itself.
Below is the function I made for establishing a connection.
def init485(port_in, baudrate_in):
client = ModbusClient(method="rtu", port=port_in, stopbits=1 ,bytesize=8 ,parity="N", baudrate=baudrate_in, timeout=3)
connection = client.connect()
print("Connecting to", port_in, "...")
sleep(5)
if (connection is True):
print("Connection successful at", getcurrenttime())
else:
print("Failed to connect. Please check if settings are correct.")
sleep(2)
return connection, client
And below that is the try-except within a while loop.
while True:
try:
c = init485("/dev/ttyUSB0", 9600)
connection = c[0]
mb_client = c[1]
while (connection is True):
...
except:
mb_client.close()
print("Failed")
sleep(60)
The idea is that if the connection to the port fails, it'd catch and print "Failed". Right now, it's just stuck in the while loop. Is there a way to make it work? The error I want to catch is this:
ERROR:pymodbus.client.sync:could not open port '/dev/ttyUSB0': FileNotFoundError(2, 'The system cannot find the path specified.', None, 3)