--- a/slotUI/freeslot.py Sat Dec 03 12:10:10 2011 +0100 +++ b/slotUI/freeslot.py Sat Dec 03 13:53:44 2011 +0100 @@ -3,8 +3,18 @@ Blackbox communication library """ -import serial -import sys +import serial, sys, string, time + +# how often should a command retried when busy? +RETRIES = 10 + +# define loglevels +DEBUG = 20 +def log(level, msg): + """ + Logging output function + """ + print msg class SerialCommunicator(): def __init__(self, device, speed): @@ -38,12 +48,23 @@ answer = self.com.readline() return string.strip(answer, "\n") + def query(self, msg): + retry = 0 + response = self.write(msg, True) + while (retry < RETRIES) and (response == "BUSY"): + time.sleep(0.1) + response = self.write(msg, True) + retry += 1 + log( DEBUG, "%i> %s\n< %s" % (retry, msg, response) ) + return response + + class Blackbox(): def __init__(self): self.com = None self.info = None - def connect(self, device="/dev/ttyUSB0", speed=115200): + def connect(self, device="/dev/ttyUSB0", speed=57600): if self.com == None: self.com = SerialCommunicator(device, speed) if self.com.connected: @@ -51,10 +72,10 @@ self.com.connect() self.info = self.readinfo() - def disconnect(): + def disconnect(self): self.com.disconnect() - def readinfo(): + def readinfo(self): """ Read complete Information from connected box This does not include race+car status! @@ -64,10 +85,40 @@ def progcar(self, carid, command, value): """ Send program packets to specified car id - valid command: speed, brake + valid command: speed, brake, fuel valid value: 4 bit integer (0..15) + valid carid: 0..5 """ - return True + if (carid < 0) or (carid > 5): + return "ERR - invalid carid" + cmd = -1 + if command == "speed": + cmd = 0 + if command == "brake": + cmd = 1 + if command == "fuel": + cmd = 2 + if (cmd == -1): + return "ERR - invalid command" + if (value<0) or (value>15): + return "ERR - invalid value" + # transform value 10..15 to A..F + if (value>9): + value = chr(ord("A") + (value-10)) + command = "P%i%s%i" % (cmd, value, carid) + response = self.com.query( command ) + return response + + def blinkcar(self, carid, blink): + """ + Set car blinking state + """ + if (carid < 0) or (carid > 5): + return "ERR - invalid carid" + if blink: + return self.com.query( "P48%i" % carid ) + else: + return self.com.query( "P40%i" % carid ) def setmode(self, mode): """