def handleNotification(self, cHandle, data): self.log.debug("BLE: Handle: {}, data: {}".format( cHandle, data)) rcv = "" for b in data: rcv += chr(b & 127) self.log.debug('BLE received [{}]'.format(rcv)) self.chunks += rcv if self.chunks[0] not in clp.protocol_replies: self.log.warning( "Illegal reply start '{}' received, discarding".format( self.chunks[0])) while len(self.chunks) > 0 and self.chunks[ 0] not in clp.protocol_replies: self.chunks = self.chunks[1:] if len(self.chunks) > 0: mlen = clp.protocol_replies[self.chunks[0]] if len(self.chunks) >= mlen: valmsg = self.chunks[:mlen] self.log.debug( 'bluepy_ble received complete msg: {}'.format( valmsg)) if clp.check_block_crc(valmsg): que.put(valmsg) self.chunks = self.chunks[mlen:]
def usb_read_synchr(self, usbdev, cmd, num): """ Synchronous reads for initial hardware detection. """ rep = [] start = False while start is False: try: b = chr(ord(usbdev.read()) & 127) except Exception as e: self.log.debug("USB read failed: {e}") return [] if b == cmd: rep.append(b) start = True for _ in range(num-1): try: b = chr(ord(usbdev.read()) & 127) rep.append(b) except (Exception) as e: self.log.error(f"Read error {e}") break if clp.check_block_crc(rep) is False: return [] return rep
def event_worker_thread(self, que): """ Background thread that sends data received via usb to the queue `que`. """ self.log.debug('USB worker thread started.') cmd_started = False cmd_size = 0 cmd = "" self.agent_state(self.que, 'online', 'Connected to {}'.format(self.uport)) self.error_state = False posted = False while self.thread_active: while self.error_state is True: time.sleep(1.0) try: self.usb_dev.close() except: pass try: self.usb_dev = serial.Serial( self.uport, 38400, timeout=0.1) self.usb_dev.dtr = 0 self.agent_state(self.que, 'online', 'Reconnected to {}'.format(self.uport)) self.error_state = False posted = False break except Exception as e: if posted is False: emsg = "Failed to reconnected to {}, {}".format( self.uport, e) self.log.warning(emsg) self.agent_state(self.que, 'offline', emsg) posted = True b = "" try: if cmd_started == False: self.usb_dev.timeout = None else: self.usb_dev.timeout = 0.2 by = self.usb_dev.read() if len(by) > 0: b = chr(ord(by) & 127) else: continue except Exception as e: if len(cmd) > 0: self.log.debug( "USB command '{}' interrupted: {}".format(cmd[0], e)) time.sleep(0.1) cmd_started = False cmd_size = 0 cmd = "" self.error_state = True continue if len(b) > 0: if cmd_started is False: if b in clp.protocol_replies: cmd_started = True cmd_size = clp.protocol_replies[b] cmd = b cmd_size -= 1 else: cmd += b cmd_size -= 1 if cmd_size == 0: cmd_started = False cmd_size = 0 if self.protocol_debug is True: self.log.debug("USB received cmd: {}".format(cmd)) if clp.check_block_crc(cmd): que.put(cmd) cmd = ""