April 10th, 2013, 09:34 PM
Python and serial port
I'm using Python to grab data from a serial port and insert it into a database.
It's all working well, but I have an issue with error handling (or, more to the point, lack of it! )
I connect to the serial port at the start of the code, before the polling routine starts. The problem is, if the serial data is interrupted from the source, I get errors all through the code and the python script crashes, as once it's polling the serial port is never connected to nor checked again.
I'm sure I don't want to connect to the serial port everytime through the loop, but I'd like to catch any error and sit on a loop attempting to reconnect to either ttyACM0 or ttyACM1, toggling between each one (if the USB device disconnects for any reason, it sometimes comes up again on the Pi as ACM1. At bootup of the Pi, it's always ACM0). Once it's connected to either port, start polling again.
Any help would be most appreciated.
sSql="INSERT INTO SensorData MCDateTime,SensorID,SensorValue,CreateDateTime) "
sSql += "VALUES ('" + sDateTime + "',"
sSql += sSensorID + "," + sValue + ",'"
sSql += str(datetime.datetime.now()) + "')"
with open('/proc/uptime','r') as f:
uptime_seconds = float(f.readline().split())
uptime_string = str(timedelta(seconds = uptime_seconds))
print "data committed : " + uptime_string + ":" + sLine
if __name__ == '__main__':
April 10th, 2013, 11:17 PM