# kode and kode_sys

kode_init(), the blocking calls of an app's tasks, the commands and requests of its Active Objects, the start order, the boot banner and the build options.

## What it is

Two components are the door of the SDK, and an app names `kode` only. `kode_sys` holds `kode_init()` and what an app with Active Objects of its own writes against. `kode` is the standard layer on top of it: blocking calls an app makes from its own tasks, by plain names such as `"top"` or `"sd/log.txt"`. A third component, `kode_screen`, adds the glass to the standard layer: `kode_screen_new()`, its widgets, canvases and PNG files, with no LVGL in your code.

You add `kode` to a project, include `kode.h`, call `kode_init()` from `app_main()`, and the whole system runs inside your firmware: the same Active Objects, the same signals and the same rule that every device has exactly one owner. kodeOS starts itself with this call, and so does your app.

An app is a **whole firmware**. It carries its own copy of the runtime, so your Active Objects and kodeOS's are the same objects, in your image, scheduled by your own QF. Nothing is shared with a running kodeOS, and any reset of your firmware comes back to kodeOS, because the bootloader marks the app's boot request as tried before it jumps and the app never renews it.

Pick the layer by what your code is:

- A task of your own (`app_main()` or a task you create) includes `kode.h` and makes calls that wait for the answer.
- An Active Object of your own includes `kode_sys.h`, which brings `kqp.h`. It makes commands that return at once and requests that are answered by an event.

The headers and components that cover both:

- `kode.h` is the standard layer: every call of the sections below that start with `kode_`. It also brings `kode_init.h` (`kode_init()`, `kode_up()`), `kode_defs.h`, `kode_colors.h` and `kapp_desc.h` (`KODE_APP_MANIFEST`, what the launcher shows about your app).
- `kode_sys.h` is the extended layer: every `kode_sys_*` call, with `kode_log.h`, `kode_variables.h`, `kode_functions.h`, `kode_config.h`, `kapp_cat.h` and `kqp.h` (`sdk/kqp`).
- `kode_worker.h` gives an Active Object a worker for the calls that wait.
- `kode_cert.h` holds the bench requests of the FCC and CE labs: the maximum-drive carriers and the field listening of the NFC and RFID owners.
- `kode_screen` has no header of its own: its calls are declared in `kode.h`, and an app that draws adds the component to its `REQUIRES`.

## How it is connected

```mermaid
flowchart LR
  app["Your task"]
  subgraph sdk["The SDK in your image"]
    std["kode.h<br/>the standard layer"] --> sys["kode_sys.h<br/>commands and requests"]
    sys -- "LED_RGB_SIG" --> ao["AO_LedMgr"]
    ao -- "function call" --> drv["kdrv<br/>KTD2026 driver"]
  end
  app -- "kode_led_set_rgb()" --> std
  drv --> chip["KTD2026"]
  class app app
  class ao ao
  class chip chip
```

*A call from your code to a chip*

The standard layer is built on the extended one, and the extended layer on kaos and kqp. Everything an app asks for goes through the Active Object that owns the device, exactly as kodeOS's own code does. `kode_sys` requires kaos, kqp, kdefs, klog, kdrv and khal publicly, because its headers include theirs, and kbsp privately: the facade claims the expansion header's resource and an app never names one. `kode` requires `kode_sys`, kdefs, kaos, kdrv and khal.

Three kinds of call exist:

- A **standard call** (`kode_*`) blocks the calling task until the owner answers, and returns a `bool`, a value or a struct. Why it failed is in `kode_error()`: a short English text, valid until the task's next `kode.h` call. A call from an Active Object or an ISR is refused, and the text says to call `kode_sys_*` instead.
- A **command** (`kode_sys_*` without an Active Object argument) builds an event, posts it to the owner and returns a `kode_status_t`. It tells you the request was accepted, and never that the work happened. A command leaves the owner's queue a margin of free slots (`KODE_SYS_CMD_MARGIN`) and is refused with `KODE_NO_RESOURCES` inside it, so a loop of commands is refused and never asserts. It is safe from an Active Object and from any task.
- A **request** (`kode_sys_*` taking `QActive *me`) posts to the owner and returns at once. The answer arrives later at `me` as an event that carries a copy, on the signal each call names. Each asker has one door per kind of request: a second request of the same kind before the answer is refused with `KODE_DENIED`, and the door is free again just before the answer is posted, so `me` may ask again from the answer's handler.

A request that moves a buffer too big for an event lends yours: keep it valid and leave it alone from the call until the answer arrives. The answer signals are also published for the console and kodeOS's own screens, so an Active Object never subscribes to one: it would receive answers that are not its own.

An Active Object's queue must hold everything that can wait in it at once: one slot per open door, its own timers and the signals it subscribes to, and during a listing the entries that AO_Storage posts until `KODE_SYS_LIST_FREE_SLOTS` are free. `KQP_AO_QUEUE_LEN` (16) suits an Active Object above AO_Storage (`KODE_PRIO_STORAGE`, 5); one below it that lists and asks for other things on one tick needs a queue of `KODE_SYS_FILE_LIST_MAX` plus `KODE_SYS_LIST_FREE_SLOTS` (32) and every slot the rest of its work needs.

## Specifications

### The files

The files of the components.

| File | What it does |
| --- | --- |
| `kode/include/kode.h` | The standard layer: every `kode_*` function below, the constants an app sizes arrays against, and `KODE_VERSION_MAJOR` 4, `KODE_VERSION_MINOR` 0 |
| `kode_sys/include/kode_sys.h` | The extended layer: every `kode_sys_*` function, its answer types and its limits |
| `kode_sys/include/kode_init.h` | `kode_init()` and `kode_up()`, declared once for both headers |
| `kode_sys/include/kode_worker.h` | `kode_worker_t`, `kode_worker_start()` and `kode_worker_submit()`, inline over `kqp_worker_*` |
| `kode_sys/include/kode_cert.h` | The FCC and CE bench requests |
| `kode_sys/src/kode_sys.c` | `kode_init()`, the table of rows that starts every Active Object and parks the devices the app did not link |
| `kode_sys/src/kode_banner.c`, `kode_banner_text.c` | The four banner lines, and the closed table of reset words as pure text the host tests compile alone |
| `kode_sys/version.cmake` | Writes `kode_sdk_version.h` on every build |
| `kode/src/kode_standard_ao.c` | The standard layer's own Active Object, which runs the event listeners |
| `kode_screen/src/` | The screen, widgets, canvases and PNG drawing of the standard layer |

### The start order

`kode_init()` is safe to call again or from several tasks: the first does the work and the others wait for it. Never call it from its own bring-up (a hook or an Active Object it starts). `kode_up()` says whether every owner `kode_init()` starts has its queue: an interface that starts early (`kode_app_early()`) asks it before it posts to an owner. Every `kode.h` call runs `kode_init()` first.

`kode_init()` does this, in order:

1. It runs `kode_log_init()`, then with `CONFIG_KODE_LOWPOWER` `kode_boot_gate()`, which sends a Kode Dot woken from OFF by any button but BOT back to deep sleep before any Active Object exists (`sdk/kaos/lowpower`). Then `khal_heap_watch()`, `khal_keep_init()`, `khal_identity_init()`, `khal_pwm_init()`, `khal_exp_init()` and `kqp_init()`.
2. It starts AO_Log, prints the banner, and walks the table of rows below in order. A row whose owner the app did not link is parked: its device is put to rest and its pins stay claimed.
3. It ends with `log_start_reader()`, `sched_system_up()` when the scheduler is built, and `QF_run()`, which returns at once because the scheduler already runs.

Your `app_main()` goes on as an ordinary task beside them.

The core (AO_Log, AO_Boot, AO_Power, AO_IoExp and AO_Buttons) always starts. In the Gated by column, `used` means the owner starts when the app names one of its calls (kodeOS names them all), and an option means the build must turn it on, with the rule for an app in the Kconfig section. The priority is the FreeRTOS priority that `ps` prints.

| Order | Active Object | Priority | Queue | Stack | Gated by | Why it sits here |
| --- | --- | --- | --- | --- | --- | --- |
| 1 | AO_Log | 6 | 64 | 4096 | always | Everything logs through it |
| 2 | AO_Boot | 12 | 8 | 4096 | always | From here on the next boot is kodeOS again |
| 3 | AO_LowPower | 24 | 48 | 3072 | `KODE_LOWPOWER` | Third, so every owner after it can join the rounds of rest in its own initial transition |
| 4 | AO_Scheduler | 16 | 24 | 3072 | `KODE_SCHEDULER` | After AO_LowPower, which it joins, and before AO_Console. It posts to nobody until `sched_system_up()` |
| 5 | AO_Storage | 5 | 16 | 6144 | used | Before AO_AppMgr, which streams an image out of it, and before the interface |
| 6 | AO_AppMgr | 9 | 16 | 8192 | `KODEOS_APPMGR` | The first thing an interface asks for is the list |
| 7 | AO_IoExp | 17 | 16 | 4096 | always | Buttons, touch and display use it from their initial transitions |
| 8 | AO_Buttons | 13 | 16 | 3072 | always |  |
| 9 | AO_Touch | 14 | 16 | 4096 | used |  |
| 10 | AO_Display | 15 | 16 | 6144 | used | The glass comes up first. The rows below it that talk to the I2C bus wait up to 800 ms for the panel's reset line to settle |
| 11 | AO_Radio | 4 | 16 | 6144 | `KODEOS_RADIO` | After AO_Storage: the link's bring-up walks the card by posting to it |
| 12 | AO_Net | 2 | 24 | 4096 | `KODEOS_NET` | After AO_Radio: its initial transition asks for the Wi-Fi state |
| 13 | AO_LedMgr | 7 | 16 | 3072 | used |  |
| 14 | AO_Ir | 18 | 16 | 3072 | used | Self-contained |
| 15 | AO_Nfc | 19 | 16 | 6144 | `KODEOS_NFC` | Self-contained |
| 16 | AO_Rfid | 23 | 16 | 3072 | used | Self-contained |
| 17 | AO_Audio | 20 | 16 | 3072 | used | Self-contained |
| 18 | AO_Imu | 21 | 16 | 4096 | used | AO_Haptic posts to it from its first step |
| 19 | AO_Haptic | 22 | 16 | 3072 | used |  |
| 20 | AO_Autotest | 10 | 16 | 4096 | `KODEOS_AUTOTEST` | Before the console, its first client |
| 21 | AO_Console | 11 | 64 | 8192 | `KODEOS_CONSOLE` |  |
| 22 | AO_TestDot | 1 | 32 | 4096 | `KODE_TEST_DOT` | After the console, whose verbs it adds to |
| 23 | AO_Power | 8 | 8 | 4096 | always |  |

