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.

# SPDX-FileCopyrightText: 2019 Dave Astels for Adafruit Industries
# SPDX-License-Identifier: MIT

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 Handler
from adafruit_ble.uart import UARTServer

class BLEHandler(Handler):
    """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, record):
        """Generate a string to log.

        :param record: The record (message object) to be logged
        return super().format(record) + '\r\n'

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

        :param record: The record (message object) to be logged
        while not self._uart.connected:
        data = bytes(self.format(record), '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 Jun 22, 2024.

This page (Log to BLE) was last updated on Jun 21, 2024.

Text editor powered by tinymce.