micropython blehid
时间: 2025-01-08 15:11:14 浏览: 6
### MicroPython 实现 BLE HID 的示例代码及实现细节
#### 使用 `pyboard` 或兼容板卡作为基础硬件平台,在 MicroPython 中可以利用内置库来创建 BLE HID 设备。
为了构建一个简单的 BLE HID 键盘设备,以下是具体实现方法:
1. **初始化 BLE 并设置服务**
需要先导入必要的模块并配置基本参数。这包括定义用于报告按键状态的数据结构以及初始化 BLE 接口[^3]。
```python
from ubluetooth import UUID, FLAG_READ | FLAG_WRITE, FLAG_NOTIFY
import bluetooth
hid_service_uuid = UUID(0x1812) # HID Service UUID
report_char_uuid = UUID(0x2A4D) # Report Characteristic UUID
# 初始化蓝牙对象
ble = bluetooth.BLE()
```
2. **注册 HID 服务和特征**
创建 HID 服务并将相应的特性(如输入报告)添加到该服务中。这里使用的是标准的 HID over GATT 协议中的 Input Report 特性[^3]。
```python
def register_services():
service = (
hid_service_uuid,
[
(report_char_uuid, FLAG_WRITE),
],
)
services = (service,)
return services
```
3. **处理连接事件**
当有客户端尝试连接时触发此回调函数。在此处可执行一些额外的操作,比如准备发送初始数据给主机端应用[^3]。
```python
connected_clients = set()
def on_connect(conn_handle):
global connected_clients
print('New connection')
connected_clients.add(conn_handle)
def on_disconnect(conn_handle):
global connected_clients
print('Disconnected')
try:
connected_clients.remove(conn_handle)
except KeyError:
pass
```
4. **编写 HID 数据包格式化器**
定义如何打包键盘扫描码成符合 HID 规范的数据帧。对于大多数情况来说,只需关注键按下/释放两种状态即可[^3]。
```python
KEYBOARD_REPORT_ID = const(1)
def make_keyboard_report(keycode=0, modifiers=0):
report = bytearray([modifiers, 0]) # Modifiers byte followed by reserved zero-byte.
if keycode != 0:
report.append(KEYBOARD_REPORT_ID)
report.extend((keycode,))
while len(report) < 8: # Ensure the length of keyboard report is always 8 bytes long.
report.append(0)
return report
```
5. **发送按键命令至配对设备**
将构造好的 HID 报告通过已建立的 BLE 连接传输给远程设备。注意每次只应传送单个完整的报告单元[^3]。
```python
async def send_keypress(characteristic, key_code):
characteristic.write(make_keyboard_report(key_code))
await asyncio.sleep_ms(50) # Simulate key press duration.
characteristic.write(make_keyboard_report()) # Release all keys.
```
6. **启动 BLE HID 应用程序逻辑**
综合上述组件形成完整的工作流程。监听来自用户的输入指令并通过 BLE 发送对应的 HID 命令[^3]。
```python
if __name__ == '__main__':
ble.active(True)
ble.config(gap_name="MPY_HID")
((input_characteristic,),) = ble.gatts_register_services(register_services())
ble.irq(handler=lambda event, data: {
1: lambda d: on_connect(d[0]),
2: lambda d: on_disconnect(d[0])
}.get(event)(data))
loop = asyncio.get_event_loop()
while True:
if not connected_clients:
continue
user_input = input("Enter a character to type via BLE:")
char_to_send = ord(user_input[:1].upper())
loop.run_until_complete(send_keypress(input_characteristic, char_to_send))
```
以上就是基于 MicroPython 构建简单 BLE HID 设备的方法概述及其核心部分的源代码片段。实际开发过程中可能还需要考虑更多因素,例如安全性、电源管理等。
阅读全文