A firmware's interface may start with the first rows: it defines `kode_app_early()`, and `kode_init()` calls it right after AO_Display, so its first frame does not wait for the rows below.

Each Active Object's task is named after it before it starts, so a backtrace and `ps` read `log`, `boot`, `storage` and so on.

### Announcements at startup

An announcement made during startup has already been made. Every Active Object that kodeOS starts is running when `kode_init()` returns. Ask for a state instead of waiting for it: subscribe to `DISPLAY_STATE_SIG`, then call `display_state_request()` (`sdk/kscreen`).

### Coming home

Coming home is not your job. `kode_exit()` is the polite way, but any reset does it: the button, a crash, a watchdog.

The bootloader marks the boot request `TRIED` before it jumps to your app, and AO_Boot in an app never writes otadata or the request. The next reset therefore boots kodeOS, even for an app that dies on its first line (`sdk/kaos/boot`).

### The boot banner

`kode_init()` prints four lines at the top of every log, through AO_Log, at level NOTICE under the tag `kode`. They pass every level filter except a global `off`.

The four lines:

| Line | Reads | From |
| --- | --- | --- |
| 1 | `<project> <version> (<date> <time>, ESP-IDF <version>), <role>`; the role is `the OS, from <partition>` or `an app` | The image descriptor, `kdrv_running_desc()` |
| 2 | `sdk <version>` | `KODE_SDK_VERSION`, written by the build |
| 3 | `hardware <product> <revision>, <chip> v<major>.<minor>, <n> MB flash, <n> MB PSRAM` | kbsp for the names, `khal_chip_info()` for the chip and sizes |
| 4 | `reset <reason>` | `kdrv_reset_reason()` and a closed table of sixteen |

A fact that cannot be read prints `?`.

For a panic, the interrupt watchdog and the task watchdog, line 4 gives the core dump's panic reason instead of the words, read only when the dump belongs to this image (`reset AO stuck: Net, 30 s in one event`). When kodeOS starts after an app, it reads the app's name from the `TRIED` boot request before AO_Boot clears it and prints `reset back from app <name>: <reason>`, without reading the dump, because an app is built without one. AO_Boot logs no reset reason of its own: the banner is the one place.

The SDK version is the first of these that exists:

1. `git describe --tags --dirty --always` in the SDK's work tree (when the SDK is a submodule).
2. The version the component manager recorded for `kodediy/kode` in `dependencies.lock` (when the SDK was fetched).
3. The word `unknown`.

`version.cmake` runs on every build and rewrites the header only when the string changed.

### API: how to read the tables

The sections for the standard layer list calls of `kode.h`: they block, and a call from an Active Object is refused, because a call parked inside a state handler stalls every priority beneath it. An Active Object uses the `kode_sys` sections, or runs a standard call as a job on a worker (`kode_worker_start()`) and handles the result as an event. Status values are `kode_status_t` (`sdk/kdefs`). A `kode.h` call that fails returns `false`, `NULL`, `NAN`, 0 or an empty struct, as its header says, and `kode_error()` tells why.

### API: the standard layer, start and time

Calls of `kode.h`.

| Call | What it does |
| --- | --- |
| `kode_init()` | Brings up logging, QF, the pools and every Active Object the build and the app's calls ask for, then returns |
| `kode_error()` | Why this task's last call failed; `""` when none, never `NULL` |
| `kode_delay(ms)` | Sleeps this task |
| `kode_uptime_ms()` | Milliseconds since boot; wraps after about 49 days |
| `kode_time_unix()` | The wall clock in Unix seconds UTC; -1 while it is not set |
| `kode_time_local(out)` | The wall clock as `kode_time_t` in the board's zone (`config key="zone"`, UTC while none is stored); false while the clock is not set |
| `kode_device_id()` | The board's serial: no separators, safe in a topic, a file name or a URL. Never `NULL`; empty when the factory MAC could not be read |
| `kode_exit()` | Ends the app and goes back to kodeOS; does not return |
| `kode_print(fmt, ...)` | One line on the console as `!N <ms> app <text>`, at most `KODE_PRINT_MAX` (200) bytes, shown whatever `config key="log"` filters unless the log is off |
| `kode_random(min, max)` | A number from the hardware generator, both ends included |

### API: the standard layer, buttons and events

Buttons are named `"up"`, `"down"`, `"left"`, `"right"`, `"top"` and `"bottom"`, in any case. `kode_button_was_pressed()` and `kode_button_get_presses()` share one count per button with every task, and asking either consumes the news.

| Call | What it does |
| --- | --- |
| `kode_button_is_pressed(name)` | Whether the button is down now |
| `kode_button_was_pressed(name)` | Whether it was pressed since the last ask |
| `kode_button_get_presses(name)` | How many presses since the last ask; the count restarts |
| `kode_button_read_all()` | All six states, as `kode_buttons_t`, from one reading |
| `kode_event_add_listener(event, fn)` | Calls `fn` every time the event happens, in the standard layer's own task and in event order. Up to `KODE_LISTENERS_MAX` (32) listeners |
| `kode_event_remove_listener(event, fn)` | Stops calling it; a call already running finishes |
| `kode_event_wait(event, ms, out)` | Waits for the next event; refused inside a listener |

The events, named in any case:

| Event | Source | Value and text |
| --- | --- | --- |
| `button_<name>_pressed`, `button_<name>_released` | The button's name | `button_<name>_held` exists for `top` and `bottom` |
| `wifi_connected`, `wifi_lost` | The network's name | |
| `mqtt_message` | The topic | The text is the payload, the value its length |
| `battery_low` | | The value is the level in percent, when it falls below `KODE_BATTERY_LOW_PCT` (15); it fires again after the level climbs `KODE_BATTERY_REARM_PCT` (5) above it |
| `ir_received` | `"NEC"` | The value is the command, the text the address such as `"0x0004"`; `"unknown"` for any other frame |
| `nfc_tag` | The card | The text is the UID; also for the app's own NFC reads |
| `touch_pressed`, `touch_moved`, `touch_released` | | `x` and `y` of the finger in glass pixels |
| `pin_<n>_changed`, n = 1 to 14 | | The value is the new level; the level is read `KODE_PIN_SETTLE_MS` (30 ms) after the edge |
| `ble_connected`, `ble_disconnected` | | A phone connected or left; any phone, the console's included |
| `ble_written` | The characteristic's name | The value is how many bytes, the text the bytes themselves, NULs included, followed by one NUL |
| `ble_taken` | The characteristic's name | A read took a value from a `KODE_BLE_QUEUED` characteristic; the value is how many are still queued |
| `ble_pair_code` | | A device is pairing with the board: the value is the code to show, and the text the same code as six digits with its leading zeroes. Only in an app that serves the Bluetooth mouse or keyboard (`sdk/kaos/ble-hid`) |
| `ble_pair_done` | | The pairing ended: the value is 1 when the device is bonded and 0 when it is not |

The first event call starts the standard layer's own Active Object at level `KODE_PRIO_USER_GUI` (3), which an app's own Active Object then cannot take. An event comes only from an owner the app links, and an app links an owner by naming one of its calls. Twelve events have an owner no other call links, the six Bluetooth events among them: name them with `KODE_EVENT_IR_RECEIVED`, `KODE_EVENT_WIFI_CONNECTED`, `KODE_EVENT_WIFI_LOST`, the `KODE_EVENT_TOUCH_` constants and the `KODE_EVENT_BLE_` constants, which link it. A listener or a waiter for a Bluetooth event has the radio send it. The text of an event is at most `KODE_EVENT_TEXT_MAX` bytes: one MQTT payload (256), or one Bluetooth value plus its NUL when `CONFIG_KODE_BLE_APP_VALUE_MAX` is larger.

### API: the standard layer, light and glass

| Call | What it does |
| --- | --- |
| `kode_rgb(r, g, b)` | A colour as `0xRRGGBB` |
| `kode_led_set_color(c)`, `kode_led_set_rgb(r, g, b)`, `kode_led_off()`, `kode_led_toggle()` | The status LED; each waits up to 100 ms for AO_LedMgr to take the request |
| `kode_display_set_brightness(pct)` | The panel's level while the app runs, 0 or 5 to 100; never stored, the user's level comes back when the app ends. 0 darkens the glass and the touch still reads |
| `kode_display_sleep(sleep)` | Puts the display to sleep, or wakes it, and waits until it is as asked, up to `KODE_DISPLAY_SLEEP_BOUND_MS` (2 s). Asleep, the panel and its link are off: the glass is dark and the board draws less than at a brightness of 0. The touch keeps reading, so a touch can be what wakes it. On waking, the screen comes back as the app left it, at its brightness. Fails while a screenshot is being read |
| `kode_touch_read(x, y)` | Whether a finger is on the glass, and where, in glass pixels (410 by 502, origin top-left) |
| `kode_screen_new(title)` | Puts a new screen on the glass: an optional header and the widgets under it. Needs the `kode_screen` component, and is not available in the kodeOS image |
| `kode_screen_add_text()`, `kode_screen_add_value()`, `kode_screen_add_button()` | Add a widget, up to `KODE_WIDGETS_MAX` (32); 0 when it fails |
| `kode_widget_set_text()`, `kode_widget_set_color()`, `kode_widget_was_pressed()` | Change a widget, and ask whether a button was tapped since the last ask |
| `kode_canvas_*`, `kode_draw_*`, `kode_fill_*` | Canvases of the screen: pixels, lines, rectangles, circles, text and PNG files |

