# AO_Radio

Owns the ESP32-C5 of a Kode Dot: the link, Wi-Fi and BLE as services, two workers, C5 updates and parking the radio for a jump.

## What it is

A Kode Dot has two processors. The P4 runs kodeOS. The ESP32-C5 holds the only radio. **AO_Radio** owns the C5 as a whole: its EN line, the esp-hosted link to it over SDIO, its GPIOs (reached by RPC), the Wi-Fi and the BLE controller that run on its radio, its flash, and its row of the production test.

Everything reaches the C5 through one RPC channel that carries one request at a time. So AO_Radio runs **one job at a time** and refuses every other request, and each refusal comes with an answer. A scan is the one exception: the newest request of a radio ends that radio's scan in flight (below). Nothing in AO_Radio blocks: a Wi-Fi scan takes about 38 s and a C5 update more than a minute, and both run as jobs on worker tasks that AO_Radio owns.

Wi-Fi and BLE are services, each with a desired state kept as a flag. Both use the link, and switching one on or off in the settings does not start or end the link by itself. Link, driver and chip are on `sdk/kdrv/radio` and `sdk/kdrv/c5`. The network on top of Wi-Fi is `sdk/kaos/net`.

## How it is connected

```mermaid
flowchart LR
  req["Console, facade<br/>AO_Net, AO_Boot"]
  subgraph p4["On the P4"]
    ao["AO_Radio<br/>priority 4"] -- "kdrv_radio_run()" --> w1["radio_worker"]
    ao -- "kdrv_c5svc_send()" --> w2["radio_svc"]
    sto["AO_Storage"]
  end
  req -- "WIFI_*, BLE_*,<br/>RADIO_*_REQ_SIG" --> ao
  w1 -- "esp-hosted, SDIO" --> c5["ESP32-C5"]
  w2 -- "esp-hosted, SDIO" --> c5
  ao -- "unmount, remount" --> sto
  ao -- "RADIO_STATE_SIG,<br/>WIFI_STATE_SIG,<br/>BLE_STATE_SIG" --> subs["Subscribers"]
  class ao,sto ao
  class c5 chip
  class subs app
```

*AO_Radio, its workers and the C5*

### Priority and start

AO_Radio claims `KBSP_RES_C5`. It runs at priority 4 (`KODE_PRIO_RADIO`) with a 16-event queue (`KQP_RADIO_QUEUE_LEN`) and a 6144-byte stack, and it shares that level with the console reader task and its own two workers. All of them move data and block, so all sit low, round-robin by FreeRTOS. Only AO_Net (2) and AO_Gui (3) are lower.

QP answers a full queue with a reset, so every post from another task leaves slots free. Every request door (a request from the console, the facade or another Active Object) stops at half of the queue, 8 slots (`KQP_RADIO_POST_MARGIN`). With no room the door refuses the request, logs `AO_Radio's queue is full; <request> is refused` and returns false. Its caller then answers its own asker, so most console verbs answer `>err code=4 msg=busy` and the c5 row fails at once.

A scan knock and a KODE answer leave 2 slots free (`KQP_RADIO_DROP_MARGIN`) and are dropped when refused. The next knock or the end of the sweep lists what a refused knock would have, and the deadline of a request tells its asker that its answer was lost. The BLE state and its ask, the pairing note, the lost link, the knock of the advertisement stream and the HID wake-up leave 2 slots free (`KQP_RADIO_KNOCK_MARGIN`) and are owed when refused, posted again once there is room. What AO_Radio cannot refuse posts with no margin into the slots the others leave: its posts to itself, its time events, the answers to its own asks and the publishes it subscribes to (`LOWPOWER_ROUND_SIG`, `LOWPOWER_STATE_SIG`, `C5_RUN_REQ_SIG`, `C5_AMP_OFF_SIG`, `POWER_EVT_SIG`).

`kode_init()` starts it after AO_Storage, since the link walks the microSD card between its mount paths by posting to AO_Storage, and before AO_Net, whose initial transition posts a question to it. The Kconfig options for AO_Radio:

| Option | What it does |
| --- | --- |
| `KODEOS_RADIO` | Compiles AO_Radio |
| `KODEOS_WIFI`, `KODEOS_BLE` | Switch the services |
| `KODEOS_WIFI_AUTOJOIN` | The join at link-up |
| `KODEOS_C5_HOLD` | The reset hold |
| `KODE_BLE_APP_VALUE_MAX` | Bytes of one value of the app's Bluetooth service, 20 to 512, default 244 |
| `KODE_BLE_ADVERTISE_APP_SERVICE` | The advert carries the app's service UUID instead of the console's. Off by default |

### The shared SD controller

The C5 and the microSD card share one SDMMC controller of the P4. With the link up the card is mounted in hosted mode, without it on the plain path. So AO_Radio asks AO_Storage to unmount before it touches the C5 and to mount again after, and each unmount that must come first is asked with an answer.

### States

```mermaid
stateDiagram-v2
  [*] --> Radio_off
  [*] --> Radio_starting: a service is wanted
  Radio_off --> Radio_starting: radio_up, a service start, the row
  Radio_starting --> Radio_up: CONNECT_DONE ok, card remounted
  Radio_starting --> Radio_failed: CONNECT_DONE failed
  Radio_up --> Radio_stopping: radio_down, or nothing uses the link
  Radio_stopping --> Radio_off: DISCONNECT_DONE
  Radio_up --> Radio_failed: LINK_LOST
  Radio_failed --> Radio_starting: radio_up
  Radio_up --> Radio_autojoin: WIFI_AUTO_REQ_SIG
  Radio_autojoin --> Radio_up: round over
  Radio_up --> Radio_updating: dst=c5 install
  Radio_updating --> Radio_off: C5 activated, link gone
  Radio_updating --> Radio_up: failure
```

*AO_Radio states*

`Radio_down` is the parent of `Radio_off`, `Radio_starting`, `Radio_stopping` and `Radio_failed`. `Radio_up` is the parent of `Radio_updating` and `Radio_autojoin`.

A request that needs the link has one right answer when it is down, written once in `Radio_down`: a scan with no link gets an empty scan end with `ok=false`, and never a timeout. The states mirror `kradio_link_t` (`KRADIO_OFF`, `_STARTING`, `_UP`, `_STOPPING`, `_FAILED`), and every change publishes `RADIO_STATE_SIG`.

### The workers

The two workers are `kqp_worker` tasks at `KODE_PRIO_RADIO`, and a worker runs one job and decides nothing.

| Worker | Stack | Runs | Done event |
| --- | --- | --- | --- |
| `radio_worker` | 6144 bytes, internal RAM | `kdrv_radio_run()`: link, scans, joins, firmware pushes, BLE calls | `RADIO_JOB_SIG` |
| `radio_svc` | 8192 bytes, PSRAM | `kdrv_c5svc_send()` to the C5's KODE services: vault, identity, BLE keys, `INFO`. Queue of two requests per service | `RADIO_SVC_JOB_SIG` |

