pythonconnectiontimeoutpyserial

Python: pyserial timeout doesn't seem to work on connect


I am trying to get python to fail if a COM port is not connected:

import serial

ser = serial

print("ermrmrmrr")
try:
    ser = serial.Serial(
        port        = 'COM6',
        baudrate    = 115200,
        parity      = serial.PARITY_NONE,
        stopbits    = serial.STOPBITS_ONE,
        bytesize    = serial.EIGHTBITS,
        timeout     = 1,
        )
except:
    print("what what in the butt")
    ser.close()
    sys.exit(0)

print("grrrrr")

the output is:

ermrmrmrr
what what in the butt
Traceback (most recent call last):
  File "C:\Projects\Personal\Alex_Quadcopter\mine\scripts\lib\GetData.py", line 21, in <module>
    write_timeout = 1,
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 31, in __init__
    super(Serial, self).__init__(*args, **kwargs)
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialutil.py", line 240, in __init__
    self.open()
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 78, in open
    self._reconfigure_port()
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 222, in _reconfigure_port
    'Original message: {!r}'.format(ctypes.WinError()))
serial.serialutil.SerialException: Cannot configure port, something went wrong. Original message: OSError(22, 'The semaphore timeout period has expired.', None, 121)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ".\PrincipalAxes.py", line 11, in <module>
    from lib import GetData as gd
  File "C:\Projects\Personal\Alex_Quadcopter\mine\scripts\lib\GetData.py", line 25, in <module>
    print("what what in the butt")

This output is somewhat ok except that it timesout 30 seconds - 1 minute after attempting to connect, instead of timing out 1 second after.

It seems to be timing out on "The semaphore timeout period has expired." instead of the actual connection attempt.


Solution

  • The problem is that you cannot close ser because something fatal happened.

    You should break your catch into individual exceptions, instead of one that catches everything. For instance:

    except serial.SerialException as e:
        #There is no new data from serial port
        print str(e)
        sys.exit(1)
    except TypeError as e:
        print str(e)
        ser.port.close()
        sys.exit(1)
    

    Also note that typically passing 0 to sys.exit denotes success. You should pass 1 or some other non-zero number to denote failure.