How to read serial port with several scripts?

106 Views Asked by At

I'm using a temperature controller that I want to control with my python app. I use the module minimalmodbus to send instruction to the controller and open/close the serial port.

I wrote a class TempSensor with two methods:

  • get_temperature(): to get the actual temperature of my set-up
  • set_consign(): to change the temperature consign.

Each time those methods are called, the port is opened and then closed.

In my app, I use two scripts calling at these methods in loop, and it works until one of the script call one of the method when the other has already opened the port and not closed it yet.

I'm looking for a way to force the script to wait until the port is closed to open it and call the method.

I tried to do this every time I call one of the method:

try:
    temperature=Temp_Sensor.get_temperature()
except:
    pass

The problem with that, is the code doesn't try again if there is an exception (e.g. port already open) and the temperature variable is still empty.

Do you have a method to make the code try again and again to call get_temperature() until there is no exception?

1

There are 1 best solutions below

0
On

You could use while loop with break, that will only trigger if the above line don't throw exception. Like this:

while True:
    try:
        temperature=Temp_Sensor.get_temperature()
        break
    except: # i would suggest catching only the specific exception that you expect :D
        pass