BLE handler

This commit is contained in:
Dave Astels 2019-04-12 17:22:21 -04:00
parent c42a52773d
commit 4d227c437e
2 changed files with 96 additions and 0 deletions

View file

@ -0,0 +1,68 @@
"""
UART 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.
"""
#pylint:disable=missing-super-argument
# Example:
#
# import board
# import busio
# from uart_handler import UartHandler
# import adafruit_logging as logging
#
# uart = busio.UART(board.TX, board.RX, baudrate=115200)
# logger = logging.getLogger('uart')
# logger.addHandler(UartHandler(uart))
# logger.level = logging.INFO
# logger.info('testing')
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()
self._uart.start_advertising()
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:
pass
data = bytes(self.format(level, msg), 'utf-8')
for i in range(len(data)):
self._uart.write(data[i:i+1])

View file

@ -0,0 +1,28 @@
import time
import random
from ble_handler import BLEHandler
import adafruit_logging as logging
l = logging.getLogger('ble')
l.addHandler(BLEHandler())
def go():
while True:
t = random.randint(1, 5)
if t == 1:
print('debug')
l.debug("debug message: %d", random.randint(0, 1000))
elif t == 2:
print('info')
l.info("info message: %d", random.randint(0, 1000))
elif t == 3:
print('warning')
l.warning("warning message: %d", random.randint(0, 1000))
elif t == 4:
print('error')
l.error("error message: %d", random.randint(0, 1000))
elif t == 5:
print('critical')
l.critical("critical message: %d", random.randint(0, 1000))
time.sleep(5.0 + (random.random() * 5.0))