I have an Arduino which is communicating properly with my Mac over serial using the pySerialTransfer library, running for hours. Then there is an interruption of the serial of some sort - though I've been unable to identify the cause when this happens overnight, I can reproduce the behavior pretty easily by just unplugging the Arduino USB cable from the laptop. The python code on my laptop continues to run, but gets into this infinite error loop:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pySerialTransfer/pySerialTransfer.py", line 257, in send
self.connection.write(stack)
File "/usr/local/lib/python3.7/site-packages/serial/serialposix.py", line 571, in write
raise SerialException('write failed: {}'.format(e))
serial.serialutil.SerialException: write failed: [Errno 6] Device not configured
SENT (12 byte struct): (0, -55.836434114277004, 31.732435543849192)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/serial/serialposix.py", line 537, in write
n = os.write(self.fd, d)
OSError: [Errno 6] Device not configured
During handling of the above exception, another exception occurred:
I seem unable to catch the exceptions using any try / except blocks in my python code, so that I can detect this and restart or try to reconnect. Below is my current python code - appreciate any pointers! Thank you.
#!/usr/bin/python3
import sys
import time
import arduino
import messageboard
VERBOSE = arduino.VERBOSE
SN = '75835343130351802272' # arduino uno serial
SIMULATE_ARDUINO = arduino.SIMULATE_ARDUINO
if '-s' in sys.argv:
SIMULATE_ARDUINO = True
COMMAND_DELAY_TIME = 1 # send a command to servos every n seconds
def main():
servos = arduino.OpenArduino(sn=SN)
format_string = '<lff'
format_byte_size = arduino.SizeOf(format_string)
azimuth=90
while True:
if not servos and not SIMULATE_ARDUINO:
servos = arduino.OpenArduino(sn=SN)
if VERBOSE:
print('Reopening connection')
if servos or SIMULATE_ARDUINO:
if azimuth == 90:
azimuth = 85
else:
azimuth = 90
values = (0, azimuth, 0)
arduino.StuffObject(servos, values, format_string, format_byte_size)
if not SIMULATE_ARDUINO:
servos.send(format_byte_size)
time.sleep(COMMAND_DELAY_TIME)
if __name__ == "__main__":
main()