bledev.hid

BLE keyboards and game controllers, both ways: HID over GATT (HOGP).

As a host (central), a board or a laptop connects to a BLE keyboard, remote or gamepad and gets OmniPython events, the same events.Key and events.Joy* records a USB keyboard gives through usbif or SDL gives on the desktop:

import bledev.hid as hid

host = await hid.connect(ble, name="Keyboard K380")
while True:
    for event in await host.events():
        print(event)

It reads the device’s Report Map, parses it (bledev.hidreport), subscribes to every input report and decodes each one as it arrives. A keyboard that insists on pairing gets it: the first read that fails for want of encryption pairs the link and tries again, and with bond=True (the default) the keys are kept, so the next connect is quick.

As a device (peripheral), a board advertises as a BLE keyboard, mouse, media remote and gamepad. Its Peripheral.devices are CircuitPython’s usb_hid.devices shape, so Adafruit’s adafruit_hid drives them exactly as it drives USB:

from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.mouse import Mouse

per = hid.Peripheral(ble)                # keyboard, mouse, consumer
await per.serve()                        # waits for a host
kb = Keyboard(per.devices)
KeyboardLayoutUS(kb).write("Hello\n")
Mouse(per.devices).move(x=40)

Install adafruit_hid with mip.install("github:PyDevices/omnipython/bledev_hid"). The gamepad, which adafruit_hid no longer has, is bledev.hid_gamepad.

Its name, appearance and Report Map follow from which functions it offers, the same way every time, because hosts cache a device’s services against its identity. Change the set and a host that paired before must forget the board and pair again.

A laptop (bleak) or a browser can’t advertise, so they are hosts only. Windows keeps HID devices for itself once paired; don’t pair a board you are testing with the PC you are testing from, or it will type into it.

bledev.hid.INSPECT_SERVICE = UUID('b1ed0000-4849-4400-8000-00805f9b34fb')

The HID characteristics under a vendor UUID, for inspection from a laptop. Windows hides the HID service (0x1812) from apps entirely, and Chrome’s Web Bluetooth blocklist does too, so a laptop can only see a board’s HID characteristics if the board serves them under another UUID.

bledev.hid.report_map(keyboard=True, mouse=True, consumer=True, gamepad=False)[source]

The Report Map a board serves for this set of functions, always the same bytes.

bledev.hid.identity(keyboard=True, mouse=True, consumer=True, gamepad=False)[source]

(name, appearance, product_id) for a set of functions.

The name is the board’s, boarddev.name(): the appearance already tells a host it’s a keyboard, a mouse or a gamepad. The appearance and product ID are derived from the functions the same way every time.

bledev.hid.SEND_WAIT_MS = 2000

How long one send_report keeps retrying a busy radio before it gives up.

class bledev.hid.Device(owner, characteristic, report_id, usage_page, usage, in_report_length, out_report_length=0)[source]

Bases: object

One HID function of a Peripheral, in CircuitPython’s usb_hid.Device shape: usage_page, usage, send_report() and get_last_received_report(). adafruit_hid finds it by usage.

send_report(report, report_id=None)[source]

Send one input report to the connected host, now.

It returns once the radio has taken the report. A busy radio is retried for up to SEND_WAIT_MS, then raises BusyError; with no host connected it raises BLEError.

get_last_received_report(report_id=None)[source]

The last output report the host wrote (the keyboard’s LEDs), or None.

class bledev.hid.Peripheral(ble, *, keyboard=True, mouse=True, consumer=True, gamepad=False, name=None, encrypted=False, battery=100, manufacturer='PyDevices', service_uuid=UUID(0x1812))[source]

Bases: object

A board that is a BLE keyboard, mouse, media remote and gamepad (any of them).

devices lists one Device per function, in that order, for adafruit_hid (Keyboard(per.devices), Mouse(per.devices), ConsumerControl(per.devices)) and bledev.hid_gamepad. The default set is usb_hid’s: keyboard, mouse and consumer control.

encrypted=True serves the Report Map and reports only to a host that has paired, as real keyboards do; the host pairs “just works”. Call ble.enable_bonding() first on MicroPython so the keys are kept.

service_uuid=INSPECT_SERVICE serves the same characteristics under a vendor UUID instead of 0x1812, so a laptop can read them (no host will treat the board as a keyboard then).

It advertises as name, by default the board’s, boarddev.name().

devices

One Device per function, as usb_hid.devices lists them.

async serve(timeout_ms=None)[source]

Advertise until a host connects, and return the connection.

async leds(timeout_ms=None)[source]

The next LED report the host writes, as (ticks_us, data). devices’ keyboard keeps the last one for adafruit_hid too.

class bledev.hid.Host(connection, *, bond=True, instance_id=0, queue_limit=256, service_uuid=UUID(0x1812))[source]

Bases: object

One connected HID device, as a stream of OmniPython events.

Make it with connect, or start it on a connection you already have. report_map is the parsed ReportMap; paired says whether it had to pair.

last_report_us

When the last input report arrived, in ticks_us.

poll()[source]

Every event decoded so far, as a list (possibly empty). Never waits.

async events(timeout_ms=None)[source]

Wait for at least one event, and return every one waiting.

They come in the order the device sent them, whichever function (keyboard, mouse, media keys) each report was for, on a backend that numbers notifications as they arrive (MicroPython does).

async set_leds(bits)[source]

Write the keyboard’s LED report (Num Lock is bit 0), if it has one.

async bledev.hid.connect(ble, name=None, *, device=None, timeout_ms=10000, bond=True, instance_id=0, service_uuid=UUID(0x1812), **options)[source]

Find a BLE HID device (by name, or any advertising the HID service), connect, and return a started Host.