import serial from time import sleep import thread class SCOM: com0 = "/dev/ttyUSB0" com1 = "/dev/ttyUSB1" tick = 460800 def __init__(self): self.ser = None self.findConnected() def findConnected(self): while 1: if self.initSerial(self.com0): break else: if self.initSerial(self.com1): break sleep(0.5) def initSerial(self, com): try: self.ser = serial.Serial(com, self.tick) print 'connected to', com return True except: print 'error connecting to', com return None def getSerial(self): return self.ser def command_is_ok(command): if len(command) > 0: if str(command[0]).isalpha(): if str(command[1:len(command)]).isdigit(): return True return False class LoopSender: def __init__(self, ser): self.done = True self.loop = False self.ser = ser def command_thread_loop(self, command): self.done = False print 'start loop', command while self.loop: try: self.ser.write(command) sleep(0.2) except: pass # self.ser.readline() print 'loop closed', command self.done = True def send_command(self, command): self.loop = False while not self.done: pass # wait until thread finished print 'done' self.loop = True print 'start' thread.start_new_thread(self.command_thread_loop, (command,)) sleep(0.2) def rawCommand(loopSender, command): if command_is_ok(command): # send command print 'command accepted' command += 'c' loopSender.send_command(command) else: print 'wrong command' def main_loop(): scom = SCOM() ser = scom.getSerial() loopSender = LoopSender(ser) while 1: print '1. up' print '2. down' print '3. keep height' print '4. stop' print '5. custom' print '+. tighten' print '-. release' selection = raw_input('selection: ') if selection == '1': rawCommand(loopSender, 'p1000') elif selection == '2': rawCommand(loopSender, 'o500') elif selection == '3': height = raw_input('height: ') rawCommand(loopSender, 'm'+str(height)) elif selection == '4': rawCommand(loopSender, 'q0') elif selection == '5': command = raw_input('command: ') rawCommand(loopSender, command) elif selection == '+': rawCommand(loopSender, 'w0') elif selection == '-': rawCommand(loopSender, 's0') else: print 'wrong selection' if __name__ == '__main__': while 1: try: main_loop() except Exception as e: print e print 'fatal error, full reset'