When the cell is critical on battery, before the board switches itself off, a notice covers the screen of `kode_screen` until a tap closes it or a cable comes. The standard layer hands `POWER_CRITICAL_SIG` to kscreen, which draws it (`sdk/kscreen`).

### API: the standard layer, files

Paths are `"sd"` or `"flash"`, then nothing or `/` and the rest: `"sd/log.txt"`, `"flash/data/a.csv"`, up to `KODE_FILE_PATH_MAX` (91) bytes, with no leading `/` and no `.` or `..` part. A file call waits up to `KODE_FILE_BUSY_MS` (5 s) for another task's file call and for AO_Storage.

| Call | What it does |
| --- | --- |
| `kode_file_read(path)` | The whole file as text, at most `KODE_FILE_READ_MAX` (4 MiB); valid until this task's next `kode_file_read()` |
| `kode_file_read_bytes(path, len)` | The whole file as bytes, the same limit |
| `kode_file_read_at(path, offset, buf, cap, got)` | Up to `cap` bytes starting at `offset`, into your own buffer. The file can be of any size. A read at or past the end gives no bytes and is not an error |
| `kode_file_write(path, text)`, `kode_file_append(path, text)` | Creates or replaces a file with a text, or adds to its end; the folder must exist |
| `kode_file_write_bytes(path, data, len)`, `kode_file_append_bytes(path, data, len)` | The same for `len` bytes, NULs included, of any size the volume can hold. The bytes go in parts, so a failure after the first leaves the file cut |
| `kode_file_status(path)`, `kode_file_exists(path)` | What a path is (`exists`, `is_folder`, `size`) |
| `kode_file_space(volume, total_bytes, free_bytes)` | How big a volume is and how much of it is free, in whole kilobytes. On a large card the first count can take hundreds of milliseconds |
| `kode_file_list(folder)` | One level of a folder, at most `KODE_FILE_LIST_MAX` (24) entries, each name up to `KODE_FILE_NAME_MAX` (96) bytes with its NUL; `more` says there were others |
| `kode_file_create_folder(path)`, `kode_file_delete(path)`, `kode_file_rename(path, new_name)`, `kode_file_move(from, to)` | Folder, delete (a file or an empty folder), rename and move. A move between `sd` and `flash` copies a file and then deletes it |

### API: the standard layer, motion

A failed read answers `NAN`. The four reads take their turn behind other tasks' reads, keep trying for `KODE_MOTION_BUSY_MS` (1 s), and their last try can take 600 ms more.

| Call | What it does |
| --- | --- |
| `kode_imu_read()`, `kode_imu_read_axis(axis)` | The seven IMU readings (acceleration in g, rotation in degrees a second, temperature), or one by name |
| `kode_mag_read()`, `kode_mag_read_axis(axis)` | The magnetic field in microtesla, corrected once a calibration is stored |
| `kode_mag_heading()` | Degrees clockwise from north that the Kode Dot's top points to; `NAN` without a calibration, while the Kode Dot is shaken or when the field is too weak |
| `kode_mag_is_calibrated()`, `kode_mag_clear_calibration()` | Ask for or forget the stored calibration, which is AO_Imu's `mag_cal` setting |
| `kode_mag_calibrate()` | Guides the user on the glass to turn the Kode Dot in every direction, for at most `KODE_MAG_CALIBRATE_MS` (30 s), and stores the result. Needs `kode_screen`, replaces the app's screen, and is not available in the kodeOS image |
| `kode_haptic_play(profile)` | A named buzz: `"click"`, `"tick"`, `"double"`, `"success"`, `"warning"`, `"error"` or one the app added. Returns once it starts |
| `kode_haptic_vibrate(on)` | Vibrates until `kode_haptic_vibrate(false)` |
| `kode_haptic_add_profile(name, pattern_ms, n, intensity)` | Adds or replaces a vibration; up to `KODE_HAPTIC_PROFILES_MAX` (8), with `KODE_HAPTIC_PATTERN_MAX` (16) segments |

### API: the standard layer, audio

Everything is 48 kHz, 16-bit, mono: the codec's capture and playback share one I2S clock, and the SDK ships no resampler. A call waits up to `KODE_AUDIO_BUSY_MS` (5 s) for the audio path. A sound is refused while a recording runs, and a recording while a sound plays in the background.

| Call | What it does |
| --- | --- |
| `kode_audio_play(path)` | Plays a WAV file and waits until it has been heard; another rate, width or channel count fails and says which |
| `kode_audio_play_start(path)`, `kode_audio_is_playing()`, `kode_audio_play_stop()` | The same in the background, ask whether it still plays, and stop it. The stop takes no turn, so it works while another task's call blocks |
| `kode_audio_play_samples(samples, count)` | Plays samples from memory and waits |
| `kode_audio_stream_open(channels)`, `kode_audio_stream_write(frames, count, ms, taken)`, `kode_audio_stream_close()` | Sound written a piece at a time: mono samples or left-right pairs played as their mean. The stream holds 200 ms. A write blocks only while the stream is full, `ms` at most, and `taken` says how many frames went in. While it is open every other sound and recording is refused. A stream left `KODE_AUDIO_STREAM_IDLE_MS` (10 s) without a write that put frames in is closed for the app, and the next write says so. The close waits until what the stream held has been heard |
| `kode_audio_tone(hz, ms)` | Plays a tone, 400 to 3400 Hz, up to 65 535 ms |
| `kode_audio_set(setting, value)`, `kode_audio_get(setting)` | Change or read an audio setting for this boot |
| `kode_audio_record_file(path, ms)` | Records the microphone into a WAV file, at most `KODE_AUDIO_RECORD_MAX_MS` (30 s) |
| `kode_audio_record_samples(buf, cap, ms, frames)` | Records into a buffer of your own until it is full or the time is up, whichever is first; `frames` says how many arrived |
| `kode_audio_record_start(max_ms)`, `kode_audio_record_status()`, `kode_audio_record_stop()`, `kode_audio_record_save(path)` | Records in the background into PSRAM, reports how far it got, ends it keeping what it has, and writes it to a WAV file |

### API: the standard layer, radios and network

The calls block, one task at a time. Bluetooth on and off is the user's, in Settings: an app never switches it, and while it is off every Bluetooth call fails and `kode_error()` says so.

| Call | What it does |
| --- | --- |
| `kode_wifi_connect(ssid, password)`, `kode_wifi_is_connected()`, `kode_wifi_disconnect()` | Join a network and wait up to `KODE_WIFI_CONNECT_MS` (30 s) for an address, ask whether the board has one, and leave; the password stays remembered |
| `kode_wifi_scan(out, cap)` | Scans both bands and waits for the sweep (about 38 s, at most `KODE_WIFI_SCAN_MS`). The newest Wi-Fi request wins: this scan ends a Wi-Fi scan in flight (another app's, the console's) and runs in its place, and a newer Wi-Fi scan, `kode_wifi_connect()` or Wi-Fi switched ends this one, which fails saying a newer request ended it early. Do not scan again at once then. Fails at once, saying the radio is busy, while the radio listens for Bluetooth devices, runs its own search for a known network, a self-test or an install, or sleeps between wakes for the board's rest. A join in flight is waited for |
| `kode_ble_set_name(name)`, `kode_ble_set_manufacturer_data(data, len)` | The name and the maker data a phone sees in a scan, at most `KODE_BLE_SCAN_RSP_MAX` (31) bytes together. Not stored. The chosen name is also the Device Name a connected phone reads |
| `kode_ble_scan(out, cap, ms)` | Listens for Bluetooth devices for 500 to 30 000 ms. As for Wi-Fi, it ends the Bluetooth listen in flight and a newer Bluetooth request ends it. It fails at once, busy, while the radio sweeps for Wi-Fi networks, runs its own search for a known network, a self-test or an install, or sleeps between wakes for the board's rest. That search runs each time the link comes up with Wi-Fi on, so the first listen on a link that was down nearly always fails busy |
| `kode_ble_hid_select(kinds)`, `kode_ble_hid_ready()`, `kode_ble_hid_mouse(buttons, dx, dy, wheel)`, `kode_ble_hid_click(buttons)`, `kode_ble_hid_keys(modifiers, keys)`, `kode_ble_hid_tap(modifiers, key)` | The board as a Bluetooth mouse (`KODE_BLE_HID_MOUSE`), keyboard (`KODE_BLE_HID_KEYBOARD`) or both, for a computer or a phone. Choose with the app's first call, at each start: the radio reads the choice once per boot. A report is queued for the link, and a full queue fails, except a report that lets everything go (`sdk/kaos/ble-hid`) |
| `kode_ble_pair_open()` | Opens five minutes in which a new computer or phone can pair, as Pair new device does in kodeOS. Only an app that chose a kind pairs a device. The code to show arrives as `ble_pair_code` |
| `kode_http_get(url)`, `kode_http_post(url, body)`, `kode_http_status()` | The answer's body as text, at most `KODE_HTTP_BODY_MAX` (64 KiB). A 404 is an answer, and a redirect is not followed. The body of a POST goes as `application/json` when it starts a JSON object or array, otherwise as `text/plain` |
| `kode_http_get_range(url, offset, buf, cap, got, total)` | The `cap` bytes of a resource from `offset` on, into a buffer of your own, for a resource too big for `kode_http_get()`. Each call is a connection of its own. `kode_http_status()` says what `buf` holds: 206 the bytes from `offset`, 200 the resource from byte 0 (kept only when `offset` is 0), 416 nothing. `total` is the length of the whole resource when the server says it. The offset is `kode_http_off_t`, 32 bits, or 64 with `CONFIG_KODE_HTTP_OFFSET_64` |
| `kode_net_ping(host, count)`, `kode_net_resolve(host, ip4)`, `kode_udp_send(host, port, data, len)` | Ping (one echo a second, up to 10), resolve a name, send one datagram |
| `kode_mqtt_connect(uri)`, `kode_mqtt_publish()`, `kode_mqtt_subscribe()`, `kode_mqtt_unsubscribe()`, `kode_mqtt_is_connected()`, `kode_mqtt_disconnect()` | The app's MQTT client; messages arrive as `mqtt_message` events. `kode_mqtt_is_connected()` is false while the Kode channel holds the client |

