# Bluetooth mouse and keyboard

How a Kode Dot serves HID over GATT so a computer or a phone uses it as a Bluetooth mouse, a keyboard or both: the choice, the bonds, the pairing code, the reports and the console verbs.

## What it is

A Kode Dot can be a Bluetooth mouse, a keyboard, or both, for a computer or a phone. The computer pairs with it from its own Bluetooth settings, with nothing to install, and the app then sends mouse movements, clicks and keys.

**AO_Radio** serves the HID service over GATT (HID over GATT, service `0x1812`) beside the console's service. Nothing of it exists until it is asked for: an app chooses the kinds with `kode_ble_hid_select()`, and KodeOS reads its stored `ble_hid` setting. A firmware that asks for nothing keeps the GATT table and the advert it had.

HID needs `CONFIG_KODEOS_BLE_CONSOLE_PAIRING=y`, the default, because the service uses the console's security. Without it every kind is refused.

## How it is connected

```mermaid
flowchart LR
  app["app task<br/>kode_ble_hid_*()"] --> sys["kode_sys_ble_hid_*()"]
  ao2["app AO"] --> sys
  sys -- "claim a slot,<br/>BLE_HID_REPORT_REQ_SIG" --> radio["AO_Radio"]
  radio -- "kdrv_ble_hid_push(), kick()" --> drv["kdrv_ble<br/>ring of 16"]
  drv -- "notification" --> c5["ESP32-C5"]
  c5 -- "Bluetooth" --> host["computer or phone"]
  power["AO_Power"] -- "POWER_EVT_SIG" --> radio
  class radio ao
  class c5 chip
  class app,ao2 app
```

*From a call to the computer*

A call claims a slot of the driver's ring from the calling task (`kdrv_ble_hid_claim()`) and posts the report to AO_Radio in a `BleHidReportEvt` (`kind`, `tap`, `len`, `data`). AO_Radio alone pushes the report into the ring and kicks the link, and NimBLE's host task sends the notification. The report reaches the computer once it has subscribed to the reports of that kind. A link that ends empties the ring.

AO_Radio also hands every charge reading of `POWER_EVT_SIG` to the Battery service, so the computer shows the Kode Dot's battery.

### The choice of kinds

The radio reads the choice **once**, when it registers its GATT table at Bluetooth's first start in the boot. From then the choice is fixed until the next boot.

- **In an app**, call `kode_ble_hid_select()` as the first call to the SDK, so the choice is kept before anything starts. It is not stored: the app makes the call at each start. Bluetooth switched off in Settings is not an error, and the choice waits for it to come on.
- **In KodeOS**, the setting `ble_hid` (`off`, `mouse`, `keyboard` or `both`) is stored in `kset/ble_hid` and applied at boot. A set before Bluetooth's first start is served at once and logs `ble_hid <word> (stored): served when Bluetooth starts`. A set after it holds from the next boot and logs `ble_hid <word> (stored): it holds from the next boot, Bluetooth has registered its table`. The row exists only in the OS role, and a set is taken from the cable or Bluetooth alone, not from the Kode channel or the scheduler.

### What the board serves

With HID chosen, the GATT table carries three more services after the console's and the app's: HID (`0x1812`) with the SDK's own report map, Battery, and Device Information with `Kode` as the maker. The advert carries `0x1812` and the appearance beside the console's UUID, in place of its transmit power:

| Kinds | Appearance |
| --- | --- |
| Mouse | `0x03C2`, a mouse |
| Keyboard | `0x03C1`, a keyboard |
| Both | `0x03C0`, a generic HID device |

**The board takes one link.** While a computer uses it as a mouse or a keyboard, neither the console nor a phone gets in. A computer bonded as a host comes back by itself whenever it sees the board. A firmware that serves no HID hangs up on such a host once its link is encrypted, so the one link stays free for everything else.

### Bonds: a host or the console

A bond belongs to the console or to the HID service, by what the board was when the bond was made, and opens that one alone:

- A device that paired while the board served HID is a **host**. It gets the reports and never the console.
- A device that paired while the board did not serve HID, such as the phone paired for the console, has the console and is never sent a report, whichever firmware made the bond.

The service that refuses answers ATT's Insufficient Authorization. A device changes its use by pairing again: to use the console from a computer that is a host, forget the board on the computer and pair again while no HID is served.

The board keeps up to three hosts in the NVS namespace `kble_hid`, key `hosts`, and the print of the GATT table it registered last in key `table`. When the table changes between boots, the subscriptions the bonds stored are forgotten, except Service Changed, which tells each bond to read the table again.

