Blame | Last modification | View Log | SVN | RSS feed
############################################################# Serial interface, connects with can bus over a serial# line############################################################import logging as logfrom NodeIfBase import NodeIfBasefrom threading import Threadimport serialimport sysimport timeUART_START_BYTE = 253UART_END_BYTE = 250PACKET_LENGTH = 17readBufferSize = 8192UART_CONN_BYTE = 252class SerialThread(Thread):terminated = Falseport = NonepktHandler = Nonedef __init__ (self, pktHandler, port, exceptHook):Thread.__init__(self)self.pktHandler = pktHandlerself.port = portsys.excepthook = exceptHookdef run(self):log.debug('SerialThread.run')readBuffer = []while not self.terminated:inByte = self.port.read()if inByte == '\n':msg = ''.join(readBuffer)readBuffer = []#print 'Incoming:', msgself.pktHandler.input(msg)else:readBuffer.append(inByte)time.sleep(0.1)self.port.close()def terminate(self):log.debug('SerialThread.terminate')self.terminated = Trueclass NodeIfSerial(NodeIfBase):DEFAULT_CONFIG = {'serialPort':1, #com1'baudRate':9600,'byteSize':8,'parity': 'N','stopBits':1,'timeOut': 0, # must be 0 (non-blocking mode)'softFlowCtl': 0,'hardFlowCtl': 0}serialThread = NonepktHandler = NoneexceptHook = Nonedef __init__ (self, pktHandler, exceptHook, cfg = None):if cfg is None:self.config = self.DEFAULT_CONFIGself.pktHandler = pktHandlerself.exceptHook = exceptHookNodeIfBase.__init__(self, cfg, pktHandler)def start(self):try:port = serial.Serial(self.config['serialPort'],self.config['baudRate'],self.config['byteSize'],self.config['parity'],self.config['stopBits'],self.config['timeOut'],self.config['softFlowCtl'],self.config['hardFlowCtl'])except (serial.SerialException), Error:print Errorreturn Falseself.serialThread = SerialThread(self.pktHandler, port, self.exceptHook)self.serialThread.start()return Truedef stop(self):if self.serialThread is not None:self.serialThread.terminate()else:log.debug('Serial interface not started, or already stopped')