### API: the standard layer, the app's Bluetooth service

An app adds one GATT service of its own beside the console's, declared at file scope in the file that holds `app_main()`, or in one the app otherwise links. The radio finds it when its Bluetooth starts, and an app without one pays nothing:

```c
static const kode_ble_characteristic_t s_chars[] = {
    { "temp", "6e400002-b5a3-f393-e0a9-e50e24dcca9e", KODE_BLE_READ | KODE_BLE_NOTIFY },
    { "cmd",  "6e400003-b5a3-f393-e0a9-e50e24dcca9e", KODE_BLE_WRITE },
};
KODE_BLE_SERVICE("6e400001-b5a3-f393-e0a9-e50e24dcca9e", s_chars);
```

A characteristic has a name of 1 to 15 bytes, unique in the service, a 128-bit UUID as text and properties `KODE_BLE_READ`, `KODE_BLE_WRITE`, `KODE_BLE_NOTIFY` and `KODE_BLE_QUEUED`, at least one. A service holds up to `KODE_BLE_CHARACTERISTICS_MAX` (4) characteristics. A table the radio cannot serve (a UUID that is not 8-4-4-4-12 hex, no characteristic or too many, a name missing, too long or used twice, no property) is left out with one log line, and the value calls fail and say why.

Security is the console's. With console pairing and the passkey on, the default, every characteristic needs an encrypted, authenticated, bonded link, so only a phone bonded in kodeOS with the code on the glass reads, writes or subscribes. With Just Works pairing the link is encrypted and bonded but not authenticated, and with console pairing off the service is as open as the console. The service needs `CONFIG_KODEOS_BLE_CONSOLE=y`, whose pairing it uses.

| Call | What it does |
| --- | --- |
| `KODE_BLE_SERVICE(uuid, chars)` | Declares the service; a second one in the same app is a link error |
| `KODE_BLE_BATTERY_SERVICE()` | Serves the standard Battery service (0x180F) with Battery Level (0x2A19): the charge AO_Power reads, in percent, which a phone reads or subscribes to. It sits beside the app's service, behind the same security |
| `kode_ble_set_value(chr, data, len)` | Sets what a read of the characteristic gets; nothing is sent. Works before Bluetooth has started |
| `kode_ble_notify(chr, data, len)` | Sets the value and notifies a subscribed phone. With nobody subscribed the value is set and the call answers true. A notification carries at most 448 bytes, and a longer one is dropped while the value stays for a read |
| `kode_ble_queue_push(chr, data, len)` | Queues one value for the reads of a `KODE_BLE_QUEUED` characteristic, behind the others. Each read takes the oldest value, and a read with none left gets 0 bytes. A queue holds `KODE_BLE_QUEUE_SLOTS` (8) values, and a phone that connects or leaves empties it. A value longer than one read is read in parts and taken with its last part |
| `kode_ble_queue_room(chr)` | How many more values the queue takes now, 0 to 8; 0 with `kode_error()` set when it cannot be told |
| `kode_ble_queue_clear(chr)` | Empties the queue |

A value is at most `KODE_BLE_VALUE_MAX` bytes, which is `CONFIG_KODE_BLE_APP_VALUE_MAX` (20 to 512, 244 by default). A read or a write carries a whole value at any MTU, as a long read or a long write. Above 244 the host asks the central for an MTU of the value plus 3, at most 451. `CONFIG_KODE_BLE_ADVERTISE_APP_SERVICE` puts the service's UUID in the advert instead of the console's, for the phone apps that scan with a filter on it; only one 128-bit UUID fits.

### API: the standard layer, power, settings and pins

| Call | What it does |
| --- | --- |
| `kode_battery_level()`, `kode_battery_is_charging()`, `kode_battery_voltage_mv()`, `kode_power_is_usb_connected()` | The last reading of AO_Power; waits up to `KODE_BATTERY_WAIT_MS` (3 s) for the first |
| `kode_power_off()` | Switches the board off: deep sleep, and only BOT held for about a second wakes it. An order: an owner that is busy is given up to `KODE_LOWPOWER_ORDER_MS` (10 s), then the board goes off. Does not return on battery, and nothing is asked on a cable. Needs `CONFIG_KODE_LOWPOWER` |
| `kode_rest(parts, wake)`, `kode_rest_end()` | Puts parts of the board at rest while the app runs (the screen, the panel, the touch, the sound, the card, the radio, the CPU) and waits for the answer, up to `KODE_REST_BOUND_MS` (37 s); then brings them back. The board stays AWAKE. The board keeps the last word: when it goes to sleep or switches off by itself, when the radio chip cannot sleep through its rest (a request for AWAKE), or when the user holds BOT to go home, the rest is over and every part comes back. An owner with no room in its queue for the wake that ends a rest keeps its part at rest and is asked again every second inside the request's window. Past it `kode_rest_end()` returns false and `kode_error()` says `the rest did not end: <part>: out of events`. Needs `CONFIG_KODE_LOWPOWER` (`sdk/kaos/part-rest`) |
| `kode_power_set_charging(on)`, `kode_power_set_charge_current(ma)` | Allow or forbid charging, and set the fast-charge current, 64 to 896 mA in 64 mA steps. Not stored |
| `kode_setting_set(key, value)`, `kode_setting_get(key)` | A few strings the board keeps by name across resets and visits to kodeOS: a key of at most 15 bytes and a value of at most 191. Not a vault. Fails on a task whose stack is in PSRAM. Every app's settings share `KODE_NVS_SHARE_MAX` (16384 bytes) of the store, so KodeOS keeps room for its own: a set past it fails and `kode_error()` says `setting '<key>' could not be kept: the apps' share of the store (16384 bytes) is full` |
| `kode_pin_write()`, `kode_pin_read()`, `kode_pin_read_analog()`, `kode_pin_write_pwm()` | The 14 positions of J3, by the number printed on the connector. A pin that something listens to (`pin_<n>_changed`) is read and never driven |
| `kode_pin_power_3v3(on)`, `kode_pin_power_5v(on)` | J3's 3.3 V, switched by the C5 and waiting up to `KODE_PIN_POWER_MS` for it, and J3's 5 V from the cell, up to 0.5 A, refused while USB is present |
| `kode_i2c_*`, `kode_spi_*`, `kode_uart_*` | One I2C, one SPI and one UART bus on any of J3's pins, from `begin` to `end`, shared by every task. `begin` lends the pins and takes the controller |
| `kode_ir_send()`, `kode_ir_send_raw()`, `kode_ir_receive()`, `kode_ir_receive_raw()`, `kode_ir_last()`, `kode_ir_capture_start()`, `kode_ir_capture_stop()`, `kode_ir_send_file()` | Infrared: NEC frames, raw marks and spaces (up to `KODE_IR_RAW_MAX` durations), the last frame heard, and a capture file of up to 32 signals to play back |
| `kode_nfc_*`, `kode_rfid_*` | NFC (13.56 MHz) tags read, written and emulated from profiles, and EM4100 (125 kHz) tags read, written and played. Calls take turns, and each waits up to 5 s for the reader or the front end |

### API: commands of the extended layer

Calls of `kode_sys.h` that post to an owner and return a `kode_status_t`: `KODE_OK` when the owner's queue took it, `KODE_NO_RESOURCES` when the event pool is dry or the queue is within its margin, `KODE_DENIED` for an argument out of range or a build with no such owner. All are safe from an Active Object and from any task.

| Call | What it does |
| --- | --- |
| `kode_sys_led_set(on)`, `kode_sys_led_toggle()`, `kode_sys_led_set_rgb(r, g, b)` | The status LED |
| `kode_sys_screen_brightness(pct)` | The panel's level while the app runs, 0 or 5 to 100 |
| `kode_sys_screen_sleep(sleep)` | Puts the display to sleep or wakes it. To sleep, AO_Display first publishes `DISPLAY_PARK_SIG` so whoever draws stops; each call that returns `KODE_OK` ends in one `DISPLAY_SLEEP_SIG` with the outcome. A renderer that gives no answer within `KODE_LOWPOWER_GLYPHS_WAIT_MS` leaves the glass lit (`sdk/kaos/display`) |
| `kode_sys_screen_parked(seq)` | The answer of an app's own renderer to `DISPLAY_PARK_SIG`, with the park's `seq`; kscreen answers by itself |
| `kode_sys_ir_send_nec(addr, cmd)` | One NEC frame; AO_Ir drops it, with a log line, when too many requests for the C5 are held |
| `kode_sys_audio_tone(hz, ms, amp_pct)`, `kode_sys_audio_volume(pct)`, `kode_sys_audio_mic_gain(db)`, `kode_sys_audio_mute(on)` | One tone (400 to 3400 Hz, snapped to the detector's bin), the output volume (0 to 100), the microphone gain (0 to 42 dB in 6 dB steps) and mute for this boot. A setting keeps one request pending at most |
| `kode_sys_audio_record_stop()` | Ends a recording into memory early, whoever asked for it |
| `kode_sys_haptic_play_buzz(ms, gain_pct)`, `kode_sys_haptic_play_pattern()`, `kode_sys_haptic_hold()`, `kode_sys_haptic_stop()` | A buzz of 1 to 2000 ms, a pattern of up to 16 segments, a hold until the stop. One play at a time; the driver clamps the strength at the LRA's rating (80 %) |
| `kode_sys_flash(src, dst, run)` | Writes an image: `src` is `fs:<file>`, `sd:<file>`, a bare name or an `http://` or `https://` URL of up to 256 characters; `dst` is `os` or `app`; `run` boots an app once verified. `KODE_DENIED` without AO_AppMgr |
| `kode_sys_wifi_connect(ssid, pass)`, `kode_sys_wifi_disconnect()` | Join a network (a remembered one when `ssid` is `NULL`) and leave it |
| `kode_sys_mqtt_connect()`, `_disconnect()`, `_publish()`, `_subscribe()`, `_unsubscribe()` | AO_Net's MQTT client. A payload over `KODE_MQTT_PAYLOAD_MAX` (240) bytes is cut. Messages arrive as `MQTT_MSG_SIG`, so receiving takes an Active Object of your own. Needs `CONFIG_KODEOS_NET` |
| `kode_sys_ble_set_name(name)`, `kode_sys_ble_set_data(data, len)` | The scan response's name and maker data; what does not fit is refused, not cut |
| `kode_sys_ble_set_value()`, `_notify()`, `_queue_push()`, `_queue_clear()` | The values of the app's service, with the rules of the standard layer's calls of the same names. They check the declared table at once and are `KODE_DENIED` for a service left out, an unknown name or a value over `KODE_SYS_BLE_VALUE_MAX`. What AO_Radio then refuses has nobody to tell: a task that needs to know uses `kode.h` |
| `kode_sys_ble_hid_select(kinds)`, `kode_sys_ble_hid_mouse()`, `_click()`, `_keys()`, `_tap()` | The Bluetooth mouse and keyboard, with the rules of the standard layer's calls. A report is `KODE_DENIED` when its kind is not served or no host is subscribed, and `KODE_NO_RESOURCES` when the ring of `KODE_SYS_BLE_HID_RING_SLOTS` (16) is full (`sdk/kaos/ble-hid`) |
| `kode_sys_ble_pair_open()` | Five minutes to pair a new device, in an app only while the HID service is served. The code arrives as `BLE_PAIR_SIG`. `KODE_NO_RESOURCES` when AO_Radio's queue had no room |
| `kode_sys_nvs_set(key, value)` | Stores a string for `kode_sys_nvs_get()` to read back, in the namespace `kapp`. AO_Boot writes it from its own thread, so an Active Object and a `kode_worker` job may call it. Nobody is answered, and a pair the store refuses is a warning in the log, as is one that would take the apps' keys past their share, `KODE_NVS_SHARE_MAX` (16384 bytes). A pair asked before `kode_sys_exit_to_os()` or `kode_sys_home_now()` is written before the board leaves |
| `kode_sys_power_sleep()`, `kode_sys_power_off()` | Ask AO_LowPower for ASLEEP (the glass dim and showing the time, every owner at rest, the P4 and the C5 in light sleep, the radios up) or OFF (the C5 held in reset, the P4 in deep sleep). The answer is `LOWPOWER_STATE_SIG`, or `LOWPOWER_REFUSED_SIG` while a cable is in (`cable: external power`) or an owner is busy. Neither reaches the battery's ship mode, which is the console verb `ship_mode`. Without `CONFIG_KODE_LOWPOWER` they log `low power not built` and answer `KODE_DENIED` |
| `kode_sys_rest(parts, wake)`, `kode_sys_rest_end()` | An app's rest of single parts, `KODE_SYS_REST_*` bits, answered on `LOWPOWER_PART_SIG` (`sdk/kaos/part-rest`). A request for AWAKE, which AO_Radio makes when the C5 stays up through its rest, takes the rest: `KODE_LP_PART_TAKEN`, then `LOWPOWER_STATE_SIG` says AWAKE over AWAKE and every part comes back. An owner with no room for its wake past the request's window makes the end's answer `KODE_DENIED`, `<part>: out of events`, and its part stays at rest |
| `kode_sys_power_boost(on)`, `kode_sys_power_charge(on)`, `kode_sys_power_charge_limit(ma)` | 5 V from the battery on J3 (0.5 A, refused while USB is present or the cell is under `KODE_SYS_BOOST_MIN_MV`), allow charging, and the fast-charge current (`KODE_SYS_CHARGE_LIMIT_MIN_MA` 64 to `_MAX_MA` 896). The outcome shows on `POWER_CTRL_SIG` and `POWER_EVT_SIG` |
| `kode_sys_exp_power(on)` | Switches J3's `+3.3V_EXT` (the C5's IO5). AO_Radio publishes `EXP_POWER_SIG` when the switch is over, with `rc` `KODE_OK` (the rail is as asked), `KODE_IO_ERROR` (the C5 refused) or `KODE_DENIED` (the link would not come up; the wish stays and the next link-up carries it out). A Wi-Fi sweep delays it by about 40 s. Claims nothing |
| `kode_sys_exit_to_os()`, `kode_sys_home_defer()`, `kode_sys_home_now()` | Reset the board, ask AO_Boot for a moment before it resets on a held BOT (only inside the handling of `HOME_SIG`, within `KODE_SYS_HOME_GRACE_MS`, 200 ms), and reset now. The deferral is capped at `KODE_SYS_HOME_DEFER_MAX_MS` (3000 ms) from `HOME_SIG` |