### Pairing

Security is the console's, so with the passkey (`KODEOS_BLE_PAIRING_PASSKEY`, the default) a host pairs with a six-digit code shown on the Kode Dot.

- **In KodeOS**, the Bluetooth page's Pair new device, or the console's `ble_pair`, shows the board for five minutes (`internals/gui/sheets`).
- **In an app**, serving HID is the one case in which a new device pairs outside KodeOS. `kode_ble_pair_open()` shows the board for five minutes. The code to show arrives as the event `ble_pair_code`, and `ble_pair_done` says how the pairing ended. With a device connected, the five minutes start when it leaves. An app that serves no HID pairs nothing: it serves the phones bonded in KodeOS.

The bond is kept, so a computer pairs once.

### The reports

| Report | Bytes | Layout |
| --- | --- | --- |
| Mouse | 4 (`KDRV_BLE_HID_MOUSE_LEN`) | Buttons (bit 0 left, 1 right, 2 middle), x, y, wheel. Movement and wheel are relative, -127 to 127 |
| Keyboard | 8 (`KDRV_BLE_HID_KEYS_LEN`) | The eight modifier bits (left Control first), a zero byte, six keys. A key is a usage ID from 1 to 101 (`0x65`): 4 is `a` |

**A report never waits.** It is queued for the link, `KODE_BLE_HID_RING_SLOTS` (16) at most, and a full queue fails the call. A keyboard report says which keys are down now, so the report that lets them go must follow it. That report, all zeroes, is never refused for want of room: the driver owes it and sends it behind what is queued (`kdrv_ble_hid_owe()`), so a key is never left down. `kode_ble_hid_tap()` and `kode_ble_hid_click()` press and let go in one call, which takes two slots, both or neither.

A report also leaves 16 blocks of the small event pool free for the other Active Objects. Without that room, the call fails as with a full ring.

## Specifications

### The facade (`kode.h`)

For `app_main()` and tasks of your own. Each call returns at once.

| Call | What it does |
| --- | --- |
| `bool kode_ble_hid_select(uint8_t kinds)` | `KODE_BLE_HID_MOUSE` (`0x01`), `KODE_BLE_HID_KEYBOARD` (`0x02`), both, or 0 for neither. False for a kind that does not exist, once the table is registered, or in a firmware without the console's pairing |
| `bool kode_ble_hid_ready(void)` | True when a computer is connected and takes the reports of every kind chosen. Sets no error |
| `bool kode_ble_hid_mouse(uint8_t buttons, int8_t dx, int8_t dy, int8_t wheel)` | One mouse report. False when Bluetooth is off in Settings, the mouse is not chosen, no computer takes its reports, or the queue is full. A report of no button and no movement never fails for a full queue |
| `bool kode_ble_hid_click(uint8_t buttons)` | Presses the buttons and lets them go. False for no button too |
| `bool kode_ble_hid_keys(uint8_t modifiers, const uint8_t *keys)` | One keyboard report: up to `KODE_BLE_HID_KEYS_MAX` (6) usage IDs held down, 0 for none, copied. NULL lets every key go |
| `bool kode_ble_hid_tap(uint8_t modifiers, uint8_t key)` | Types one key: presses it with its modifiers and lets it go. False for a key out of range too |
| `bool kode_ble_pair_open(void)` | Opens five minutes to pair. False when Bluetooth is off in Settings, no kind is chosen, or the radio has no room for the request |

Every false return leaves `kode_error()` saying why. The events `ble_pair_code` (the code as the value, and as six digits of text with the leading zeroes) and `ble_pair_done` (value 1 when the device is bonded, 0 when it is not) are named by `KODE_EVENT_BLE_PAIR_CODE` and `KODE_EVENT_BLE_PAIR_DONE` (`sdk/kode`).

### The commands (`kode_sys.h`)

For an Active Object of the app. The bits and limits are the same, as `KODE_SYS_BLE_HID_*`.

| Call | Answers |
| --- | --- |
| `kode_sys_ble_hid_select(kinds)` | `KODE_OK`, or `KODE_DENIED` as above |
| `kode_sys_ble_hid_ready()` | A `bool`, from any task |
| `kode_sys_ble_hid_mouse(buttons, dx, dy, wheel)`, `kode_sys_ble_hid_keys(modifiers, keys)` | `KODE_OK` when queued. `KODE_DENIED` when the kind is not served or no host is subscribed to it. `KODE_NO_RESOURCES` when the ring is full: send it again, or the sum |
| `kode_sys_ble_hid_click(buttons)`, `kode_sys_ble_hid_tap(modifiers, key)` | As above, two reports, both queued or neither. `KODE_DENIED` for no button or a key out of range |
| `kode_sys_ble_pair_open()` | `KODE_OK` when asked. `KODE_DENIED` in an app that serves no HID, or without `CONFIG_KODEOS_BLE`. `KODE_NO_RESOURCES` when AO_Radio's queue had no room, and nothing was asked |
| `kode_sys_ble_pair_subscribe(me)` | Subscribes the Active Object to `BLE_PAIR_SIG` and links AO_Radio. `KODE_DENIED` for NULL, an Active Object not started, or without `CONFIG_KODEOS_BLE` |

