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