With `CONFIG_KODEOS_HOME_HOLD` (on by default in an app), holding BOT for 3 s (`KODE_HOME_HOLD_MS`) publishes `BUTTON_HOME_HOLD_SIG`, then `HOME_SIG`, and restarts into kodeOS after the grace, whatever the firmware is doing. The 600 ms hold of the same button, `BUTTON_HOLD_SIG`, stays the app's own. An app with something to save defers from its `HOME_SIG` handler, saves, then calls `kode_sys_home_now()`.

### API: requests of the extended layer

Calls of `kode_sys.h` that take the asking Active Object `me`, post to the owner and return `KODE_OK`, `KODE_DENIED` (`me` is `NULL` or not started, a bad argument, the door of that kind is busy, or the build has no such owner) or `KODE_NO_RESOURCES`. The owner's own refusals arrive in the answer's `rc`: an owner whose device is not fitted still answers.

| Call | Answer signal | What it does |
| --- | --- | --- |
| `kode_sys_ir_send_raw()`, `kode_sys_ir_capture()`, `kode_sys_ir_last()` | `IR_SEND_RAW_RSP_SIG`, `IR_CAPTURE_RSP_SIG`, `IR_LAST_RSP_SIG` | Raw symbols (up to `KODE_SYS_IR_RAW_MAX_SYMBOLS`, 256), one captured frame, and the last frame AO_Ir heard. A request that finds the C5 link down waits for it, then answers `KODE_TIMEOUT` |
| `kode_sys_audio_info_read()` | `AUDIO_INFO_RSP_SIG` | What the path is and is set to |
| `kode_sys_audio_play(me, frames, n)` | `AUDIO_DONE_SIG` | Plays a whole sound, up to `KODE_SYS_AUDIO_MAX_FRAMES` (30 s at 48 kHz); the frames are lent |
| `kode_sys_audio_record(me, buf, cap, ms)` | `AUDIO_REC_RSP_SIG` | Records into your buffer, capped at `cap` frames and `KODE_SYS_AUDIO_BUF_SECONDS` (30); the answer carries the frames written. `kode_sys_audio_record_stop()` ends it early |
| `kode_sys_audio_record_file(me, path, ms)` | `AUDIO_FILE_RSP_SIG` | Records into a WAV file |
| `kode_sys_audio_stream_open()`, `_close()`, `kode_sys_audio_stream_write()` | `AUDIO_STREAM_OPEN_RSP_SIG`, `AUDIO_STREAM_CLOSE_RSP_SIG` | A stream whose ring holds `KODE_SYS_AUDIO_STREAM_FRAMES` (200 ms). It holds the codec until closed, so every other sound and a second stream are refused. Only `me` writes and closes it. A stream left `KODE_SYS_AUDIO_STREAM_IDLE_MS` (10 s) without a write is closed by AO_Audio |
| `kode_sys_imu_read()`, `kode_sys_mag_read()`, `kode_sys_mag_cal_get()`, `_set()`, `_clear()` | `IMU_SAMPLE_RSP_SIG`, `MAG_SAMPLE_RSP_SIG`, `MAG_CAL_RSP_SIG` | One IMU sample, one raw magnetometer sample and the compass calibration |
| `kode_sys_nfc_read_tag()`, `kode_sys_nfc_ndef_read()`, `_ndef_write_uri()`, `_ndef_write_text()` | `NFC_READ_RSP_SIG`, `NFC_NDEF_RSP_SIG` | Read a tag's identity, read or write its NDEF message |
| `kode_sys_nfc_emulate_start()`, `_stop()` | `NFC_EMU_RSP_SIG` | Present the Kode Dot as a passive NFC-A card until stopped |
| `kode_sys_rfid_read()`, `_write()`, `_emulate_start()`, `_emulate_stop()` | `RFID_OP_RSP_SIG`, `RFID_EMU_RSP_SIG` | Read an EM4100 ID, clone one onto a T5577, play one |
| `kode_sys_file_status()`, `_space()`, `_list()`, `_create_folder()`, `_delete()`, `_rename()` | `FILE_STATUS_RSP_SIG`, `FILE_SPACE_RSP_SIG`, `STORAGE_ENTRY_SIG` then `FILE_LIST_END_SIG`, `FILE_FOLDER_RSP_SIG`, `FILE_DELETE_RSP_SIG`, `FILE_RENAME_RSP_SIG` | What a path is, how big a volume (`"/sdcard"` or `"/storage"`) is and how much of it is free in whole kilobytes, a page of a directory (up to 24 entries; `more` asks for the next from `skip + count`), and the folder, delete and rename calls. Paths are absolute and virtual (`/sdcard/...`, `/storage/...`) and shorter than `KODE_SYS_FILE_PATH_MAX` (96) |
| `kode_sys_file_read(me, path, offset, buf, cap)` | `FILE_READ_RSP_SIG` | A window of a file starting at `offset`, 1 to `KODE_SYS_FILE_READ_MAX` (32 768) bytes, into your buffer; `got` below `cap` is the end of the file |
| `kode_sys_file_write(me, path, data, len, append)` | `FILE_WRITE_RSP_SIG` | 0 to 32 768 bytes of `data`, which is lent, appended to the file or replacing it. A bigger file is written in parts, each with `append` |
| `kode_sys_http_get_range(me, url, offset, buf, cap)` | `NET_HTTP_RSP_SIG` | The `cap` bytes of a resource from `offset` on, into your lent buffer. The answer's status says where the bytes start (206 at `offset`, 200 at byte 0, 416 nowhere) and `range_total` the length of the whole resource. It shares `kode_sys_http_get()`'s turn: one GET or range per Active Object at a time |
| `kode_sys_http_get_file(me, url, path)`, `kode_sys_http_file_stop(me)` | `HTTP_FILE_PROGRESS_SIG` per chunk, then `HTTP_FILE_RSP_SIG` | Downloads a URL into a file of any size, 32 KiB at a time, from the length the file already has: the same call after a cut goes on where it stopped. A bare name goes on the card when the card has taken a write, else inside. One download at a time on the board, and the board does not rest while it runs. The stop ends it with `stopped` set and keeps what was written (`sdk/kaos/storage`) |
| `kode_sys_net_lookup()`, `_net_ping()`, `_http_get()`, `_http_post()`, `_udp_send()` | `NET_LOOKUP_RSP_SIG`, `NET_PING_RSP_SIG`, `NET_HTTP_RSP_SIG`, `NET_UDP_RSP_SIG` | Name lookup, ping (up to `KODE_SYS_NET_PING_MAX`, 10), HTTP into your lent buffer, one datagram. Need Wi-Fi joined. In the answer `KODE_IO_ERROR` is no network and `KODE_DENIED` is the worker busy with another job |
| `kode_sys_wifi_scan()` | `WIFI_SCAN_ENTRY_SIG` per network, then `WIFI_SCAN_RSP_SIG` | The strongest `KODE_SYS_WIFI_SCAN_MAX` (24) networks; the entry carries the SSID, strength, channel, authmode and BSSID. `KODE_NO_RESOURCES` in the answer means the radio was busy, or the C5 sleeps between wakes for the board's rest: ask again. `KODE_DENIED` with `rest` true means an app rests the radio: ask again after `kode_sys_rest_end()`. `KODE_CANCELLED` means a newer Wi-Fi request took its place: do not ask again at once (`sdk/kaos/radio`) |
| `kode_sys_wifi_frames(me, on, channel)` | `WIFI_FRAMES_STATE_SIG`, `WIFI_FRAMES_TICK_SIG`, `WIFI_FRAME_SIG` | Hears Wi-Fi frames on one channel (1 to 177, or 0 to stay where the radio is). Receive only; the station is never moved |
| `kode_sys_ble_scan(me, ms)` | `BLE_SCAN_ENTRY_SIG` per device, then `BLE_SCAN_RSP_SIG` | A listen of 500 to 30 000 ms; a device that advertises repeatedly is listed once, at its strongest. The answer is `KODE_DENIED` while an app rests the radio (`rest` true) and with Bluetooth off in Settings (`rest` false), and `KODE_CANCELLED` when a newer Bluetooth request took its place |
| `kode_sys_ble_heard(me, on)` | `BLE_HEARD_STATE_SIG`, then `BLE_HEARD_SIG` per advertisement | Hears every BLE advertisement around, passively, until stopped: address, type, level, kind of packet and payload. One asker at a time; the stream ends with a reason when Bluetooth goes off, the board rests, the C5 updates or a newer Bluetooth request takes the radio (`sdk/kaos/radio`) |

### API: immediate reads and subscriptions

Calls of `kode_sys.h` that answer at once and touch no owner's queue.

| Call | What it does |
| --- | --- |
| `kode_sys_time_ms()`, `kode_sys_device_id()`, `kode_sys_clock_read()`, `kode_sys_clock_local()` | Milliseconds since boot, the serial, and the wall clock as Unix seconds or as local time; `KODE_ERROR` while the clock is unknown |
| `kode_sys_button_read_mask()`, `kode_sys_button_read_presses(id)` | The mask of buttons down (bit `1U << KODE_SYS_BUTTON_x`, x = `UP`, `DOWN`, `LEFT`, `RIGHT`, `TOP`, `BOT`), 0 before `kode_init()`, and the presses confirmed since boot. A press shows after `KODE_SYS_BUTTON_SETTLE_MS` (30 ms), so find an edge by comparing with the last call |
| `kode_sys_touch_subscribe(me)` | Subscribes `me` to `TOUCH_EVT_SIG`, the finger's reports, and links AO_Touch. A bare subscription links nothing |
| `kode_sys_ble_subscribe(me)` | Subscribes `me` to `BLE_APP_WRITE_SIG` (a write to the app's service), `BLE_APP_LINK_SIG` (a phone connected or left) and `BLE_APP_TAKEN_SIG` (a read took a value of a queued characteristic; `left` says how many remain), and links AO_Radio. Without `CONFIG_KODEOS_BLE` it answers `KODE_DENIED` |
| `kode_sys_ble_queue_room(chr, room)`, `kode_sys_ble_service_fault(why, cap)` | How many values a queued characteristic takes now, and whether the app's service was left out and why |
| `kode_sys_ble_pair_subscribe(me)`, `kode_sys_ble_hid_ready()` | Subscribes `me` to `BLE_PAIR_SIG`, the code to show, the end of a pairing and a pairing refused with no code (`KODE_SYS_BLE_PAIR_REFUSED`, told at most once in `KODE_BLE_PAIR_REFUSED_QUIET_MS`, 10 s), and links AO_Radio; and whether a host is subscribed to the reports of every kind served |
| `kode_sys_screen_is_asleep()` | Whether the display is asleep, by `kode_sys_screen_sleep()` or by the board's own rest: true from the moment the link is down until the glass is back |
| `kode_sys_ble_enabled()`, `kode_sys_wifi_status()`, `kode_sys_mqtt_status()`, `kode_sys_mqtt_is_connected()`, `kode_sys_battery_read()` | The radios' and the client's state and AO_Power's last reading. AO_Power also publishes `POWER_CRITICAL_SIG`, read as `kode_sys_battery_critical_t` (`critical`): the cell is critical on battery, once per fall and always before the readings that switch the board off, or that it is over. AO_Power always runs, so subscribing is all it takes. A kscreen app shows kscreen's notice by handing the event to `kscreen_critical()`, or its own by handling it itself (`sdk/kaos/power`) |
| `kode_sys_nvs_get(key, out, cap)` | The store, read back. `KODE_DENIED` means nothing was ever stored: the board is not provisioned, not a fault. Keys of at most 15 bytes and values of at most 191 |
| `kode_sys_haptic_is_holding()`, `kode_sys_nfc_is_emulating()`, `kode_sys_rfid_is_emulating()`, `kode_sys_console_congested()` | Whether a hold or an emulation is on, and whether the console is behind, so a producer of many records waits before its next slice |
| `kode_sys_exp_*()` | The expansion header J3: 14 positions, numbered 1 to 14 in the connector's order. `input`, `output`, `write`, `level`, `adc`, `pwm`, `irq`, `irq_enable`, `release`, `info`, `lend`, `return` and `ctrl` act on a position, and `kode_sys_exp_lend()` and `kode_sys_exp_ctrl()` take positions and an I2C, SPI or UART controller for a module you drive with ESP-IDF yourself |

The first call on J3 claims the header for the app. `KODE_EXISTS` means something in this image already owns it (the console, after one `exp pos=... mode=...` typed on the wire), and no later call succeeds in this boot. The header carries no identification, so the firmware that drives a module takes the module's positions with `kode_sys_exp_lend()` and every other call on them is refused. A UART on lent pins loses bytes while flash is written unless the image sets `CONFIG_UART_ISR_IN_IRAM`: a sector erase takes tens of milliseconds and the 128-byte FIFO fills in about 11 ms at 115200 baud.

An app that drives the LEDC itself, a servo on a lent position for example, clocks its timers from the PLL with `.clk_cfg = LEDC_USE_PLL_DIV_CLK` in `ledc_timer_config_t`. On the Kode Dot's ESP32-P4 (revision v3.2) with ESP-IDF v6.1, a timer clocked from XTAL stops the board with a store access fault the first time a channel is configured on it, because `ledc_channel_config()` clears the channel's fade parameters in the LEDC's gamma RAM and the fifth word, at `0x500d3410` (the panic's `MTVAL`), faults. `LEDC_AUTO_CLK` picks XTAL for low frequencies, such as 50 Hz at 14 bits for a servo. Seen on a Kode Dot in November 2026, also with a probe image that runs nothing of KodeOS first, which faults the same way on XTAL and runs on the PLL clock. `kode_pin_write_pwm()` and `kode_sys_exp_pwm()` already clock every timer from the PLL (`sdk/khal`).

### API: workers and the console's tables

The worker calls, and the three calls that add rows to the console's tables.

| Call | What it does |
| --- | --- |
| `kode_worker_start(me, ao, name, stack_bytes, prio, depth)` | Brings up a worker for `ao`, stack in PSRAM, once. `KODE_DENIED` for a `NULL` argument; `KODE_NO_RESOURCES` when the task cannot be had |
| `kode_worker_submit(me, fn, arg, done_sig, seq_out)` | Queues a job and never blocks; the result returns as `kode_worker_done_t` (`sdk/kqp`). `arg` stays valid until the done event. Only the Active Object the worker was started for submits to it |
| `kode_variables_add(table, n)` and `KODE_VARIABLES_ADD(t)` | Registers read-only state for `variable name="<row>" [watch=<ms>]` on the console. Up to 32 rows in 4 tables, `watch` 100 to 60000 ms |
| `kode_functions_add(table, n)` and `KODE_FUNCTIONS_ADD(t)` | Registers what the app does for `function name="<row>" [arg=]`. Up to 64 rows in 4 tables |
| `kode_config_add(table, n)` and `KODE_CONFIG_ADD(t)` | Registers stored settings for `config`. Up to 32 in 4 tables; the owner answers with `kode_config_answer()` |

