#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    3
    Rep Power
    0

    Python and serial port


    G'day all,

    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.

    Cheers.


    Code:
    def main():
    
    	
    	ser=serial.Serial('/dev/ttyACM0',9600)
    	sSql=""
    	while 1:
    		sDateTime=""
    		sSplit=""
    		sFirstChar=""
    		sSql=""
    		sSensorID=""
    		sValue=""
    		
    		sLine=ser.readline()
    		
    		sSplit=sLine.split("|")
    		sDateTime=sSplit[0]
    		sDateTime=sDateTime[1:]
    		sSensorID=sSplit[1]
    		sValue=sSplit[2]
    
    		sSql="INSERT INTO SensorData  MCDateTime,SensorID,SensorValue,CreateDateTime) "
    			sSql += "VALUES ('" + sDateTime + "',"
    			sSql += sSensorID + "," + sValue + ",'" 
    			sSql += str(datetime.datetime.now()) + "')"		
    			
    			db=MySQLdb.connect("localhost","123","123","test")
    			cur=db.cursor()
    			cur.execute(sSql)
    			db.commit()
    			with open('/proc/uptime','r') as f:
    				uptime_seconds = float(f.readline().split()[0])
    				uptime_string = str(timedelta(seconds = uptime_seconds))
    			
    				
    			print "data committed : " + uptime_string + ":" + sLine
     			
    			sSql=""
    if __name__ == '__main__':
    	main()
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,996
    Rep Power
    481
    Read the python tutorial (link) about exception handling.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo