def start_reading(self):
        readBuffer = UartReadBuffer()
        self.started = True
        _LOGGER.debug(F"Read starting on serial port.{self.port} {self.running}")
        try:
            while self.running:
                bytesFromSerial = self.serialController.read()
                if bytesFromSerial:
                    # clear out the entire read buffer
                    if self.serialController.in_waiting > 0:
                        additionalBytes = self.serialController.read(self.serialController.in_waiting)
                        bytesFromSerial = bytesFromSerial + additionalBytes
                    readBuffer.addByteArray(bytesFromSerial)

            # print("Cleaning up UartBridge")
        except OSError or serial.SerialException:
            _LOGGER.info("Connection to USB Failed. Retrying...")
        except KeyboardInterrupt:
            self.running = False
            _LOGGER.debug("Closing serial connection.")

        # close the serial controller
        self.serialController.close()
        self.serialController = None
        # remove the event listener pointing to the old connection
        UartEventBus.unsubscribe(self.eventId)
        self.started = False
        UartEventBus.emit(SystemTopics.connectionClosed, True)
    def initialize_usb_sync(self,
                            port=None,
                            baudrate=230400,
                            writeChunkMaxSize=0):
        '''
                writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.
                For normal usage with Crownstones this is not required.
                writeChunkMaxSize of 0 will not send the payload in chunks
                :param port:
                :param baudrate:
                :param writeChunkMaxSize:
                :return:
                '''
        self.uartManager.config(port, baudrate, writeChunkMaxSize)

        result = [False]

        def handleMessage(result, data):
            result[0] = True

        event = UartEventBus.subscribe(
            SystemTopics.connectionEstablished,
            lambda data: handleMessage(result, data))
        self.uartManager.start()

        try:
            while not result[0] and self.running:
                time.sleep(0.1)
        except KeyboardInterrupt:
            print("\nClosing Crownstone Uart.... Thanks for your time!")
            self.stop()

        UartEventBus.unsubscribe(event)
    def start_reading(self):
        readBuffer = UartReadBuffer()
        self.started = True
        _LOGGER.debug(F"Read starting on serial port {self.port} {self.running}")
        try:
            while self.running:
                bytesFromSerial = self.serialController.read() # reads single byte (blocks until it is received)
                if bytesFromSerial:
                    # read all extra bytes in read buffer
                    if self.serialController.in_waiting > 0:
                        additionalBytes = self.serialController.read(self.serialController.in_waiting)
                        bytesFromSerial = bytesFromSerial + additionalBytes

                    UartEventBus.emit(SystemTopics.uartRawData, bytesFromSerial)
                    readBuffer.addByteArray(bytesFromSerial)
        except OSError or serial.SerialException:
            _LOGGER.info("Connection to USB Failed. Retrying...")
        except KeyboardInterrupt:
            self.running = False
            _LOGGER.debug("Closing serial connection.")
        except Exception as error:
            self.running = False
            _LOGGER.error(f"Error in handling UART data: {error}")
            traceback.print_exc()

        # close the serial controller
        self.serialController.close()
        self.serialController = None
        # remove the event listener pointing to the old connection
        UartEventBus.unsubscribe(self.eventId)
        self.started = False
        UartEventBus.emit(SystemTopics.connectionClosed, True)
    def receive_sync(self):
        counter = 0
        while counter < self.timeout:
            if self.response is not None:
                # cleanup the listener(s)
                UartEventBus.unsubscribe(self.cleanupId)
                return self.response

            time.sleep(self.interval)
            counter += self.interval

        UartEventBus.unsubscribe(self.cleanupId)
        return None
Beispiel #5
0
    def initialize_usb_sync(self,
                            port=None,
                            baudrate=230400,
                            writeChunkMaxSize=0):
        """
        Initialize a Crownstone serial device. 
            
        :param port: serial port of the USB. e.g. '/dev/ttyUSB0' or 'COM3'.
        :param baudrate: baudrate that should be used for this connection. default is 230400.
        :param writeChunkMaxSize: writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.
            For normal usage with Crownstones this is not required. a writeChunkMaxSize of 0 will not send the payload in chunks.
        """
        self.uartManager.config(port, baudrate, writeChunkMaxSize)

        result = [False]

        def handleMessage(result, data):
            result[0] = True

        event = UartEventBus.subscribe(
            SystemTopics.connectionEstablished,
            lambda data: handleMessage(result, data))
        self.uartManager.start()

        try:
            while not result[0] and self.running:
                try:
                    exc = self.manager_exception_queue.get(block=False)
                    self.uartManager.join()
                    self.stop()
                    raise exc[0](exc[1])
                except queue.Empty:
                    pass

                time.sleep(0.1)

        except KeyboardInterrupt:
            print("\nClosing Crownstone Uart.... Thanks for your time!")
            self.stop()

        UartEventBus.unsubscribe(event)
 def stop(self):
     self.running = False
     UartEventBus.unsubscribe(self.eventId)
     self.parser.stop()
 def stop(self):
     self.running = False
     UartEventBus.unsubscribe(self.eventId)
     if self._uartBridge is not None:
         self._uartBridge.stop()
 def stop(self):
     UartEventBus.unsubscribe(self.uartPackageSubscription)
     UartEventBus.unsubscribe(self.uartMessageSubscription)
 def __del__(self):
     for cleanupId in self.cleanupIds:
         UartEventBus.unsubscribe(cleanupId)
 def __del__(self):
     UartEventBus.unsubscribe(self.cleanupId)
 def cleanup(self):
     UartEventBus.unsubscribe(self.cleanupId)