A job's stack lives in PSRAM, so a job calls nothing that reaches the internal flash: ESP-IDF's flash, partition and NVS functions, and `kode_sys_nvs_get()`, which refuse there with `KODE_DENIED` and one error line.

A registration is refused whole, with an error line that names the entry:

- `KODE_EXISTS` for a name already taken.
- `KODE_NO_RESOURCES` past the limits.
- `KODE_DENIED` for any other rule, and always in a build without the console.

Every callback runs in AO_Console's task: return promptly and never block.

### The reset words

Line 4 of the banner takes its words from a closed table. A number not in it reads `unknown`.

| Reason | Words |
| --- | --- |
| `KDRV_RESET_UNKNOWN` | unknown |
| `KDRV_RESET_POWERON` | power-on or BOT+LEFT |
| `KDRV_RESET_EXTERNAL` | external reset |
| `KDRV_RESET_SOFTWARE` | software restart |
| `KDRV_RESET_PANIC` | panic |
| `KDRV_RESET_INT_WDT` | interrupt watchdog |
| `KDRV_RESET_TASK_WDT` | task watchdog |
| `KDRV_RESET_WDT` | other watchdog |
| `KDRV_RESET_DEEPSLEEP` | deep-sleep wake |
| `KDRV_RESET_BROWNOUT` | brownout |
| `KDRV_RESET_SDIO` | SDIO reset |
| `KDRV_RESET_USB` | USB port opened |
| `KDRV_RESET_JTAG` | JTAG reset |
| `KDRV_RESET_EFUSE` | eFuse error |
| `KDRV_RESET_PWR_GLITCH` | power glitch |
| `KDRV_RESET_CPU_LOCKUP` | CPU lockup |

### Kconfig options

Write `CONFIG_<NAME>=y` or `=n` in your project's `sdkconfig.defaults`. ESP-IDF links what it compiles, so without these options a firmware that uses kaos would get the console, the app manager and the radio whether it wanted them or not.

One rule runs through them: **a firmware always has the owners of its devices and can leave out every policy.** Device owners are never optional, because an unowned device is the failure the one-owner rule prevents.

A new option is not picked up by `idf.py build`: the configuration only regenerates on a CMake configure, so a `default y` compiles as unset and its code vanishes behind its `#if`. Run `idf.py reconfigure` and check with `grep CONFIG_<NAME> sdkconfig`.

A cached value in the generated `sdkconfig` beats a new default, so a changed board line needs that file deleted. Code reads these with `#if`, never a ternary: an unset Kconfig bool is undefined, not 0.

The options live under the menu "Kode Dot" (`components/kdefs/Kconfig`: the boot role and the power states) and the menu "kodeOS active objects" (`components/kaos/Kconfig`). In the Default column, "in kodeOS" means the option is on when the firmware's role is `KODEOS_BOOT_ROLE_OS` and off in an app.

In the OS role an optional owner starts when its option is on. In an app, AO_Radio, AO_Net (unless `KODEOS_CHANNEL` is on), AO_AppMgr and AO_Autotest start only when the app names one of their calls, and AO_LowPower, AO_Scheduler, AO_Console and AO_TestDot start when their option is on.

The first group holds the boot role and the policy owners.

| Option | Default | Depends on or selects | What it gates |
| --- | --- | --- | --- |
| `KODEOS_BOOT_ROLE_APP` | the default of the choice | | AO_Boot never writes otadata or the boot request, so the next reset returns to kodeOS, a crash on the first line included. An app installed through the mailbox starts again |
| `KODEOS_BOOT_ROLE_OS` | | selects `KODEOS_APPMGR` | AO_Boot clears otadata at startup, reports why the boot happened, hands the machine to a slot and runs the factory reset. A firmware that forgets to say what it is behaves like an app |
| `KODEOS_WELCOME_APP` | `welcome` | depends on the OS role | The project name of the app the first boot after a factory reset installs and runs. The factory reset keeps it and refuses to run without it |
| `KODEOS_HOME_HOLD` | y | depends on the app role | Holding BOT for 3 s (`KODE_HOME_HOLD_MS`) returns to kodeOS, so no app can trap the user, and the 600 ms hold stays the app's. The grace is `KODE_SYS_HOME_GRACE_MS` |
| `KODEOS_AUTOTEST` | n | selected by `KODEOS_CONSOLE` | AO_Autotest, the self-test rows and the walk over them. It owns no device |
| `KODEOS_CONSOLE` | in kodeOS | selects `KODEOS_APPMGR` and `KODEOS_AUTOTEST` | AO_Console, the command table. AO_Log still owns the console device without it, so the log works and nothing parses what you type |
| `KODEOS_APPMGR` | in kodeOS | | AO_AppMgr, which writes images into the apps region and the OTA slots. An app almost never needs it |
| `KODEOS_SCREENSHOT` | in kodeOS | | `screenshot`: a copy of the panel's framebuffer as a 402 KB BMP in PSRAM, held only while it is sent. Off, the verb says it is unavailable |
| `KODEOS_MIRROR` | in kodeOS | depends on `KODEOS_SCREENSHOT` | The JPEG mirror of the panel and its four verbs `mirror_start`, `mirror_stop`, `mirror_ack`, `mirror_info`, with its own BLE characteristic; about 530 KB of PSRAM when on. It does not gate `touch`, `tap`, `swipe` and `btn` injection |
| `KODE_COMPOSE` | n | | The passes of the pixel accelerator a renderer composes with (`kscreen_pic_*`, `sdk/kdrv/compose`), run by AO_Display, and the `compose` self-test row. Off, a pass is refused as not built |
| `KODEOS_NFC` | in kodeOS | | AO_Nfc, the owner of the ST25R3916B; an app that calls `kode_nfc_*` or `kode_sys_nfc_*` sets it to y. Off, the chip, SPI2 and `KBSP_RES_NFC` are the app's: nothing starts or parks the reader, and a call to `kode_nfc_*()` fails to link |
| `KODEOS_GUI` | | declared by kgui, not the SDK | Read once by the console's `ps` row `Gui`. An app built on the SDK alone has no such option |

The bench options, off by default:

| Option | Default | Depends on or selects | What it gates |
| --- | --- | --- | --- |
| `KODE_TEST_DOT` | n | needs `KODEOS_CONSOLE`, `KODEOS_RADIO` and `KODEOS_MIRROR` | AO_TestDot, the factory's final test driven over the cable, with `test component=all`, the `test_dot_*` verbs and the operator's screens. It takes level `KODE_PRIO_USER_LOW` (1) |
| `KODEOS_NFC_CERT` | n | depends on `KODEOS_NFC` | The held maximum-drive carriers of the NFC (13.56 MHz) and RFID (125 kHz) owners, for the FCC bench. Off, the `kode_cert_*_carrier()` calls refuse |

### Kconfig: radio, Wi-Fi and Bluetooth

The ESP32-C5 link and what runs over it.

| Option | Default | Depends on or selects | What it gates |
| --- | --- | --- | --- |
| `KODEOS_RADIO` | in kodeOS | selects `ESP_HOSTED_ENABLED` | AO_Radio, the ESP32-C5 link over SDIO. Without it the C5 is held in reset unless the app plays sound or sets `KODEOS_C5_RUN`, and there is no infrared. The microSD does not need it |
| `KODEOS_C5_HOLD` | n | depends on `KODEOS_RADIO` | Holds the C5 in reset while neither Wi-Fi nor BLE is wanted. A C5 in reset draws nothing and the amplifier shuts down with it; the first sound of a boot waits `KODE_C5_BOOT_MS` (600) |
| `KODEOS_C5_RUN` | n | | For an app that talks to the C5 its own way and has no AO_Radio: the core resets the C5 once at boot, leaves it running and claims it. It draws current until the next reset |
| `KODEOS_WIFI` | in kodeOS | depends on `KODEOS_RADIO` | The remote Wi-Fi stack and the `wifi_*` verbs |
| `KODEOS_WIFI_DEFAULT_ON` | n | depends on `KODEOS_WIFI` | What the stored `wifi` flag is on a board whose store was never written |
| `KODEOS_WIFI_AUTOJOIN` | y | depends on `KODEOS_WIFI` | Joins the strongest remembered network when the link comes up. It is the default of the stored `wifi_join`, and it does not turn Wi-Fi on |
| `KODEOS_BLE` | in kodeOS | depends on `KODEOS_RADIO` and `BT_NIMBLE_ENABLED` | BLE: NimBLE on the P4, the controller on the C5, HCI over the same SDIO link. The board file sets `BT_NIMBLE_ENABLED`, so an app that wants Bluetooth only sets `CONFIG_KODEOS_BLE=y` (and `CONFIG_BT_ENABLED=y`) |
| `KODEOS_BLE_DEFAULT_ON` | y | depends on `KODEOS_BLE` | The same for the stored `ble` flag: BLE advertises from boot until the user switches it off |
| `KODEOS_BLE_AT_BOOT` | n | depends on `KODEOS_BLE` | BLE on from every boot, ignoring the store. For a bench or lab build, not a shipped kodeOS |
| `KODEOS_BLE_CONSOLE` | in kodeOS | depends on `KODEOS_BLE` and `KODEOS_CONSOLE` | The console GATT service: the same verbs and grammar as the USB-C cable. The app's own service needs it |
| `KODEOS_BLE_CONSOLE_PAIRING` | y | depends on `KODEOS_BLE_CONSOLE` | LE Secure Connections, bonded. Off, the service is open to anyone in range. Needs `CONFIG_BT_NIMBLE_SM_SC_ONLY=0`, which is an int and not a bool: written as `=y` it fails the type check so quietly that it looks as if it worked |
| `KODEOS_BLE_PAIRING_PASSKEY` | y | depends on `KODEOS_BLE_CONSOLE_PAIRING` | Passkey entry with the board showing six digits on the glass in kodeOS. In an app a new pairing is refused and a phone bonded in kodeOS reconnects; only an app that serves the Bluetooth mouse or keyboard pairs a device, in the time it opens, and shows the code itself. The digits never reach a log or a console verb |
| `KODE_BLE_APP_VALUE_MAX` | 244 (20 to 512) | depends on `KODEOS_BLE` | The longest value of the app's service, and the longest write `ble_written` carries. Over 244 the values travel in a tier of events of their own, in PSRAM |
| `KODE_BLE_ADVERTISE_APP_SERVICE` | n | depends on `KODEOS_BLE` | The advert carries the UUID of the app's service instead of the console's. The console is still served, and a client that filters on its UUID stops finding the board. With no service declared the advert stays as it is |

