""" Listen to serial, return most recent numeric values Lots of help from here: http://stackoverflow.com/questions/1093598/pyserial-how-to-read-last-line-sent-from-serial-device """ from threading import Thread import time import serial import struct status = [0, 23, 23, 0, 0, 0] oven_connected = False profile = [ 150, 200, 217, 260, 480, 1, 2, 1, 2, -1, -6, 60, 180, 60, 150, 20, 40] PI_TS_MIN = 0 PI_TS_MAX = 1 PI_TL = 2 PI_TP = 3 PI_TIME_MAX = 4 PI_TS_RAMP_UP_MIN = 5 PI_TS_RAMP_UP_MAX = 6 PI_TP_RAMP_UP_MIN = 5 PI_TP_RAMP_UP_MAX = 6 PI_RAMP_DOWN_MIN = 7 PI_RAMP_DOWN_MAX = 8 PI_TS_DURATION_MIN = 9 PI_TS_DURATION_MAX = 10 PI_TL_DURATION_MIN = 11 PI_TL_DURATION_MAX = 12 PI_TP_DURATION_MIN = 13 PI_TP_DURATION_MAX = 14 def recv_config(ser): global profile ser.write(chr(255)) ser.flush() t = ser.read(30) profile = struct.unpack("hhhhhhhhhhhhhhhhh", t) ser.flushInput() def receiving(ser): global status try: time.sleep(2) recv_config(ser) except Exception, e: print e pass while 1: ser.write(chr(254)) ser.flush() status = struct.unpack("hhhhhb", ser.read(11)) ser.flushInput() class SerialData(object): def __init__(self, init=50): try: self.ser = ser = serial.Serial( port='/dev/ttyUSB0', baudrate=9600, timeout=2) except serial.serialutil.SerialException: #no serial connection self.ser = None else: Thread(target=receiving, args=(self.ser,)).start() def next(self): global status if not self.ser: return status[1] try: return status[1] except Exception: pass def send_config(self): if not self.ser: return global profile self.ser.write(struct.pack("hhhhhhhhhhhhhhhhh", profile)) def send_start(self): if not self.ser: return False self.ser.write(chr(251)) return True def connected(self): return self.ser != None def __del__(self): if self.ser: self.ser.close() if __name__=='__main__': s = SerialData() for i in range(500): time.sleep(1) print s.next()