code.py
 1  # SPDX-FileCopyrightText: 2019 Dave Astels for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  """
 6  BLE based message handler for CircuitPython logging.
 7  
 8  Adafruit invests time and resources providing this open source code.
 9  Please support Adafruit and open source hardware by purchasing
10  products from Adafruit!
11  
12  Written by Dave Astels for Adafruit Industries
13  Copyright (c) 2018 Adafruit Industries
14  Licensed under the MIT license.
15  
16  All text above must be included in any redistribution.
17  """
18  
19  
20  from adafruit_logging import Handler
21  from adafruit_ble.uart import UARTServer
22  
23  class BLEHandler(Handler):
24      """Send logging output to the BLE uart port."""
25  
26      def __init__(self):
27          """Create an instance.
28  
29          :param uart: the busio.UART instance to which to write messages
30          """
31          self._advertising_now = False
32          self._uart = UARTServer()
33          self._uart.start_advertising()
34  
35      def format(self, record):
36          """Generate a string to log.
37  
38          :param record: The record (message object) to be logged
39          """
40          return super().format(record) + '\r\n'
41  
42      def emit(self, record):
43          """Generate the message and write it to the UART.
44  
45          :param record: The record (message object) to be logged
46          """
47          while not self._uart.connected:
48              pass
49          data = bytes(self.format(record), 'utf-8')
50          self._uart.write(data)