If you are using a board that supports BLE, such as the Feather nRF52840, you can write a handler that sends log messages over BLE to, for example, the BlueFruit mobile app. As you can see above, each message is split into 20 character chunks. This is due to the way the low level BLE UART support code operates. Since we use the BLE UART interface, this is very much like the UARTHandler.

BLE based message handler for CircuitPython logging.

Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!

Written by Dave Astels for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.

All text above must be included in any redistribution.


from adafruit_logging import LoggingHandler
from adafruit_ble.uart import UARTServer

class BLEHandler(LoggingHandler):
    """Send logging output to the BLE uart port."""

    def __init__(self):
        """Create an instance.

        :param uart: the busio.UART instance to which to write messages

        self._advertising_now = False
        self._uart = UARTServer()

    def format(self, level, msg):
        """Generate a string to log.

        :param level: The level at which to log
        :param msg: The core message

        return super().format(level, msg) + '\r\n'

    def emit(self, level, msg):
        """Generate the message and write it to the UART.

        :param level: The level at which to log
        :param msg: The core message

        while not self._uart.connected:
        data = bytes(self.format(level, msg), 'utf-8')

The constructor sets up the BLE UART interface, and starts advertising. This lets devices in the area see it and connect to it. See this guide for information on using the BlueFruit app. You need to select UART Mode to receive the logging messages from the board.

As with the UART handler, this provides its own format method which calls the superclass's format to build the output string (that's the LoggingHandler class) and appends a newline sequence (a carriage return then a line feed) since write doesn't automatically terminate the line the way print does.

The emit method ensures that there is a live connection, uses format to build the string, converts it to a bytearray, and writes the bytes to the BLE UART.

You would use it like in the following example:

import board
import busio
from ble_handler import BLEHandler
import adafruit_logging as logging

logger = logging.getLogger('test')

This guide was first published on Mar 18, 2019. It was last updated on Mar 18, 2019.

This page (Log to BLE) was last updated on May 05, 2021.

Text editor powered by tinymce.