The stack of `radio_worker` is in internal RAM because link bring-up calls `khal_nvs_init()` and the BLE jobs use NimBLE's bond store in NVS, and a PSRAM stack must never touch the internal flash. Sends have their own worker because a send is one RPC and the C5 serves RPCs one at a time. Behind a 37 s dual-band scan, an identity answer would arrive that much late.

`winflight` is set at submit and cleared only by the done event with the matching sequence number, so a job is never submitted over one still inside the worker. `busy` is policy: the channel is occupied by a job or a chain of jobs.

Every job has a guard of 180 s (`KODE_RADIO_GUARD_MS`), and a BLE listen adds its length. A KODE send has its own 60 s guard (`KODE_RADIO_SVC_SEND_GUARD_MS`) and then a 3 s wait for its answer. An expired guard answers `KODE_TIMEOUT` and leaves the worker busy. The loss of the link arrives as `RADIO_LINK_LOST_SIG` and is no job's outcome.

`DISCONNECT` is never submitted while a send is inside `radio_svc`, because tearing down destroys the semaphore the send sleeps on. It is owed, and the last send back pays it.

### Starting the link

`radio_begin_connect()` switches `kdrv_sd` to hosted mode, asks AO_Storage to unmount with an answer, and only then submits `KDRV_RADIO_JOB_CONNECT`. A card still mounted at the answer (a transfer holds it) is asked again every 500 ms for 10 s (`RADIO_UNMOUNT_RETRY_MS`, `RADIO_UNMOUNT_WAIT_MS`). After that the link does not start, and the C5 is untouched.

After `CONNECT_DONE` the card is remounted, and AO_Radio waits for `STORAGE_CMD_RSP_SIG` before it enters `Radio_up`. An RPC to the C5 while the card is being probed leaves the C5 mute for the rest of the boot. So "up" means link up and card back.

### Autostart and the flags

At start `Radio_initial` reads `kset/wifi` and `kset/ble`. A flag never stored takes the build default: Wi-Fi off (`KODEOS_WIFI_DEFAULT_ON`), BLE on (`KODEOS_BLE_DEFAULT_ON`). `KODEOS_BLE_AT_BOOT` forces BLE on, and without `KODEOS_WIFI` the Wi-Fi flag is false. If either is wanted, AO_Radio goes straight to `Radio_starting`.

AO_Radio is the only writer of the flags, through `radio_flag_set()`, and only a change is stored. A refusal is about the present and the flag about every moment after, so a busy check never decides a flag. A refused request becomes a debt: `wifi_stop_pending`, `wifi_start_pending`, `ble_stop_pending` and `ble_start_pending`, paid by `radio_settle()` when a job ends.

Setting a flag cancels the opposite debt, since someone often switches a service off and on during one job. `Radio_off` and `Radio_failed` clear all four.

`radio_settle()` pays an owed autojoin by posting it. With no remembered network that request ends without a job, so it settles again itself and whatever waited behind it is paid at once.

### The link ends when nothing uses it

Four things use the link:

1. A wanted service.
2. A direct ask (`link_asked`, set by `radio_up`, the row or a C5 update).
3. A job in flight.
4. With `KODEOS_C5_HOLD`, a sound.

When a job ends and none holds, `radio_settle()` posts `RADIO_UNUSED_SIG` to itself and `Radio_up` takes the `radio_down` path.

`wifi_down` stops the station. `ble_down` makes the host quiet, and the host keeps running because NimBLE starts once per boot. Switching a service on in `Radio_off` starts the link again in about 3 s. Code that needs the link without a service must call `radio_up_request()`.

`LINK_LOST` comes as `KODE_ERROR` (transport died) or `KODE_TIMEOUT` (the C5 went mute). Both unmount the card and order a `DISCONNECT`, so `Radio_failed` always means a cleanly torn-down link. A mute C5 is reset once by a rebuild without a request (`relink_owed`).

### Holding the C5 in reset

`KODEOS_C5_HOLD` is on in kodeOS. The entry of `Radio_off` holds the C5 when neither service is wanted and no sound asked for it.

In reset it draws nothing and the amplifier its firmware enables is shut down with it. `C5_RUN_REQ_SIG`, which AO_Audio publishes before a boot's first sound, lets it go and starts a one-shot `KODE_C5_BOOT_MS` (600 ms), then publishes `C5_RUNNING_SIG`. After that the C5 is not held again in that boot. `info` reports `power=held` or `power=running`.

### The reconcile

The entry of `Radio_up` starts a chain that starts what is wanted: first, after an adoption (below), nothing; then BLE (stack, then advert); then Wi-Fi through `wifi_auto_request()`. With autojoin compiled out or `wifi_join` off it only publishes the state, because "enabled and idle until told which network" is a real answer.

A step's `*_DONE` passes the turn only while `recon == RECON_BLE`, and `radio_reconcile_retry()` unsticks a chain whose BLE start was refused because a scan held the channel. An entry action never starts a job, so the entry posts requests to AO_Radio itself.

### Keeping BLE on the air

`radio_ble_adv_reconcile()` keeps one rule: BLE flag on, nobody connected, stack idle, therefore advertising. It runs on `BLE_LINK_SIG` (after the state is published), when a BLE start job ends, and last after every settled job. No timer turns Bluetooth off.