### Kconfig: network and the Kode channel

AO_Net and what it keeps up.

| Option | Default | Depends on or selects | What it gates |
| --- | --- | --- | --- |
| `KODEOS_NET` | in kodeOS | depends on `KODEOS_WIFI` | AO_Net: ping, HTTP(S) and UDP on the P4's own lwIP |
| `KODEOS_MQTT` | in kodeOS | depends on `KODEOS_NET` | The MQTT client, owned by AO_Net. The component downloads either way; this gates compiling and linking it |
| `KODEOS_CHANNEL` | in kodeOS | depends on `KODEOS_MQTT` and `KODEOS_CONSOLE` | The Kode channel: AO_Net signs in through the C5 and keeps one MQTT session up. The stored `chan` setting (default on) switches it. It holds the one MQTT client, so an app that uses `kode_mqtt_*` or `kode_sys_mqtt_*` leaves it off |
| `KODEOS_CHANNEL_RENEW_S` | 82800 (60 to 82800) | depends on `KODEOS_CHANNEL` | Seconds from a connect to the renewal; the token lives 24 h. Shorten only on a bench |
| `KODEOS_SHOT_HTTP` | y | depends on `KODEOS_CHANNEL` and `KODEOS_MIRROR` | Uploads the glass as one JPEG to the channel's `shots` link |
| `KODE_HTTP_OFFSET_64` | n | | `kode_http_off_t`, the offset of the two ranged GETs, is 64 bits instead of 32, for resources past 4 GB. A download into a file stays within FAT32's 4 GB |

### Kconfig: rest and schedule

The two Active Objects that decide and own no device. Both are off in the SDK and on in kodeOS, and the two are independent.

| Option | Default | Depends on or selects | What it gates |
| --- | --- | --- | --- |
| `KODE_LOWPOWER` | n in the SDK, y in kodeOS | depends on `KODEOS_RADIO`; selects `PM_ENABLE`, `FREERTOS_USE_TICKLESS_IDLE` and `PM_LIGHT_SLEEP_CALLBACKS` | AO_LowPower and the states AWAKE, ASLEEP and OFF (`sdk/kaos/lowpower`), the sleep sentinel of the radio, the rest of every owner, `kode_boot_gate()`, the settings `sleep_after` and `off_after`. Off, `kode_sys_power_sleep()` and `kode_sys_power_off()` log `low power not built`, `sleep` and `power_off` answer `not_built`, and `lowpower_info` does not exist |
| `KODE_LOWPOWER_IDLE` | y | depends on `KODE_LOWPOWER` | AO_LowPower goes ASLEEP after `sleep_after` with no input. Off when the app's interface decides when the board rests, as kodeOS does; the `sleep_after` setting is then not offered |
| `KODE_SCHEDULER` | n in the SDK, y in kodeOS | | AO_Scheduler, the table of cron entries and the verb `cron` (`sdk/kaos/scheduler`). It takes the level of `KODE_PRIO_USER_HIGH` (16), which is then not defined. Off, the calls of `kaos.h` refuse and `cron` answers `not_built` |

A new Kconfig option is not picked up by a plain `idf.py build`. After adding or changing either one, run `idf.py reconfigure` and read `grep CONFIG_KODE_LOWPOWER sdkconfig`, because a build that is suspiciously clean may have compiled the option as unset. Light sleep also needs three lines in `sdkconfig.defaults`, which kodeOS carries: `CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=n`, `CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=n` and `CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION=y`.

### Kconfig: the other components

The other components have menus of their own.

| Option | Default | Depends on | What it gates |
| --- | --- | --- | --- |
| `KLOG_MAXIMUM_LEVEL_*` | debug | a choice | The most verbose klog level compiled in: debug, info, notice, warn, error or none. A line below it is not in the firmware, and `log_level` cannot bring it back. kodeOS keeps notice or more, because the factory reads the banner |
| `KLOG_DEFAULT_LEVEL_*` | info | a choice, never more verbose than the ceiling | The level the console starts at, until `log_level` stores another: debug, info, notice, warn, error or off |
| `KQP_AO_WATCH` | y | | The Active Object watchdog (`sdk/kqp`) |
| `KQP_AO_STEP_MAX_MS` | 5000 (100 to 10000) | `KQP_AO_WATCH` | The longest step before the warning |
| `KHAL_CONSOLE_DOCK` | n | the ESP32-P4 target | A second console on the magnetic dock, USB CDC on GPIO26 and 27. Off in the SDK, because it takes the OTG controller an app may want. Pulls in `esp_tinyusb` 2.2.0, so the first configure of a clean tree reports the TinyUSB symbols as unknown |
| `KHAL_CONSOLE_DOCK_TX_WAIT_MS` | 20 (0 to 200) | `KHAL_CONSOLE_DOCK` | How long a write waits for the dock host to drain before it drops the rest |
| `KSCREEN_ROTATE_PAD` | y | | When an app turns the glass, the four pad buttons publish the direction they point on the turned glass (`sdk/kscreen`) |

The settings the board file fixes (flash size, the partition table at `0x8000`, HEX PSRAM at 250 MHz, the 128 KB L2 cache, the SDIO wiring, the NimBLE lines, the LVGL block) live in `components/kbsp/sdkconfig.board` (`sdk/kbsp`) and every firmware reads it first.

Two lines an app spells out itself: `CONFIG_PARTITION_TABLE_CUSTOM_FILENAME`, because ESP-IDF resolves it against the project, and `set(IDF_TARGET esp32p4)` before `project()`. This is what most examples write:

```text
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="managed_components/kodediy__kbsp/partitions.csv"
CONFIG_KODEOS_BOOT_ROLE_APP=y
CONFIG_KODEOS_CONSOLE=y
CONFIG_KODEOS_SCREENSHOT=n
CONFIG_KODEOS_RADIO=n
CONFIG_ESP_HOSTED_ENABLED=n
CONFIG_BT_ENABLED=n
```

To have no radio, set both `KODEOS_RADIO=n` and `ESP_HOSTED_ENABLED=n`. `KODEOS_RADIO` selects the second, and `kdrv` depends on `esp_wifi_remote`, whose presence makes `ESP_HOSTED_ENABLED` default to `y`: the component then installs a constructor that claims the SDMMC controller before `app_main`.

Kconfig cannot express "deselect", so a firmware that wants no radio says the opposite out loud. The `BT_ENABLED=n` line drops the NimBLE host the board file switches on.

## Gotchas

> **WARNING**
>
> **A standard call from an Active Object fails.** Every `kode.h` call blocks, so one made from an Active Object or an ISR is refused, and `kode_error()` says to call `kode_sys_*` instead. A blocking call inside a state handler would park the whole Active Object, and after 30 s the watchdog panics the board (`sdk/kqp`). Call them from `app_main()` or a task of your own, or run them as a job on a worker and take the result as an event.

> **WARNING**
>
> **`KODE_DENIED` is a refusal to try, not a verdict.** A second request of the same kind from the same asker, a malformed path, a call whose owner the build left out, or AO_Storage busy with a `cat`, a `cp` or an install all say it. Wait for the answer, or a moment, and ask again.

> **NOTE**
>
> **A command returns before anything happens.** `KODE_OK` from `kode_sys_led_set_rgb()`, `kode_sys_audio_tone()`, `kode_sys_ir_send_nec()` or `kode_sys_mqtt_publish()` means the request is queued. A codec in use, a dry pool inside the owner or a broker that never answers shows up in the log or as a later event. For an answer, subscribe: `POWER_CTRL_SIG`, `MQTT_STATE_SIG`, `AUDIO_DONE_SIG` and the others in `sdk/events`.

> **NOTE**
>
> **One touch of J3 claims all fourteen positions until the next boot.** Nothing releases the expansion header's resource, and `KODE_EXISTS` is permanent for that boot, so do not retry it. J3's `+3.3V_EXT` supply is not promised at the start of an app: call `kode_pin_power_3v3(true)` or `kode_sys_exp_power(true)` before you talk to a module, and wait for the module to answer.

## Example code

Poll the buttons from a loop. The LED shows green while TOP is held and red while the pad is held, and the bottom button hands the Kode Dot back to kodeOS.

```c
/*
 * led_follow.c - from Kode with love
 *
 * Polls the buttons from the main task. The LED turns green while TOP is
 * held, red while any pad button is held, and goes dark otherwise. BOT hands
 * the Kode Dot back to kodeOS.
 */
#include "kode.h"

/* Bring the system up, then follow the buttons forever. */
void app_main(void)
{
    kode_init();

    while (true) {
        const kode_buttons_t down = kode_button_read_all();

        if (down.bottom) {
            kode_exit();
        }
        if (down.top) {
            kode_led_set_rgb(0, 255, 0);
        } else if (down.up || down.down || down.left || down.right) {
            kode_led_set_rgb(255, 0, 0);
        } else {
            kode_led_off();
        }
        kode_delay(20);
    }
}
```

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/kode`](https://github.com/kodediy/kode-sdk/tree/main/components/kode): the standard layer, with `include/kode.h` holding the contract of every function.
- [`components/kode_sys`](https://github.com/kodediy/kode-sdk/tree/main/components/kode_sys): `kode_init()`, `kode_sys.h` and the worker.
- [`components/kdefs/Kconfig`](https://github.com/kodediy/kode-sdk/blob/main/components/kdefs/Kconfig) and [`components/kaos/Kconfig`](https://github.com/kodediy/kode-sdk/blob/main/components/kaos/Kconfig): the build options, with their reasons.
