MicroPython Human Interface Device library
A library that offers implementations of Human Interface Devices (HID) over Bluetooth Low Energy (BLE) GATT for MicroPython.
Table of Contents
About The Project
This library offers implementations of Human Interface Devices (HID) over Bluetooth Low Energy (BLE) GATT for MicroPython. The library has been tested using an ESP32 development board (TinyPICO) as the peripheral and Windows 10 as the central. Examples and basic implementations of HID devices are available for
- Keyboard,
- Mouse, and
- Joystick.
This library is NOT intended to offer functionality for every possible HID device configuration. Instead, the library is designed to offer basic well-documented classes that you can extend to fit your HID device needs. For example, the Mouse class offers a three button mouse with vertical scroll wheel. If you plan on developing a gaming mouse with eight buttons and both vertical and horizontal wheels, you will need to extend the Mouse class and overwrite the required functions to include a new HID report descriptor.
Requirements
The following is required to use this library:
- ESP32 chip with
- Bluetooth
- 512 kB SRAM or more
- Micropython v1.18 or higher
FAQ
My device doesn't reconnect after power cycling
Please make sure bonding and LE secure is enabled (default).
If that doesn't work, please try using NVS storage before calling start():
from hid_keystores import NVSKeyStore ks = NVSKeyStore() self.keyboard.set_keystore(ks)
Please make sure to remove the device from the client before connecting.
If you do not, the device will expect the keys from the old key store and immediately disconnect.
When you run the composite demo in this repository the firmware stores
bonding information in keys.json by default; make sure this file
survives reboots. If the file is deleted or a new firmware image is
flashed the central (for example iOS) must forget the pairing and bond
again so that new keys are exchanged.
Using a keyboard and mouse simultaneously
This is not immediately supported. You will need to create a new device that has a multi-device HID descriptor and report. Please see this tutorial for more information and use this tool to create the descriptor.
Getting Started
To get a local copy simply clone this repository.
git clone https://github.com/heerkog/MicroPythonBLEHID.git
The repository is structured as followed:
examples/directory containing some examples.async/directory containing asynchronous examples.joystick_example.pykeyboard_example.pymouse_example.py
simple/directory containing simple examples.joystick_example.pykeyboard_example.pymouse_example.py
tinypico/directory containing TinyPICO specific examples. These are mostly personal projects.
hid_services.pythe library.hid_keystores.pydifferent key stores to use with the library.LICENSEthe license.readme.md
Usage
Composite keyboard and mouse demo
The main.py file in the repository root exposes a combined keyboard +
mouse HID device that is driven entirely from a host computer over the
board's USB serial connection. This section walks through running the
demo end-to-end.
-
Copy the firmware to your MicroPython board. Upload
main.py,hid_services.pyandhid_keystores.pyto the filesystem on your ESP32 (or compatible) board. After a reset the script will start automatically and advertise a BLE pointing device called "Composite HID" by default. -
Install the host dependencies. The host utility requires
pyserialfor the UART bridge and, when using the built-in web UI,fastapianduvicorn. Install them with:pip install pyserial fastapi uvicorn
-
Run the UART bridge in command-line mode if you only want to feed JSON events manually. The firmware always tries to claim UART0 during startup; when the UART is created successfully it detaches the on-device REPL from that port and dedicates the USB serial link to transport messages. If UART creation fails (for example because the port is disabled, already owned by the REPL, or you set
UART_ID = Noneinmain.py) the script automatically falls back to the WebSocket transport. To keep the REPL on UART0, either disable the UART transport in the configuration block near the top ofmain.pyor setUART_ID = Noneso the firmware skips the UART entirely.python client.py --port /dev/ttyUSB0
Each line of JSON typed on
stdinis forwarded to the firmware. For example{"type": "mouse", "dx": 25}performs a relative mouse move. -
Start the optional web interface to control the device from a browser. The
--serveflag launches a small FastAPI app that exposes REST endpoints and a WebSocket for real-time events:python client.py --port /dev/ttyUSB0 --serve --host 127.0.0.1 --dev-port 8000
Once the server reports that it is running, open
http://127.0.0.1:8000/in your browser. The page found intemplates/control.htmlwill capture keyboard and mouse events and forward them to the board. (The script does not open a browser window automatically; launch it yourself or with your preferred tooling.) -
Pair the BLE device with your phone/tablet/computer. The BLE peripheral remembers bonding keys in
keys.json(or NVS when configured) so that subsequent connections succeed without repairing. If you ever deletekeys.jsonor flash a fresh firmware image you must remove/forget the pairing from the central device before reconnecting.
REPL access. When the UART transport is active the firmware moves the MicroPython REPL to WebREPL so you can still reach it over Wi-Fi while the USB bridge is reserved for transport messages. If you prefer to keep the REPL on UART0, disable the UART transport or set
UART_ID = Noneand the firmware will stay on the WebSocket-only path. In that mode make sure your board is configured for Wi-Fi and that WebREPL is enabled with a password so you can connect overws://<device-ip>:8266/. The main WebSocket transport for control messages listens onws://<device-ip>:8267/wswhenuwebsockets.serveris available, and a lightweight fallback server is provided as a safety net for firmware builds lacking that module.
Transport availability and fallbacks
- Transport creation lives in
_create_transports. It always tries to claimUART0first because that provides the lowest-latency link between the host bridge and the firmware. If the UART initialisation fails—for example because the port is already owned by the REPL, you explicitly setUART_ID = None, or the hardware lacks a usable USB serial port—the code automatically falls back to bringing up the WebSocket transport instead. - Keeping the REPL on the physical UART is as simple as opting out of the
UART transport: set
UART_ID = None(or comment out the UART block) in the configuration stanza near the top ofmain.py. With that setting the firmware skips any attempt to reassign UART0, leaves the REPL attached, and immediately starts the WebSocket listener for control messages. - Running WebSocket-only requires a few extra steps:
- Configure Wi-Fi access for your board, either by setting
WIFI_SSIDandWIFI_PASSWORDinmain.pyor by using the REPL to join a network before rebooting. - Enable WebREPL (
import webrepl_setup) and set a password so you can reach the MicroPython shell overws://<device-ip>:8266/once the USB bridge is no longer available. - Ensure
uwebsockets.serveris available in your firmware; when it is, control messages are exposed onws://<device-ip>:8267/ws. Stock MicroPython images include this module, so they use the standard server. Boards that ship without it can still connect because a small bundled WebSocket server is provided strictly as a safety net for those builds.
- Configure Wi-Fi access for your board, either by setting
- The firmware refuses to start if neither transport can be created. When that
happens you will see
Unable to start transports: Unable to initialise any transports...on the console so you can fix the underlying issue instead of continuing without host connectivity.
The library offers functionality for creating HID services, advertising them, and setting and notifying the central of HID events. The library does not offer functionality to, for example, send a string of characters to the central using the keyboard service (eventhough this is included in the keyboard example). The reason for this is that such functionality is entirely dependent on the intended use of the services and should be kept outside of this library.
The library consists of five classes with the following functions:
-
HumanInterfaceDevice(superclass for the HID service classes, implements the Device Information and Battery services, and sets up BLE and advertisement)__init__(device_name)(Initialize the superclass)ble_irq(event, data)(Internal callback function that catches BLE interrupt requests)start()(Starts Device Information and Battery services)stop()(Stops Device Information and Battery services)write_service_characteristics(handles)(Writes Device Information and Battery service characteristics)load_secrets()(Loads stored secrets for Bluetooth bonding)save_secrets()(Saves secrets for Bluetooth bonding)start_advertising()(Starts Bluetooth advertisement)stop_advertising()(Stops Bluetooth advertisement)is_running()(ReturnsTrueif services are running, otherwiseFalse)is_connected()(ReturnsTrueif a client is connected, otherwiseFalse)is_advertising()(ReturnsTrueif advertising, otherwiseFalse)set_state(state)(Sets one of theHumanInterfaceDeviceconstantsDEVICE_STOPPED,DEVICE_IDLE,DEVICE_ADVERTISING, orDEVICE_CONNECTED. Doesn't change the actual function. Used internally)get_state()(Returns one of theHumanInterfaceDeviceconstantsDEVICE_STOPPED,DEVICE_IDLE,DEVICE_ADVERTISING, orDEVICE_CONNECTED)set_state_change_callback(callback)(Sets a callback function that is called when theHumanInterfaceDevicestate changes between constantsDEVICE_STOPPED,DEVICE_IDLE,DEVICE_ADVERTISING, orDEVICE_CONNECTED))get_device_name()(Returns the device name)get_services_uuids()(Returns the service UUIDs)get_appearance()(Returns the device appearance id)get_battery_level()(Returns the battery level)set_device_information(manufacture_name, model_number, serial_number)(Sets the basic Device Information characteristics. Must be called before callingstart())set_device_revision(firmware_revision, hardware_revision, software_revision)(Sets the Device Information revision characteristics. Must be called before callingstart())set_device_pnp_information(pnp_manufacturer_source, pnp_manufacturer_uuid, pnp_product_id, pnp_product_version)(Sets the Device Information PnP characteristics. Must be called before callingstart())set_bonding(bond)(Set whether to use Bluetooth bonding)set_le_secure(le_secure)(Set whether to use LE secure pairing)set_io_capability(io_capability)(Set input/output capability of this device Determines the pairing procedure, e.g., accept connection/passkey entry/just works. Must be called before callingstart())set_passkey_callback(passkey_callback)(Set callback function for pairing events. Callback function should return boolean to accept connection or passkey depending on I/O capability used)set_passkey(passkey)(Set the passkey to use for pairing)set_keystore(keystore)(Sets the key store to use fromhid_keystores.py. DefaultJSONKeyStore)set_battery_level(level)(Sets the battery level internally)notify_battery_level()(Notifies the client of the current battery level. Call after setting battery level)notify_hid_report()(Function for subclasses to override)
-
Joystick(subclass ofHumanInterfaceDevice, implements joystick service)__init__(name)(Initialize the joystick)start()(Starts the HID service using joystick characteristics. CallsHumanInterfaceDevice.start())write_service_characteristics(handles)(Writes the joystick HID service characteristics. CallsHumanInterfaceDevice.write_service_characteristics(handles))notify_hid_report()(Notifies the client of the internal HID joystick status)set_axes(x, y)(Sets the joystick axes internally)set_buttons(b1, b2, b3, b4, b5, b6, b7, b8)(Sets the joystick buttons internally)
-
Mouse(subclass ofHumanInterfaceDevice, implements mouse service)__init__(name)(Initialize the mouse)start()(Starts the HID service using mouse characteristics. CallsHumanInterfaceDevice.start())write_service_characteristics(handles)(Writes the mouse HID service characteristics. CallsHumanInterfaceDevice.write_service_characteristics(handles))notify_hid_report()(Notifies the client of the internal HID mouse status)set_axes(x, y)(Sets the mouse axes movement internally)set_wheel(w)(Sets the mouse wheel movement internally)set_buttons(b1, b2, b3)(Sets the mouse buttons internally)
-
Keyboard(subclass ofHumanInterfaceDevice, implements keyboard service)__init__(name)(Initialize the keyboard)start()(Starts the HID service using keyboard characteristics. CallsHumanInterfaceDevice.start())write_service_characteristics(handles)(Writes the keyboard HID service characteristics. CallsHumanInterfaceDevice.write_service_characteristics(handles))notify_hid_report()(Notifies the client of the internal HID keyboard status)set_modifiers(right_gui, right_alt, right_shift, right_control, left_gui, left_alt, left_shift, left_control)(Sets the keyboard modifier keys internally)set_keys(k0, k1, k2, k3, k4, k5)(Sets a list of key codes to press internally. Call without keys to release.)ble_irq(event, data)(Internal callback function that catches BLE keyboard interrupt requests)set_kb_callback(kb_callback)(Sets a callback function that is called on a keyboard event)
-
Advertiser(from the MicroPython Bluetooth examples, used internally byHumanInterfaceDeviceclass)__init__(ble, services, appearance, name)advertising_payload(limited_disc, br_edr, name, services, appearance)decode_field(payload, adv_type)decode_name(payload)decode_services(payload)start_advertising()(Used internally)stop_advertising()(Used internally)
Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
Distributed under the GNU General Public License. See LICENSE for more information.
Contact
Heerko Groefsema - @HeerkoG - hgroefsema.nl
Project Link: https://github.com/heerkog/MicroPythonBLEHID
Acknowledgments
The following resources were of interest during development:
- Bluetooth HID
- USB HID
- Micropython