The rule also decides how the board shows itself. A board with no bond is visible. A board with a bond is hidden: the advert stays connectable for the devices that know the board, but it carries no name and no discoverable flag, and a new pairing is refused. `ble_pair_open_request()` (the Bluetooth page's Pair new device, the verb `ble_pair`) makes it visible for 5 minutes (`RADIO_BLE_PAIR_MS`), until a device pairs, or until Forget all leaves it with no bond. The board has one link, so with a device connected nothing can go on the air: the 5 minutes start when that device leaves, and `ble_info` says `pair=wait` until then. An advert on the air that shows the board the wrong way is stopped, and its `IDLE` brings the right one. A lab build (`KODEOS_BLE_AT_BOOT`) and an app that serves Bluetooth of its own never hide.

A pairing refused on the glass (`ble_pair_reject_request()`, which the pairing card calls) is said at once in every state of AO_Radio, a C5 update included, because the refusal takes no lock of NimBLE's. Only the hang-up on the peer takes NimBLE's host lock, which the radio worker can hold for seconds while it writes a key, so the hang-up is a job of that worker (`KDRV_RADIO_JOB_BLE_PAIR_REJECT`). AO_Radio owes it and sends it when the worker is free, or when the link comes back. A refused peer that finishes typing the code before the hang-up has its bond deleted and is hung up on by the driver.

**A pairing refused with no code is told.** The driver notes each new device it hangs up on before any code, with phase `KDRV_BLE_PAIR_REFUSED` and the cause in `outcome`: `KDRV_BLE_PAIR_HIDDEN` in KodeOS, where the board hides from new devices until Pair new device, and `KDRV_BLE_PAIR_APP_CLOSED` in an app that runs and is not pairing. It logs each try, `pairing refused: the board is hidden; Pair new device makes it visible` in KodeOS and `pairing refused: a new phone pairs in kodeOS; this app serves bonded phones` in an app. A phone retries a refused pairing several times, so AO_Radio publishes one `BLE_PAIR_SIG` and tells no other refusal for `KODE_BLE_PAIR_REFUSED_QUIET_MS` (10 s) from it. At debug level it logs `pairing refused: told`, then `pairing refused again within 10 s; not told again` for each one it keeps quiet. The notice changes nothing: the board stays hidden, or the app stays closed, and a new device pairs after a deliberate act. The note exists with `KODEOS_BLE_PAIRING_PASSKEY`.

The advert runs in legs. A leg is fast (`KDRV_BLE_ITVL_FAST`, about 150 ms) for 30 s (`RADIO_BLE_FAST_MS`) after somebody may be looking: Bluetooth switched on, Pair new device, or a bonded device that just left. Otherwise it is slow (`KDRV_BLE_ITVL_SLOW`, about 1 s) and has no end, except while Pair new device's time is what shows the board: then the leg ends with that time. At rest the advert stays slow.

A BLE scan listens `ms` long: 0 means 5000 and the range is 500 to 30000 (`KODE_BLE_SCAN_MIN_MS`, `_MAX_MS`). A length outside the range is refused with an end marker `ok = false`.

### Scans: the newest request wins

One scan somebody asked for is alive per radio, running or waiting for the worker. It is a listing on the bus (`wifi_scan_request()`, `ble_scan_request()`, the console's `wifi_scan` and `ble_scan`) or an asked scan (`wifi_scan_ask()`, `ble_scan_ask()` and their blocking forms, which `kode_sys.h` and `kode.h` wrap). The newest request of a radio wins:

- A Wi-Fi scan, a join, Wi-Fi switched off, or Wi-Fi switched on from off, ends the Wi-Fi scan in flight.
- A Bluetooth listen, the BLE advertisement stream, or Bluetooth switched on or off, ends the Bluetooth listen in flight.
- A request of one radio ends no scan of the other.

The asker of the scan that ended is answered at that moment. An asked scan gets its answer with `rc` `KODE_CANCELLED`. A listing gets an end that says `cut`, with the entries it had published before it. A Wi-Fi listing ended by a newer `wifi_scan` gets `WIFI_SCAN_AGAIN_SIG` instead, and the new sweep's end closes both. The sweep or the listen the worker still holds is asked to end (a sweep after its step on the air, a listen at once), its outcome is dropped, and the newer request starts when the worker is back.

Each listing request takes a generation, which its entries and its end carry (`WifiScanEndEvt.gen`). A listener that waits for its own request skips what belongs to a listing before it that is still in its queue. An asker that scans again at every answer waits for its own end first: one that asks again at once after `KODE_CANCELLED` ends the scan that replaced it, and two of them never let a sweep finish.

Some work is never cut:

| Work in flight | A scan asked behind it |
| --- | --- |
| A join somebody asked for | Waits for it. The join ends in seconds |
| A scan of the other radio | Answered busy: `busy` in the end, `KODE_NO_RESOURCES` for an asked scan |
| The automatic join, the board's own round over the remembered networks, running or owed | Answered busy |
| The production row, the radio check | Answered busy |
| An install or a C5 update | Answered busy |

On the console a valid line from the port that asked for a scan takes the scan's place: `wifi_scan`, `wifi_join` or `wifi_down` behind `wifi_scan`, and `ble_scan` or `ble_down` behind `ble_scan`. The scan is closed first with `>err code=5 msg=stopped`, then the new line runs. A line that is not valid leaves the scan running.

`wifi_scan_stop_request()` ends the Wi-Fi listing in flight after its step on the air. The driver's sweep reads a flag between its seven steps, so the step that is running finishes first and the networks heard so far are listed. The end marker then carries `cut` with `ok = false`, and the console closes `wifi_scan` with `>err code=5 msg=stopped`. The verb `wifi_scan_stop` runs while `wifi_scan` holds the console, begins no command of its own and answers `>ok`, or `>err code=4 msg=busy` when the request is refused. Only a listing is cut this way: an asked scan, the automatic round, the row and the radio check run to their end. With no listing to stop, the log says so and nothing changes. The link's loss withdraws the flag, so it never cuts the first sweep of the next link.

### The app's Bluetooth service

An app can serve one GATT service of its own beside the console's. It declares it at file scope with `KODE_BLE_SERVICE()` (`kode.h`): a UUID and up to four characteristics (`KODE_BLE_CHARACTERISTICS_MAX`), each with the properties `KODE_BLE_READ`, `KODE_BLE_WRITE`, `KODE_BLE_NOTIFY` and `KODE_BLE_QUEUED`. AO_Radio finds the table when Bluetooth starts and serves it with the security of the console. The service needs `KODEOS_BLE_CONSOLE`, whose pairing it uses. A table the radio cannot serve is left out with one log line, and the calls on it fail saying why.

`kode_ble_set_value()`, `kode_ble_notify()` and `kode_ble_queue_push()` reach AO_Radio as `BLE_APP_VALUE_REQ_SIG`, and the calling task waits for the answer. A write by a phone is published as `BLE_APP_WRITE_SIG`. A phone that connects or leaves is `BLE_APP_LINK_SIG`.

The longest value is `KODE_BLE_APP_VALUE_MAX`, 20 to 512 bytes and 244 by default, one notification at an MTU of 247. A larger value travels in a tier of events of its own, in PSRAM, and the host asks the central for an MTU of the value plus 3, at most 451. A read or a write carries a whole value at any MTU, as a long read or a long write. A notification carries at most 448 bytes: a longer one is dropped and the value stays for a read.

A `KODE_BLE_QUEUED` characteristic holds up to 8 values (`KODE_BLE_QUEUE_SLOTS`) and gives each read the oldest, for a phone that reads until a read comes back empty. A value longer than one read is read in parts and taken with its last part. `BLE_APP_TAKEN_SIG` says how many values are left, so the app refills without looking, and `kode_ble_queue_room()` reads the room without waiting. A push onto a full queue fails. A phone that connects or leaves empties the queue.

`KODE_BLE_BATTERY_SERVICE()` adds the standard Battery service (0x180F) with Battery Level (0x2A19), one byte from 0 to 100 that a phone reads or subscribes to, behind the same permissions. AO_Radio subscribes to `POWER_EVT_SIG` only when the app declared it, and hands each charge reading to the driver unless a job of its worker is running. The next reading brings it.

With `KODE_BLE_ADVERTISE_APP_SERVICE` (off by default) the advert carries the UUID of the app's service instead of the console's, for phone apps that scan with a filter on it. Only one 128-bit UUID fits, so a client that filters on the console's UUID stops finding the board. With no service declared the advert stays as it is.

### Bluetooth mouse and keyboard

In the kodeOS role AO_Radio can also serve the standard HID service, so the board works as a Bluetooth mouse, a keyboard or both for a computer or a phone. The `ble_hid` setting chooses it, `ble_hid_report_post()` (`BLE_HID_REPORT_REQ_SIG`) queues a report for the host, and bonds belong to the console or to HID. `sdk/kaos/ble-hid` describes the service, the bonds, the reports and their calls.

### Autojoin

Autojoin scans first and joins after, since a join without a scan costs 20 s per network that is elsewhere. The remembered networks are the C5's vault, and AO_Radio keeps their names only. `auto_pick()` chooses the strongest remembered network among the strongest 24 the sweep heard, skipping those already tried this round (`tried` is a bitmask, so `KDRV_WIFI_SCAN_MAX` stays under 32).

A join is three steps: ready the P4 interface, `KODE_VAULT_JOIN` on the C5, wait for the address. Credentials are stored only after a join worked and `remember` is set, and AO_Radio clears its copy of the password. Every outcome checks `wifi_want` first, and every round ends in `auto_finish()`, which publishes the state and settles.

The settings `wifi_join` (default is the build option) and `wifi_ps` (default on) are stored as `kset/wifi_join` and `kset/wifi_ps`.

### Fast mode

`wifi_fast_request(on)` posts a static event, so it needs no pool block, and returns false when the queue has no room for it. `on` means no Wi-Fi power save on the C5, which AO_Net asks for while commands arrive on the Kode channel or one of its workers has a job. AO_Net asks again after 100 ms when AO_Radio had no room for the wish (`internals/kode-channel`). AO_Radio keeps the wish in `fast_want` and what it believes in `ps_fast`, and submits one `WIFI_PS` job when they differ and the channel is free.

A job the C5 refuses logs `the C5 would not change the power save`. Leaving `Radio_up` clears both, since a reset C5 boots on the default.

### Parking the C5 for a jump

Before a deliberate restart (an app, kodeOS, an update), AO_Boot sends `RADIO_PARK_REQ_SIG` with the target role. AO_Radio answers exactly once, in every state, with `BOOT_RADIO_PARKED_SIG`, which means it has done with the C5, parked or not. A park request with no pool block or no room in the queue is answered at once, as a park the C5 refused. With the link up, `PARK_QUIET` submits `BLE_QUIET` so a phone sees the disconnect now. `PARK_ASKED` sends `SELF/PARK` to the C5, and then `radio_park_end()` answers.

The 3 s service deadline applies.

Only a `KODE_ST_OK`, the station associated, leaves a handover note (`kdrv_radio_note_leave(target)`) and calls `kdrv_wifi_keep_station_on_restart()`. Any other ending leaves none, and the next firmware resets the C5. `PARK_DONE` is terminal until the reset, and AO_Radio then asks the C5 nothing.

At the next boot with a note, `kdrv_radio_adopted()` is true and, if Wi-Fi is wanted, `KDRV_RADIO_JOB_WIFI_ADOPT` is the first reconcile step. A failed adoption logs `adoption failed (…): joining` and the usual round follows.

### KODE services on the C5

`ID_SIGN_REQ_SIG` signs the cloud's challenge. `ID_REQ_SIG` reads the certificate pair, makes the CSR, puts a part of the pair or locks. `C5_WIPE_REQ_SIG` forgets the vault, the BLE keys and the bonds in three steps, and the identity stays.

Each is answered always, a refusal included: `ID_SIGN_RSP_SIG`, `ID_PART_SIG` records of up to 144 bytes with an `ID_END_SIG`, `C5_WIPE_RSP_SIG`. At every link AO_Radio asks the C5 for `INFO` and then the vault's `LIST`.

### Wi-Fi frames

The C5 can listen to one Wi-Fi channel and tell the P4 about the frames it hears. AO_Radio offers that to one Active Object at a time through `wifi_frames_request(who, on, channel)`, which `kode_sys_wifi_frames()` wraps for an app. Channel 0 stays where the radio is; 1 to 177 names a channel. It is receive only: nothing is sent, and the station never leaves its network to listen. While the station is joined, only channel 0 or the network's own channel is heard.

Every request is answered to `who` with `WIFI_FRAMES_STATE_SIG`, in every state of the link: `on`, the radio's `channel`, `joined` and `why`. While it listens, `who` gets a `WIFI_FRAMES_TICK_SIG` for each 100 ms in which a frame was heard (frames heard since the start, management and data frames in the period, the strongest level, frames lost), and after it one `WIFI_FRAME_SIG` per frame handed over. A frame carries its channel, level, frame control, three addresses, its length on the air and up to 48 bytes after its MAC header (`head`, with `head_len` the bytes kept). In a beacon those are 12 fixed bytes, the capabilities at offset 10 with privacy in their bit 4, then the element with the network's name. `addr3` is the network's address in a management frame, and in a data frame the one its To DS and From DS bits name. A data frame keeps no head (`head_len` 0), and a C5 whose firmware predates the longer head keeps 8 bytes and no third address. All three signals are posted to `who`, never published. Ticks and frames leave `KQP_FRAMES_MARGIN` (4) slots of its queue free, and what does not fit is counted in the next tick's `dropped`.

| `why` | The answer means |
| --- | --- |
| `KWIFI_FRAMES_OK` | Listening, or stopped as asked |
| `KWIFI_FRAMES_NO_LINK` | The link is down, or the request could not be sent or was not answered in time |
| `KWIFI_FRAMES_NO_SERVICE` | The C5's firmware does not carry the service. It answers the request `BAD_REQUEST` |
| `KWIFI_FRAMES_WIFI_OFF` | Wi-Fi is not started, or it stopped under the stream |
| `KWIFI_FRAMES_JOINED` | The station is joined and the channel asked is not its own |
| `KWIFI_FRAMES_CHANNEL` | The radio refused the channel |
| `KWIFI_FRAMES_BUSY` | Another Active Object listens, the service's one request is still out, or a C5 update runs |
| `KWIFI_FRAMES_MEMORY` | No room on the C5 for its queue or task, or on the P4 for the ring |
| `KWIFI_FRAMES_RESTING` | The board is going to rest |

A second asker is answered busy, and its stop changes nothing. AO_Radio ends a stream itself, with a stop to the C5 and an answer to the asker, before work the stream would not survive: a round of the board's rest to ASLEEP (`RESTING`), Wi-Fi stopped or a join, which may restart the station (`WIFI_OFF`), and a C5 update (`BUSY`). While AO_Radio joins a network by itself, a start that names a channel is refused busy, and channel 0 is accepted.

The C5's batches arrive on esp-hosted's thread. `kdrv_frames` (`sdk/kdrv/radio`) copies them into a ring of 64 records in PSRAM, and the thread posts AO_Radio one static knock with `KQP_RADIO_POST_MARGIN` while none is waiting. The knock's handler drains the ring to the asker. A batch that arrives with nobody listening makes AO_Radio send one stop, which quiets a C5 that kept listening across a reset of the P4.

`dropped` counts only what the P4 lost: the ring's overflow, and frames the asker's queue or the pool had no room for. A frame the C5 could not queue, or one past the 8 a batch carries, is in `heard` and in no drop count. A tick's `channel` is the radio's when the C5 sent the batch, so frames heard while a scan visited other channels carry the channel at the period's end.

The console verb `wifi_frames ch=<0..177> ms=<100..10000>` listens that long, stops and prints one record, `>|frames ch= joined= heard= handed= dropped= mgmt= data= rssi_max=`, then `>ok`. It never prints an address or a payload.

### BLE advertisements heard

The host stack hears BLE advertisements while a passive scan with no end runs, one job of the radio worker (`kdrv_ble_hear()`). Interval and window are both 10 ms, so the radio listens all the time and a BLE console goes slower meanwhile. AO_Radio offers what it hears to one Active Object at a time through `ble_heard_request(who, on)`, in a build with `KODEOS_BLE`; an app asks with `kode_sys_ble_heard()`. Nothing is sent, and Bluetooth is never brought up: with it off in Settings or its stack down the answer is `KBLE_HEARD_BLE_OFF`.

Every request is answered to `who` with `BLE_HEARD_STATE_SIG` (`on`, `why`, and the totals `heard` and `dropped`), in every state of the link. While it listens, `who` gets one `BLE_HEARD_SIG` per advertisement: the address as printed, its type (`KBLE_HEARD_ADDR_PUBLIC` or `_RANDOM`), the level (`KBLE_HEARD_RSSI_NONE` when the controller gave none), the kind of packet (`KBLE_HEARD_PDU_*`), up to 31 bytes of payload as on the air, and the `dropped` total. The first comes after the answer that says the stream is on. Both are posted to `who`, never published. An advertisement leaves half of the asker's queue free (`KQP_HEARD_MARGIN` slots at least) and `KQP_HEARD_POOL_MARGIN` blocks of the medium tier, and what does not fit is dropped and counted, along with what the ring of 64 records in PSRAM refused (`kdrv_ble_heard`). Nothing asserts when the asker cannot keep up.

| `why` | The answer means |
| --- | --- |
| `KBLE_HEARD_OK` | Listening, or stopped as asked |
| `KBLE_HEARD_NO_LINK` | The link is down, or went down under the stream |
| `KBLE_HEARD_BLE_OFF` | Bluetooth is off in Settings, its stack is not up, or it went off |
| `KBLE_HEARD_BUSY` | Something that is not cut holds the radio: a Wi-Fi scan somebody asked for, the automatic join's round, the radio check, the production row, an install or an update. A stop the worker could not take also says `on` with `BUSY`: ask again |
| `KBLE_HEARD_MEMORY` | No room for the ring |
| `KBLE_HEARD_REFUSED` | The stack refused the scan, or ended it by itself |
| `KBLE_HEARD_RESTING` | A round of the board's rest to ASLEEP or OFF. A start is refused this way until the board is awake |
| `KBLE_HEARD_CANCELLED` | A newer Bluetooth request took the radio |

The stream is one more Bluetooth request beside a listen, so the newest wins. A start ends the listen somebody asked for, running or waiting, and goes when the worker is back. Another asker's start takes the stream without stopping the radio. A newer listen ends the stream in turn, and so do the radio check's name find and the production row's scan as they start. A Wi-Fi request ends nothing of it. A stream that was ended does not come back by itself: the asker asks again. A stop asked again while the first is still being served shares its answer, and a stop from an Active Object that does not hold the stream is answered off and changes nothing.

The console verb `ble_heard ms=<100..10000>` listens that long, stops and prints one record of counts and levels, `>|ble_heard heard= handed= dropped= conn= direct= scan= nonconn= rssi_max=`, then `>ok`. The four kind columns need not add up to `handed`: a packet of another kind counts in `handed` alone. It never prints an address, a name or a payload.

### Updating the C5

With `install dst=c5` the image is decoded whole into PSRAM, up to 1920 KB (`C5_IMAGE_MAX`, one slot of the C5), before the C5 is asked for anything. It is then pushed in 32 KB chunks (`C5_PUSH_CHUNK`) as `KDRV_RADIO_JOB_C5_WRITE`. Phases are `OPENING`, `DECODING`, `BEGIN`, `WRITING`, `FINISH` and `TEARDOWN`.

`C5_BEGIN` opens the session only after `kfw_end()` verified the digest and `kdrv_radio_image_header_ok()` accepted the header, which also checks the chip id. The card is unmounted first.

`FINISH_DONE` orders a `DISCONNECT`, and the update ends in `Radio_off` with the link off for the rest of the boot. Send `radio_up` and read `c5` to see the new image.

The C5 slave has rollback disabled, so a bad activated image leaves it unreachable. During an update AO_Radio refuses every Wi-Fi and BLE verb from an explicit list, because `busy` is false while it waits for storage.

Progress is `APP_FLASH_PROGRESS_SIG` with `what = KWRITE_C5`, at 0 % and then every percent, then one `APP_FLASH_DONE_SIG` or `APP_FLASH_FAIL_SIG` with reason `KFAIL_WRITE`. From the cable (`install src="terminal" dst=c5`) the receive needs neither the link nor the channel. AO_Radio asks AO_Log for raw mode, computes the CRC of each chunk, feeds the same decoder and acks each whole 4 KB chunk with `RECV_ACK_SIG`.

At the end it checks the CRC, `kfw_end()`, the header and `kapp_idf_desc()`. Its `>ok` means the C5 activated the image, and the C5 may still not run it.

### The production row

`test component=c5` has five steps on the one channel:

1. The link, if it is down.
2. A fresh `kdrv_c5` snapshot.
3. A Wi-Fi scan.
4. The BLE start.
5. A BLE listen.

It judges, in order, and names the first failure:

1. The snapshot is valid.
2. The chip id is an ESP32-C5.
3. The descriptor answered (else "stock or old slave").
4. The project name is `kode_c5` (else "stock esp-hosted slave").
5. The esp-hosted versions are equal.
6. SDIO runs at `KBSP_C5_SDIO_WIDTH` lines and `KBSP_C5_SDIO_KHZ`.
7. The GPIO service answers on the card-detect pin.

The scan must find a network at or above -70 dBm (`KODE_C5_TEST_RSSI_MIN_DBM`). NimBLE must have synced and own an address, and the listen must hear an advertiser. A link that is up is left alone. A row that arrives while a job holds the channel becomes a debt (`test_pending`), paid after the services' debts. A row the queue has no room for fails at once with one verdict, and the log says `test c5: FAIL - AO_Radio's queue is full; the row did not start`.

The budget is 118 s (`KODE_C5_TEST_BUDGET_MS`). The owner's variant (`c5_test_request_user()`, for `sdk/kaos/autotest`) drops the scan floor and the advertiser requirement. The BLE stack stays up afterwards.

### The rest of the radios

With `CONFIG_KODE_LOWPOWER`, AO_Radio joins the rounds of AO_LowPower as `radio`, with `lowpower_join_dark()` because it takes part in dark wakes (`sdk/kaos/lowpower`). ASLEEP keeps the radios, so the P4 and the C5 sleep together. OFF leaves the link up.

**For ASLEEP**, with the link up and nothing in flight, AO_Radio hands the start of the sleep sentinel to its radio worker as a job, `KDRV_RADIO_JOB_SLEEP`, which runs `kdrv_radio_sleep()` (`sdk/kdrv/c5`). The round is answered ready when the sentinel is up. A busy job, a C5 update, a park for a jump, the production row, or a link that is starting or stopping makes AO_Radio answer busy (`radio busy`, `c5 update`, `c5 park`, `c5 test`, `link starting`, `link stopping`). A Wi-Fi frames stream makes it answer `frames`: the round's arrival ends the stream, and the next try finds it gone. A refusal of the start is also a busy answer with the reason: `c5 refused sleep`, `sdio not idle`, `wake line` or `radio sleep failed`. With no link up there is nothing to keep, and the answer is ready.

The sentinel reports each wake as a note, which reaches AO_Radio as `RADIO_SLEEP_NOTE_SIG`. The note decides nothing. A note that says the sentinel could not go back down (`STOOD_DOWN`) makes AO_Radio log `the sleep sentinel stood down: the bus is up, so the board wakes` and, when the sentinel had started for a rest, ask AO_LowPower for AWAKE with `lowpower_request()`, so that the state of the system matches the hardware. In an app's rest of the radio, that request ends the rest: AO_LowPower publishes AWAKE over AWAKE, which stops the sentinel and gives the radio back (`sdk/kaos/lowpower`). A note with a deaf C5 is counted. While the sentinel is armed, a scan is refused at once as busy (`KODE_NO_RESOURCES`, and `>err code=4 msg=busy` for `wifi_scan` and `ble_scan`): a scan fails on a C5 that sleeps between wakes. A scan refused for an app's rest of the radio is `KODE_DENIED` with `rest` true instead (`sdk/kaos/part-rest`). On AWAKE, AO_Radio stops the sentinel with another job, and the stop waits for the job in flight. A round that arrives while that stop is with the worker is owed, and AO_Radio decides it when the stop returns: ready for an OFF round once AO_Net has left, a new start for an ASLEEP round, and `c5 would not wake` when the stop fails. A round that arrives while any other sentinel job is out, a start or the stop for an OFF round, is answered busy (`radio busy`) at once.

**For a dark wake**, AO_Radio hears `LOWPOWER_STATE_SIG` with state DARK: work fell due while the board sleeps, and it needs the bus but not the glass. AO_Radio stops the sentinel as it does for AWAKE and calls `lowpower_dark_done()` once the stop has returned, whatever its outcome, or at once when no sentinel is armed or the link is not up. The round for ASLEEP that ends the dark wake reaches the owners that took part in it, and AO_Radio answers it by starting the sentinel again. A Bluetooth advertisement stream ends at a round for ASLEEP or OFF, and the round is answered busy `heard` until the scan has stopped.

**For OFF**, AO_Net leaves first. It closes its sessions and calls `radio_net_left()`, and it tells AO_Radio from its initial transition with `radio_lp_expect_net()` whether it takes part, so that AO_Radio does not wait for a call nobody would make. Then AO_Radio stops the sentinel if it runs, so that the bus is awake and nothing is suspended, and answers. If the stop fails, the answer is busy `c5 would not wake`. AO_Radio takes nothing down: no teardown job, no unmount, no hold of the C5 from here. Deep sleep stops the P4 whole and `khal_power_off_enter()` holds `C5_EN` low, which resets the C5. The link is built once per boot, and tearing esp-hosted down while the NimBLE host runs panics that host, so an OFF round leaves both alone. An OFF round that is abandoned finds the link as it was. A link that is already down, or lost while the round waits for AO_Net, is answered ready once AO_Net has left. A link lost while the stop for an OFF round is still with the worker refuses the round with `link lost`.

## Specifications

### Signals in

| Group | Signals | Meaning |
| --- | --- | --- |
| Link | `RADIO_UP_REQ_SIG`, `RADIO_DOWN_REQ_SIG`, `RADIO_STATE_REQ_SIG` | Start, end, republish. `RADIO_PARK_REQ_SIG` (`RadioParkEvt`: `target`) is AO_Boot's |
| Chip | `RADIO_TEST_REQ_SIG` (`RadioTestReqEvt`: `user`), `RADIO_FIELD_REQ_SIG` (`RadioFieldReqEvt`: `who`, `op`, `field`, `value`) | The row; one field of the `kdrv_c5` table, served from the snapshot in every state |
| Wi-Fi | `WIFI_SCAN_REQ_SIG` (`WifiScanReqEvt`: `gen`), `WIFI_JOIN_REQ_SIG` (`WifiJoinEvt`: `ssid[33]`, `pass[65]`, `remember`), `WIFI_LEAVE_REQ_SIG`, `WIFI_STATE_REQ_SIG`, `WIFI_RSSI_REQ_SIG`, `WIFI_FAST_REQ_SIG` (`WifiFastEvt`: `on`), `WIFI_AUTO_REQ_SIG`, `WIFI_LIST_REQ_SIG`, `WIFI_FORGET_REQ_SIG`, `WIFI_START_REQ_SIG`, `WIFI_STOP_REQ_SIG`, `WIFI_SCAN_STOP_REQ_SIG` | A join with an empty `pass` of a vault network is a vault join: the C5 uses the password it keeps. Leave is not forget. An accepted join also sets the Wi-Fi flag |
| Scans | `RADIO_SCAN_ASK_SIG` (`ScanAskEvt`) | A scan an Active Object or a blocked task asked for, Wi-Fi or Bluetooth as its `kind` says |
| Frames | `WIFI_FRAMES_REQ_SIG` (`WifiFramesReqEvt`: `who`, `on`, `channel`), `RADIO_FRAMES_KNOCK_SIG` | A start or a stop of the Wi-Fi frames stream; the knock is private, a static event from esp-hosted's thread |
| Heard | `BLE_HEARD_REQ_SIG` (`BleHeardReqEvt`: `who`, `on`), `RADIO_HEARD_KNOCK_SIG` | A start or a stop of the BLE advertisement stream; the knock is private |
| BLE | `BLE_START_REQ_SIG`, `BLE_SCAN_REQ_SIG` (`BleScanReqEvt`: `ms`), `BLE_STOP_REQ_SIG`, `BLE_STATE_REQ_SIG`, `BLE_UNPAIR_REQ_SIG`, `BLE_PAIR_OPEN_REQ_SIG`, `BLE_LINK_SIG`, `BLE_PAIR_TAKE_SIG`, `BLE_PAIR_REJECT_REQ_SIG`, `BLE_APP_VALUE_REQ_SIG` (`BleAppValueReqEvt`: `op`, `name`, `len`, `data`), `BLE_HID_REPORT_REQ_SIG` (`BleHidReportEvt`) | `BLE_UNPAIR_REQ_SIG` is refused while a console central is attached or the radio is busy, and `BLE_PAIR_OPEN_REQ_SIG` while Bluetooth is off. `BLE_PAIR_OPEN_REQ_SIG` is a static event posted with `KQP_RADIO_POST_MARGIN`, so `ble_pair_open_request()` returns false when the queue has no room. A refusal is answered by `BLE_STATE_SIG` with `refused` set, and the console turns it into `>err code=4 msg=busy`, or `>err code=5 msg=off` or `msg=attached`. The pairing pair exists with `KODEOS_BLE_PAIRING_PASSKEY` |
| Identity | `ID_SIGN_REQ_SIG` (`IdSignReqEvt`: `who`, `nonce[201]`), `ID_REQ_SIG` (`IdReqEvt`), `C5_WIPE_REQ_SIG` (`C5WipeReqEvt`), `KODE_SVC_RSP_SIG` (`KodeSvcEvt`), `KODE_SVC_TMO_SIG` | A second identity request while one is in flight is refused at once |
| Update | `FLASH_REQ_SIG`, `RADIO_RECV_REQ_SIG` (`AppRecvReqEvt`), `RADIO_INSTALL_GO_SIG`, `RECV_DATA_SIG`, `RADIO_RECV_IDLE_SIG`, `STORAGE_*`, `NET_STREAM_*` | The medium and the terminal paths |
| Internal | `RADIO_JOB_SIG`, `RADIO_SVC_JOB_SIG` (`KqpWorkerDoneEvt`), `RADIO_LINK_LOST_SIG` (`RadioLostEvt`), `RADIO_JOB_GUARD_SIG`, `RADIO_UNMOUNT_RETRY_SIG`, `RADIO_UNUSED_SIG`, `RADIO_TEST_STEP_SIG`, `RADIO_SCAN_MORE_SIG` | Workers, guards and self-posts |
| Rest | `LOWPOWER_ROUND_SIG`, `LOWPOWER_STATE_SIG`, `RADIO_SLEEP_NOTE_SIG` (`RadioSleepNoteEvt`: `kind`, `knocks`, `tx_sta`, `tx_serial`, `tx_hci`), `RADIO_NET_LEFT_SIG` (`RadioNetLeftEvt`: `round`) | With `CONFIG_KODE_LOWPOWER`: the rounds of the board's rest, a wake of the P4 that involved the C5, and AO_Net's word that its sessions are closed |
| Other | `CONFIG_REQ_SIG` (`wifi`, `ble`, `ble_hid`, `wifi_join`, `wifi_ps`), `C5_RUN_REQ_SIG` | Settings; the C5 asked to run |

### Signals out

| Signal | Event | Meaning |
| --- | --- | --- |
| `RADIO_STATE_SIG` | `RadioStateEvt`: `link`, `fw_known`, `fw_major/minor/patch`, `sd_hosted` | The link, on every change and on request |
| `WIFI_STATE_SIG` | `WifiStateEvt`: `state`, `ip4`, `ssid`, `rssi`, `enabled` | `enabled` is the service flag, not the association. AO_Net reads online from this |
| `WIFI_SCAN_ENTRY_SIG`, `WIFI_SCAN_END_SIG` | `WifiScanEntryEvt`: `ssid`, `rssi`, `channel`, `authmode`, `bssid`. `WifiScanEndEvt`: `count`, `ok`, `busy`, `cut`, `gen` | One per network as the sweep produces it, then the end with the count. `ok=false` for a failed sweep or a lost link, and `cut` set for a sweep ended early by `wifi_scan_stop` or by a newer Wi-Fi request. `gen` is the generation of the newest request the listing answers |
| `WIFI_SCAN_AGAIN_SIG` | `WifiScanEndEvt`: `cut`, the count the cut sweep published, the newer request's `gen` | The Wi-Fi listing in flight ended for a newer `wifi_scan` and starts again; one `WIFI_SCAN_END_SIG` closes it |
| `WIFI_SCAN_RSP_SIG`, `BLE_SCAN_RSP_SIG` | `ScanRspEvt` | Posted to the Active Object of an asked scan: the count, `rc` (`KODE_CANCELLED` when a newer request took its place), whether entries were dropped, and `rest`, true when the scan was refused because an app rests the radio |
| `WIFI_SAVED_ENTRY_SIG`, `WIFI_SAVED_END_SIG` | `WifiSavedEvt`: `ssid` | Names only; a stored password never comes back |
| `WIFI_FRAMES_STATE_SIG`, `WIFI_FRAMES_TICK_SIG`, `WIFI_FRAME_SIG` | `WifiFramesStateEvt`: `on`, `channel`, `joined`, `why`. `WifiFramesTickEvt`: `channel`, `joined`, `rssi_max`, `heard`, `mgmt`, `data`, `dropped`. `WifiFrameEvt`: `channel`, `rssi`, `fc`, `addr1`, `addr2`, `addr3`, `len`, `head_len`, `head` | Posted to the asker of the frames stream, never published |
| `BLE_HEARD_STATE_SIG`, `BLE_HEARD_SIG` | `BleHeardStateEvt`: `on`, `why`, `heard`, `dropped`. `BleHeardEvt`: `addr`, `addr_type`, `rssi`, `pdu`, `len`, `data`, `dropped` | Posted to the asker of the advertisement stream, never published |
| `BLE_STATE_SIG` | `BleStateEvt` | Reports OFF from the flag when `ble_want` is false, whatever the driver says. It carries the name the board goes by (the advert's and its Device Name), `pair_wait` while Pair new device waits for the link, and `refused` once, with the state that answers a refused request: busy, off or attached |
| `BLE_SCAN_ENTRY_SIG`, `BLE_SCAN_END_SIG`, `BLE_PAIR_SIG` | | The BLE listing and the pairing record: a code to show, the end of a pairing, or a pairing refused with no code, told at most once in `KODE_BLE_PAIR_REFUSED_QUIET_MS` |
| `BLE_APP_WRITE_SIG`, `BLE_APP_LINK_SIG`, `BLE_APP_TAKEN_SIG` | `BleAppWriteEvt`: `name`, `len`, `data`. `BleAppLinkEvt`: `connected`. `BleAppTakenEvt`: `name`, `left` | A phone wrote to the app's service, connected or left, or a read took a value of a queued characteristic |
| `RECV_READY_SIG`, `RECV_ACK_SIG`, `RECV_DONE_SIG`, `RECV_FAIL_SIG`, `RECV_STALL_SIG` | static events | The terminal install protocol; they cannot fail to allocate |
| `APP_FLASH_PROGRESS_SIG`, `APP_FLASH_DONE_SIG`, `APP_FLASH_FAIL_SIG` | | A C5 update, for the interface and AO_Power |
| `C5_RUNNING_SIG`, `TEST_RESULT_SIG` | named `c5` | The C5 has booted; the verdict |
| Posted | `RADIO_FIELD_RSP_SIG` to the asker, `ID_*` answers, `BOOT_RADIO_PARKED_SIG` to AO_Boot, `STORAGE_CMD_SIG` and the `STORAGE_*` loan to AO_Storage, `CONSOLE_RAW_REQ_SIG` to AO_Log, `NET_STREAM_*` to AO_Net | |

### Calls, numbers and settings

| Thing | Value |
| --- | --- |
| Calls | `radio_up_request()`, `radio_down_request()`, `radio_state_request()`, `radio_park_request(target)`, `wifi_scan_request(gen)`, `wifi_scan_stop_request()`, `wifi_frames_request(who, on, channel)`, `wifi_join_request(ssid, pass, remember)`, `wifi_leave_request()`, `wifi_start_request()`, `wifi_stop_request()`, `wifi_state_request()`, `wifi_rssi_request()`, `wifi_fast_request(on)`, `wifi_auto_request()`, `wifi_list_request()`, `wifi_forget_request(ssid)`, `wifi_scan_ask(who)`, `ble_heard_request(who, on)`, `ble_hid_report_post(kind, data, len, tap)`, `ble_start_request()`, `ble_scan_request(ms)`, `ble_scan_ask(who, ms)`, `ble_stop_request()`, `ble_state_request()`, `ble_unpair_request()`, `ble_pair_open_request()`, `ble_pair_reject_request()`, `c5_flash_request()`, `c5_test_request()`, `c5_field_request()`, `exp_power_request(on)`, `radio_c5_release(out, len)` (the kode_c5 release from the snapshot kdrv_c5 keeps, `info`'s `c5=`, read with no trip over the link; `KODE_DENIED` with no link up, for a slave that is not kode_c5, for a version that is esp-hosted's, or for `len` too short for the whole release). Each `*_request()` here returns `bool`, true when AO_Radio has the request, except `radio_up_request()`, `radio_park_request()` and `ble_state_request()`. False means the queue was within `KQP_RADIO_POST_MARGIN` of full or the pool was dry, and nothing answers. A refused `radio_up_request()` is a line in the log, a refused park is answered as one the C5 refused, and the ask for the BLE state is owed until there is room. With `CONFIG_KODE_LOWPOWER` also `radio_net_left(round)`, `radio_lp_expect_net(expected)` and `radio_sleep_last_note(out)`, which AO_Net and the console use. An Active Object of an app uses the `kode_sys_wifi_*` and `kode_sys_ble_*` calls of `kode_sys.h`, which wrap these; a task uses the blocking `kode_wifi_*` and `kode_ble_*` calls of `kode.h`. `*_state_request()` only after `kode_init()` returns |
| Stored settings | `kset/wifi`, `kset/ble` (the wishes, `on` or `off`), `kset/wifi_join`, `kset/wifi_ps`, and `kset/ble_hid` in the kodeOS role. A read gives the wish and `stored=yes`, not the state of the link |
| Console | `radio_up`, `radio_down`, `radio_info`, `c5`, `c5_help`, `c5_wipe`, `wifi_up`, `wifi_down`, `wifi_scan`, `wifi_scan_stop`, `wifi_frames`, `wifi_join`, `wifi_auto`, `wifi_list`, `wifi_forget`, `wifi_leave`, `wifi_info`, `ble_up`, `ble_down`, `ble_scan`, `ble_heard`, `ble_info`, `ble_unpair`, `ble_pair`, `ble_hid_info`, `ble_hid_mouse`, `ble_hid_wheel`, `ble_hid_key`, `test component=c5` |
| Timers | `guard`, `unmount_retry`, one per KODE service, the C5-boot one-shot, and the receive idle timer (5 s between chunks, 30 s while raw mode is requested) |

## Gotchas

> **DANGER**
>
> **A bad C5 image can leave the radio unreachable.** The C5 slave has rollback disabled, and there is no cable to it. `install dst=c5` checks the digest, the header and the chip id before it writes, but an image that is the right chip and does not boot cannot be undone from the P4.

> **WARNING**
>
> **Your join returns nothing, or an empty answer, with the link off.** In `Radio_down` the first answer to a join is a refusal. Call `wifi_start_request()` (or `radio_up_request()`) first, and watch `WIFI_STATE_SIG`: `wifi_join_request()` is answered there once the attempt resolves.

> **WARNING**
>
> **Switching off the last service takes the link with it.** Code that needs the link with no service must call `radio_up_request()`, or the next service that goes off ends the link. A start again costs about 3 s.

> **NOTE**
>
> **The row can outwait its budget behind an autojoin round.** A round is a scan plus up to 20 s per join, and the row's budget is 118 s. The console prints `result=timeout` and drops the late verdict. The log says `waiting for the channel`.

## Example code

This joins the network the Kode Dot remembers and waits until a name resolves. The Kode Dot must remember a network already (`wifi_join` from the console once). You see `online` in the console log within a few seconds of the join.

```c
/*
 * wifi_online.c - from Kode with love
 *
 * Asks AO_Radio to join a network the Kode Dot already remembers, which
 * brings the C5 link up. Then it retries a name lookup until it works and
 * prints the address. The console log shows online once the join is done.
 */
#include "kode.h"

/* Bring the system up, join a remembered network, then wait for a lookup. */
void app_main(void)
{
    uint32_t ip4 = 0;

    kode_init();

    while (!kode_wifi_connect(NULL, NULL)) {
        kode_print("no network yet: %s", kode_error());
        kode_delay(5000);
    }

    while (!kode_net_resolve("kode.diy", &ip4)) {
        kode_delay(1000);
    }
    kode_print("online, kode.diy is %08X", (unsigned)ip4);

    while (true) {
        kode_delay(1000);
    }
}
```

Compiled against the 0.1.1 SDK with ESP-IDF v6.1 on 2026-11-11. Not run on a Kode Dot.

## In the SDK

- [`components/kaos/radio`](https://github.com/kodediy/kode-sdk/tree/main/components/kaos/radio): `radio_ao.c`, the state machine, the workers, the reconcile, the update and the row.
- [`kaos.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kaos/core/include/kaos.h): `kradio_link_t` and the `radio_*`, `wifi_*`, `ble_*` and `c5_*` calls.
- [`components/kdrv/radio`](https://github.com/kodediy/kode-sdk/tree/main/components/kdrv/radio): the esp-hosted link, Wi-Fi and BLE drivers; see `sdk/kdrv/radio` and `sdk/kdrv/c5`.