`BLE_PAIR_SIG` carries a `kode_sys_ble_pair_t` (`BlePairEvt`): `phase` is `KODE_SYS_BLE_PAIR_SHOW` (1, show `passkey`, six digits), `KODE_SYS_BLE_PAIR_DONE` (2, `outcome` says how it ended, `KODE_SYS_BLE_PAIR_OK` = 0 for bonded) or `KODE_SYS_BLE_PAIR_REFUSED` (3, a device asked outside the time to pair and was hung up on, with no code). In a refusal `outcome` says why: 5, the driver's `KDRV_BLE_PAIR_APP_CLOSED`, in an app that is not pairing, and 4, `KDRV_BLE_PAIR_HIDDEN`, in KodeOS. A phone retries, so a refusal is told at most once in `KODE_BLE_PAIR_REFUSED_QUIET_MS` (10 s), and it opens nothing. The standard layer makes no event of it: `ble_pair_code` and `ble_pair_done` come from SHOW and DONE alone.

### The console

| Verb | What it does |
| --- | --- |
| `ble_hid_info` | `>\|ble_hid kinds=off\|mouse\|keyboard\|both ready=on\|off sent=<n> dropped=<n>` then `>ok`. `sent` counts the reports the link took since boot, `dropped` the reports queued or claimed and never sent |
| `ble_hid_mouse [buttons=<0..7>] [right=] [left=] [down=] [up=] [hold=on]` | One mouse report. Each step is 0 to 127. Buttons are pressed and let go unless `hold=on` |
| `ble_hid_wheel [up=] [down=]` | Turns the wheel, 0 to 127. Every button is let go |
| `ble_hid_key code=<1..101> [mods=<0..255>]` | Presses one key with its modifiers and lets it go |
| `config key="ble_hid" value=off\|mouse\|keyboard\|both` | The stored choice in KodeOS (`internals/settings`) |

The three report verbs run from the cable alone: Bluetooth gets `>err code=5 msg=cable`, the Kode channel `msg=net` and the scheduler `msg=sched`. They answer `>ok`, `>err code=4 msg=busy` for a full ring, `>err code=5 msg=off` when no HID is served, `msg=kind` when the kind is not served and `msg=no_host` when no host takes its reports. `ble_pair` answers `>err code=4 msg=busy` when AO_Radio's queue has no room for the request.

## Gotchas

> **WARNING**
>
> **`kode_ble_hid_select()` returns false.** Bluetooth registered its table already, and the choice holds from the next boot. Make it the first call of the app, before anything starts Bluetooth.

> **WARNING**
>
> **The phone of the console gets no reports, and the computer gets no console.** Each bond has one use, set by what the board was when the device paired. Forget the board on the device and pair again while the board is the other thing.

> **NOTE**
>
> **The console cannot connect while a computer holds the link.** The board has one link, and a host comes back whenever it sees the board. Switch Bluetooth off on the computer, or run a firmware that serves no HID: it hangs up on the host.

> **NOTE**
>
> **A key stays down on the computer.** A keyboard report holds the keys it names until the next one. Send the release, `kode_ble_hid_keys(0, NULL)`, or use `kode_ble_hid_tap()`, which sends both.

## Example code

No runnable example is available for this page. The console's `ble_hid_mouse`, `ble_hid_wheel` and `ble_hid_key` drive the same reports from the bench once `config key="ble_hid"` has chosen a kind and a computer has paired.

## In the SDK

- [`components/kaos/radio/src/radio_hid.c`](https://github.com/kodediy/kode-sdk/blob/main/components/kaos/radio/src/radio_hid.c): AO_Radio's door for the reports and the stored choice.
- [`components/kdrv/radio/include/kdrv_ble_hid.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kdrv/radio/include/kdrv_ble_hid.h): the choice, the reports, the ring and the pairing door.
- [`kode.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kode/include/kode.h) and [`kode_sys.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kode_sys/include/kode_sys.h): the calls of this page.
