Introduction
ROHI (Robonomics Open Hardware Interface) is an open ecosystem for IoT firmware built around a common control protocol. Firmware that implements the protocol can be operated by shared clients, whether it was written by the ROHI developers, the community or you.
One App. Any Firmware.
The SDK in this repository is the Rust toolkit behind it: libraries, a reference firmware for
Altruist Urban and the rohi desktop client, for devices powered by the
Robonomics network.
Where to start
| I want to… | Start here |
|---|---|
| understand what ROHI is and what works today | Why ROHI?, Current capabilities |
| operate a ROHI device | Use a Device: Desktop application |
| know whether my hardware is supported | Supported devices |
| write firmware | Build Firmware: Core concepts, Create & customize |
| trust or share a firmware | Verify & Share |
| look something up | the crate rustdoc |
How the documentation is organised
| Place | Responsibility |
|---|---|
| This book | vision, current capabilities, user journeys, tutorials, navigation |
Crate rustdoc (cargo doc --no-deps) | APIs, contracts, ownership, resource constraints, integration examples |
| Source and protocol definitions | authoritative schemas, implementations, tests, platform behaviour |
| Support matrix | hardware compatibility, firmware support, verification levels and evidence |
The book explains how to use and extend ROHI; the crates explain how ROHI works internally. See Documentation style and policy.
The book assumes basic Rust knowledge for the firmware sections. If you are unsure about any language aspects, please refer to the Rust book.
Contributing
ROHI SDK is free and open source. You can find the source code on GitHub, where issues and feature requests can be posted on the issue tracker. The project relies on community contributions to fix bugs and add features - if you’d like to help, please consider opening a pull request.
License
The ROHI SDK source and documentation are released under the Apache v2.0.
Why ROHI?
Most connected devices ship with a firmware, an app and a cloud that only work together. Changing one means rebuilding the others, and a firmware written by someone else cannot be operated with the tools you already have.
ROHI separates the three:
Applications rohi (desktop), mobile app (planned)
│ generic: they know no firmware by name
▼
Control protocol config · status · action, discovered from the device
│ transport independent, BLE implemented
▼
Firmware built from reusable components, any firmware that speaks the protocol
- Reusable firmware components. Sensor drivers, a power-fail-safe configuration store, Wi-Fi and IP networking, time, telemetry, device identity and a BLE control plane are libraries with documented contracts. A firmware is a composition of them; Altruist Urban is the reference.
- Shared applications. A client learns what a device offers from the device itself: its settings, its live status and its operations. A new firmware module shows up in the client without changing the client.
- AI-assisted customization. Because the pieces, their contracts and their support status are written down, in rustdoc, in the book and in the machine-readable support matrix, an assistant can adapt a firmware without guessing what is verified.
- Local first. Configuring and operating a device needs Bluetooth and no cloud account. Robonomics network integration (signed telemetry, identity) is an addition, not a prerequisite.
What ROHI is not
ROHI does not introduce another RTOS (it is built on Embassy and esp-hal), it does not require
a central approval of firmware, and it makes no hardware support claim that the
support matrix cannot back with evidence.
Next: One App. Any Firmware..
One App. Any Firmware.
A ROHI client does not contain knowledge of a particular device. It talks to the device through the ROHI control protocol, and the device describes itself with three kinds of things:
| Concept | The user asks | The firmware provides |
|---|---|---|
| Config | what is the device set up to do? | typed settings with defaults, validation and persistence |
| Status | what is it doing now? | live health, metrics and active issues |
| Action | what can I ask it to do? | discoverable operations with typed arguments and results |
Because these are described by schemas the device sends, the same client can show the settings of an Altruist Urban today and those of a firmware that did not exist when the client was built.
firmware A ─┐ ┌─ rohi desktop (implemented)
firmware B ─┼─ control protocol ───────┼─ mobile app (planned)
your firmware ┘ over BLE today └─ your own client
What this gives you
- Users keep one tool for every compatible device: Use a Device.
- Firmware authors get configuration, diagnostics and operations in generic clients for free: Build Firmware.
- The community can publish firmware without a client per firmware, and users can tell what has been checked: Verify & Share.
Implemented and planned
| Piece | State |
|---|---|
| Control protocol v1 (protobuf), schema-driven config, status, actions | implemented; still under development, keep client and firmware on the same revision |
| BLE as the control transport | implemented |
| TCP as a control transport | implemented for the std Altruist Urban (tcp://127.0.0.1:9300, independent of BLE); no TCP transport on hardware |
| Other transports | planned |
rohi desktop client | implemented |
| Shared mobile application | planned, not implemented: Mobile application |
| BLE pairing and encryption | not implemented: BLE control is open, anyone in radio range can use the control plane |
| Firmware distribution and verification infrastructure | not implemented: Firmware distribution |
See Current capabilities for the supported hardware and sensors.
Current capabilities
What exists today. Hardware and verification details are authoritative in the support matrix; this page is an overview.
| Area | State |
|---|---|
| Boards | Altruist Urban on ESP32-C3 and ESP32-C6, plus headless Altruist Insight on ESP32-C6 with SCD41 and BLE Control only. The C6 pin maps and Insight runtime are not verified on hardware; see the Insight workflow and security limits. |
| Sensors | BMP280/BME280, SCD40/SCD41, SDS011, I²S microphone noise level (unweighted dB SPL, not dBA). See Sensors. |
| Configuration | typed sections in a power-fail-safe store; only the user’s overrides are persisted: Configuration store |
| Networking | Wi-Fi station, DNS and TCP: Networking |
| Services | config, status and actions of every module, discovered by name: Service pipeline |
| Control | local BLE control plane and the rohi desktop client, without pairing: Control plane |
| Telemetry, time, identity, location | Telemetry, Time, Identity, Location |
| Logging | persistent, rotated, compressed device log in internal flash, read with rohi logs; SD backend not implemented: Device log, Logging |
| Hardware validation | host tests and CI builds for both chips; hardware results are mostly not yet recorded: Hardware testing |
Not available
- A mobile application, other control transports and firmware distribution infrastructure: planned, see One App. Any Firmware..
- Support for other boards. Adding one is described in Add or support a board.
How to read the status words used here (implemented, integrated, built, verified): Reading the support matrix.
Getting started with a device
This section is for people who operate ROHI devices. If you write firmware, start with Build Firmware.
1. Check that your device is supported
Look up the board in the support matrix. It says which firmware targets the board and what has been verified on hardware. The Altruist Urban and headless Altruist Insight have firmware targets; Insight’s SCD41 and BLE integration are not yet verified on hardware. See Insight instructions and security limits.
2. Get a firmware onto the device
The reference firmware for the Altruist Urban is in firmwares/altruist-urban.
Build and flash it as described in Quick start and First device.
This repository does not publish pre-built firmware images.
3. Connect with a client
A flashed device advertises over Bluetooth LE. The rohi desktop application finds it and operates it:
rohi scan # find the device
rohi status # health and every service
rohi config # the settings the device offers
rohi action # the operations the device offers
| Workflow | Page |
|---|---|
| Find a device and connect | Discovery & connection |
| Inspect and change settings | Configuration |
| Check health, services and issues | Status & diagnostics |
| Run device operations | Actions |
| Script all of the above | Automation |
A shared mobile application is planned but not implemented.
Limits to know about
- The control link is not encrypted or authenticated yet: anyone in Bluetooth range can configure the device.
- A device accepts one connection at a time.
- Keep
rohiand the firmware on the same revision: the control protocol is still changing.
Desktop application
rohi is the desktop command line for ROHI devices. It finds a device over Bluetooth LE, shows the status of its
services, reads and changes its configuration, and runs its actions. It is the quickest way to check
that a flashed device (see First device) is alive and talking.
rohi is a thin layer over the Device API of the rohi library, and the
command tree knows no device module: status, config and action take the names of services, sections and
actions that the device lists, and parse values with the field descriptions the device sends (type, unit, enum variants; the wire carries ids and numbers, the tool translates them with the schema). A new firmware module
appears in rohi without changing the tool. The tool owns only the terminal side: arguments, device selection,
prompts, output formats and configuration files.
The behaviour described here is covered by host tests against an in-memory device. It has not been exercised with a wide range of adapters and operating systems.
Install and run
rohi is a package of the workspace, tools/rohi. From the repository root (inside nix develop if you use Nix):
cargo install --path tools/rohi # installs `rohi` into ~/.cargo/bin
cargo run -p rohi -- status # or run it without installing
On Linux the build needs libdbus and pkg-config (provided by nix develop) and protoc; see
Targets and features. Bluetooth must be enabled, and the device must be
advertising and not connected to another client: a device accepts a single connection at a time.
rohi --help and rohi <COMMAND> --help describe every command with examples. Keep the tool and the firmware from the
same revision: the control protocol is under development and a stale rohi can show an incomplete view of a newer
device (for example fewer fields of a section).
First steps
rohi scan # find nearby ROHI devices
rohi info # firmware name and build identifier
rohi status # device health and every service
rohi status sensors # one service in detail
rohi config # the configuration sections of the device
rohi action # what the services can do
$ rohi status
Device: altruist-urban-0.4.0 (urban-esp32c3)
Uptime: 2h 14m
Health: ok
SERVICE HEALTH
wireless ok
connectivity ok
...
What the columns mean and how status differs from configuration is explained in Services and status.
Commands
| Command | What it does |
|---|---|
scan | discover nearby devices |
status [SERVICE] [--watch] | device summary or one service |
config [SECTION] [FIELD=VALUE...], config reset SECTION | list, show and change configuration sections |
config export, diff, apply | configuration files (your overrides) |
action [SERVICE] [ACTION] [ARG=VALUE...] | list and run the actions of the services |
SERVICE [ACTION] [ARG...] | the same actions with positional arguments, for example system reboot and system factory_reset |
logs [-n N] [-f], logs download [-d DIR], logs clear | show and follow the latest records in RAM, save and clear the archive of the device log |
Each command has its own page: Discovery & connection, Configuration, Status & diagnostics, Actions, Device log and Automation.
Migrating from earlier versions
| Before | Now |
|---|---|
rohi sensors | rohi status sensors |
rohi time | rohi status time |
rohi wifi (status) | rohi status wireless |
rohi wifi scan | rohi action wireless wifi_scan |
rohi wifi reconnect, disconnect | rohi action wireless wifi_reconnect / wifi_disconnect |
rohi wifi configure, forget | rohi config wireless wifi_ssid=.. wifi_password=-, rohi config reset wireless, then rohi status wireless |
rohi connectivity set --host .. | rohi config connectivity host=.. |
rohi config list, config describe <section> | rohi config, rohi config <section> --help |
rohi config get <section>, config set <section> .. | rohi config <section>, rohi config <section> FIELD=VALUE |
rohi config unset <section> <field> | rohi config <section> FIELD=null (removes the override) |
rohi action list, describe, run | rohi action, rohi action <service> <action> --help, rohi action <service> <action> |
rohi backup export / import | rohi config export / apply |
rohi reboot | rohi system reboot |
rohi factory-reset [--yes] | rohi system factory_reset: no confirmation prompt, and no automatic reboot (run rohi system reboot when restart_required says so) |
The reboot and the factory reset are ordinary actions of the system service, not requests of their own.
Discovery & connection
Commands that operate on a device first find it and open a Bluetooth LE link to it. This page covers how the device is chosen and what to check when that fails. No Wi-Fi or cloud connectivity is needed: the link is local BLE.
rohi scan # list nearby ROHI devices
Choose a device
| Situation | What rohi does |
|---|---|
| One device found | uses it |
| Several devices, interactive terminal | shows a numbered list on stderr and asks |
| Several devices, no terminal | fails and lists them; it never picks one for you |
-D, --device <DEVICE> | uses the device that matches; fails if none or more than one does |
--device (-D) accepts the exact platform ID, the exact advertised name, or a unique prefix or suffix of either
(A12F for ALTRUIST-URBAN-A12F). Setting ROHI_DEVICE is the same as passing --device.
rohi -D A12F status
export ROHI_DEVICE=ALTRUIST-URBAN-A12F
The value may also be a URI, so the transport is explicit: ble://ALTRUIST-URBAN-A12F. Without a scheme the transport
follows from the content: host:port is TCP, anything else is a Bluetooth name or ID. tcp://HOST:PORT connects to a device
that serves the control protocol over a socket, today the std Altruist Urban; a real
device is reached over BLE.
--scan-timeout <SECONDS> bounds the search for the device (or the connection to a TCP endpoint) and --timeout <SECONDS> the wait for each response. A scan
without --device keeps looking for a couple of seconds after the first device appears, so a second device can show up.
Troubleshooting
| Symptom | Check |
|---|---|
no ROHI device found | Bluetooth is on, the device is powered and advertising, no other client holds its connection; raise --scan-timeout |
timed out waiting for the device | the device is in range; raise --timeout |
multiple ROHI devices found | pass --device or set ROHI_DEVICE; rohi scan lists them |
the device has no section … / NotFound | the name is not one the device lists: rohi config, rohi status, rohi action |
| a section shows fewer fields than expected | the tool is older than the firmware; rebuild rohi from the same revision |
the device refused the request: permission denied | the change needs an encrypted or authenticated link, see Control plane |
Configuration
The firmware defines which settings exist, their types, units, defaults and validation; rohi discovers them from the device, so a setting of a new firmware module appears without changing the tool. How a firmware defines a section is in Config.
rohi config works on the sections the device lists. The configuration of a section is its effective
configuration: the defaults of the firmware plus the overrides you set explicitly. Fields are typed and described by
the device; values are parsed against that description (true/false, numbers, text, hex for bytes, a variant name for
enums) and checked again by the device.
rohi config # sections and their versions
rohi config wireless # the effective values; secrets are shown as <redacted>
rohi config wireless --help # fields: type, unit, allowed values (from the device)
rohi config wireless wifi_ssid=office wifi_scan_timeout=20000 --dry-run
rohi config wireless wifi_ssid=office wifi_password=- # secret from stdin or a hidden prompt
rohi config wireless wifi_ssid=none # disable Wi-Fi (no ssid is the default)
rohi config wireless wifi_scan_timeout=null # remove the override: back to the firmware default
rohi config wireless wifi_password=none # explicit "no value": an open network
rohi config wireless ip_mode=static ip_address=192.168.1.50 ip_prefix_len=24 ip_gateway=192.168.1.1
rohi config wireless ble_name=kitchen # applies after a reboot
rohi config reset wireless # remove every override of the section
A name that is also a command (reset, export, diff, apply) is not a valid section name. rohi config --help
and rohi action --help need no device; rohi config SECTION --help connects and is generated from the schema.
$ rohi config wireless
wifi_ssid office
wifi_password <redacted>
wifi_scan_timeout 20000 ms
wifi_connect_timeout 30000 ms
wifi_backoff_initial 1000 ms
wifi_backoff_max 60000 ms
wifi_link_refresh 10000 ms
ip_mode dhcp
ip_address <unset>
ip_prefix_len <unset>
ip_gateway <unset>
ip_dns <unset>
ip_hostname <unset>
ip_dhcp_timeout 20000 ms
ble_name <unset>
An optional field without a value shows as <unset> when it follows a default that has none, and as <none> when you
set it to no value explicitly. After a change rohi reads the section
again and prints what the device reports, so the output is always the effective result.
Format the whole configuration storage of the device with the system factory_reset action (not a config
subcommand, and with no confirmation prompt): every section, the device identity and anything else stored in the
partition is erased, including section versions, and a damaged storage is repaired. The runtime returns to the
defaults and the device is unprovisioned afterwards. Persistent logs and unrelated storage are not touched. The action
does not reboot the device; its result restart_required tells whether a restart is needed, and system reboot does
it.
rohi system factory_reset
rohi system reboot
$ rohi config connectivity --help
Usage:
rohi config connectivity [FIELD=VALUE...]
Fields:
enabled bool
node_id u64
interval_s u64 s
host string
port u64
Special values:
FIELD=null clear the override and use the field default
...
- Effective = defaults + overrides. A field you never set keeps following the firmware default, also after a firmware update changes it; a field you set stays as you set it.
FIELD=VALUEis a patch of overrides: fields that are not mentioned are not touched. All mutations of one command are applied to a copy, the complete effective result is validated on the device and stored atomically: if anything is invalid, nothing is stored.--dry-runvalidates without storing.- The result of every change is validated as
defaults + overrides; an unconfigured or disabled section (nowifi_ssidmeans Wi-Fi is disabled, no location, connectivity disabled) is a valid state. Fields that belong together are therefore set in one command:rohi config connectivity enabled=truealone fails until thehostis set,rohi config connectivity enabled=true host=ingress.example.orgworks. - Three states for a nullable field.
FIELD=valueis an explicit value,FIELD=noneis an explicit “no value” (rohi config wireless wifi_password=noneconfigures an open network,rohi config time server2=nonedisables the second NTP server) andFIELD=nullremoves the override, so the field follows the current firmware default again (rohi config time server2=nullrestores the firmware’s second server).noneis only valid for fields that--helpmarksnullable;rohirefuses it for any other field before contacting the device.FIELD=nullworks for any writable field, required or not. - Secrets (
secretin--help) are never returned and never part of exports. PutNAME=-instead of a value; the tool refuses a secret on the command line.wifi_password=noneandwifi_password=nullare allowed: they carry no secret. - Reset removes every override of the section, so the firmware defaults apply again.
- A change that needs a restart says so (
A restart is required for the change to take effect).
Configuration files
A file describes your overrides, not the defaults:
rohi config export config.json # or: rohi config export > config.json
rohi config diff config.json # what applying would change
rohi config apply config.json --dry-run # validate everything, change nothing
rohi config apply config.json
A file maps section names to their fields:
{
"wireless": { "wifi_ssid": "office" },
"connectivity": { "enabled": true, "interval_s": 120, "host": "ingress.example.org", "port": 443 },
"location": { "latitude": 52.52, "longitude": 13.405 }
}
| In the file | Effect |
|---|---|
"field": value | set the override (even if the value equals the default) |
"field": null | remove the override (follow the firmware default) |
"field": {"none": true} | explicit “no value” of a nullable field (distinct from null) |
| field missing | left unchanged |
"section": null | reset the section (remove every override) |
- Export writes the explicit overrides only, never materialized defaults, so a later firmware default still
reaches fields you did not override. A nullable field you set to no value is written as
{"none": true}. Sections without overrides are omitted; secrets and read-only fields are left out, so applying an exported file never clears or overwrites a secret. - A file cannot contain secrets:
config applyrefuses them and points atconfig SECTION NAME=-. diffcompares the file with your overrides on the device and prints~changes,+new overrides,-removed overrides andreset section; nothing is changed. Fields that already match are not listed.applychecks the whole file against the schemas first (unknown section, unknown or read-only field, wrong type fail with no change), then has the device validate every section with a dry run, shows the changes and asks for confirmation unless--yes, then applies the sections one by one. Each section is atomic; applying several is not atomic as a whole. If the device fails in between, the error lists the sections that were applied and the ones that were not. Every section is applied against the revision its diff was computed from, so a section that another client changed after the diff was shown fails with a conflict instead of being overwritten.- The backup of earlier versions (
rohi backup) is replaced byexport/apply; an old backup file is not understood.
Status & diagnostics
This page explains how to see what each service of a device is doing and how that differs from configuring it, using rohi. Nothing here is specific to a module: the device describes its services, sections and actions, and the tool shows them. How a firmware reports status is in Status.
Commands
rohi status # device health and one row per service: one compact request
rohi status network # one service: values with units, active issues
rohi status --watch # reprint when something observable changed (Ctrl-C to stop)
rohi status network --watch --interval 5
rohi -o json status network
Services are discovered from the device, so rohi status <name> works for any service the summary lists. Without a
service the output is the summary table; with -o json it is
{ "device": .., "uptime_ms": .., "health": .., "services": [..] }. The sections below explain health,
issues and revisions.
Four questions, four places
Capability what can this firmware do? (kept for runtime operations, e.g. firmware update)
Config what is it set up to do? persistent, desired state rohi config ...
Status what is it actually doing now? live, observed state, read-only rohi status ...
Actions what can I ask it to do? explicit operations rohi action ...
Diagnostics what happened before? logs, history rohi logs ...
The same service appears in several places, never mixed:
$ rohi config connectivity # desired: what it is set up to do (defaults + your overrides)
enabled true
node_id 42
interval_s 60 s
host ingress.example.org
port 443
$ rohi status connectivity # observed: what is happening now
Service: connectivity
Health: degraded
frames_created 212
frames_delivered 209
send_retries 7
frames_rejected 0
queue_depth 3
frames_without_location 212
Issues:
WARNING no_location (34s)
The device summary
rohi status is one compact request: the device health and one row per service. It stays small however many
fields a service has.
$ rohi status
Device: altruist-urban-0.4.0 (urban-esp32c3)
Uptime: 2h 14m
Health: degraded
SERVICE HEALTH
network ok
connectivity degraded
time ok
sensors ok
identity ok
location -
Health is the one common indicator of a service:
| Health | Meaning |
|---|---|
ok | working |
degraded | works with reduced capability, or something is wrong (telemetry without a location, a Wi-Fi that lost its link) |
error | not working |
- (unknown) | not known yet (Wi-Fi is still connecting) or not in use: turned off by configuration or never set, which is not an error |
What else a service has to tell, such as a link state or a sensor state, is a value of that service in
rohi status <service>.
Device health
Health: in the header is decided by the firmware, not computed by the tool. The firmware knows which services
are mandatory, optional or redundant: a cellular modem may be degraded while Ethernet is fine. With the default policy
an essential service with error health makes the device error, a degraded service makes it degraded, and
services with unknown health do not count.
One service in detail
rohi status <service> adds the service-specific values the device describes (with their units) and the active
issues:
$ rohi status wireless
Service: wireless
Health: ok
wifi_state connected
wifi_ip 192.168.1.42
wifi_rssi -61 dBm
wifi_reconnects 0
heap_free 41200 B
An issue has a stable machine-readable code (connection_timeout, no_location), a severity, a message and an
age. Scripts react to the code, people read the message. Only issues that are active now are listed; history is
diagnostics. With -o json the values are keyed by field name and carry their units:
$ rohi -o json status wireless
{
"schema_version": 1,
"service": { "service": "wireless", "health": "ok", "revision": 3, ... },
"values": { "wifi_state": "connected", "wifi_rssi": -61, "wifi_ip": "192.168.1.42" },
"units": { "rssi": "dBm" },
"issues": []
}
Watching
$ rohi status --watch # reprint when something observable changed
$ rohi status connectivity --watch --interval 5
Every service has a status revision that changes when its health or active issues change. A
summary watch polls the compact summary and prints again only when a revision (or the device health) moved, so it
stays cheap. Values that vary all the time (counters, signal strength) do not change the revision; rohi status <service> --watch re-reads the detail on every poll and prints when what is shown changed. Stop with Ctrl-C.
Doing things: actions
Status never changes anything. Operations are actions, listed and described by the device:
$ rohi action
SERVICE ACTION ACCESS
wireless wifi_scan read
wireless wifi_reconnect mutate
wireless wifi_disconnect mutate
identity provision provision
identity erase mutate
system reboot mutate
system factory_reset provision
$ rohi action wireless # the actions of one service, with their arguments
$ rohi action wireless wifi_scan --help # arguments and results, from the device schema
$ rohi action wireless wifi_scan
SSID RSSI CHANNEL SECURITY
office -50 dBm 6 wpa2
guest -70 dBm 11 open
Every action needs an access level (read, mutate or provision) that the link must satisfy under the device’s authorization policy. Arguments are NAME=VALUE pairs; use
NAME=- to read a value from stdin so it stays out of the shell history. Secret arguments, like the one of identity
provisioning, are always read from stdin or a hidden prompt: rohi action identity provision secret=-.
Configuration
rohi config lists the sections of the device, shows the effective configuration of a section (the firmware
defaults with your explicit overrides applied) and changes overrides with patches that are applied atomically per
section. Secrets are write-only. It is covered on Configuration; the rules are in
Service pipeline.
What the services are
| Service | What it reports | Typical issue codes |
|---|---|---|
wireless | Wi-Fi state, IPv4 address, signal and reconnects, radio heap; the BLE peripheral shows up in the health and the issues only | authentication_failed, network_not_found, dhcp_failed, driver_error |
connectivity | telemetry queue and counters | connection_timeout, unauthorized, no_identity, no_utc_time, no_location |
time | wall-clock time, source, age, failures | network_unavailable, timeout, implausible |
sensors | <sensor>.<measurement> values in canonical units | bmx280_error, sds011_degraded, … |
identity | provisioned or not, public key | not_provisioned |
location | where the device is and where that comes from (Location) | not_set |
meshtastic | the local Meshtastic radio on a UART (opt-in meshtastic-uart build): identity, counters, send, inbox, reconnect (guide) | uart_unavailable, radio_not_configured, radio_unresponsive, protocol_error, radio_reconnecting |
A firmware may offer more or fewer; rohi status shows what the connected device really has. Adding a service needs
no change to the tool: Add a service.
Actions
Actions are the operations a device offers: scan for Wi-Fi networks, reconnect, provision an identity. The device lists them with typed arguments and results; rohi generates its help and tables from that description. How a firmware declares an action is in Action.
rohi action # all actions: service, name, access
rohi action wireless # the actions of one service with their arguments
rohi action wireless wifi_scan --help # arguments and results (generated from the device)
rohi action wireless wifi_scan # results as a table, one row per record (all pages of one scan)
rohi action wireless wifi_reconnect # queues a reconnection; success means "accepted"
rohi action wireless wifi_disconnect # Wi-Fi stays idle until wifi_reconnect or a config change
rohi action radio tune channel=11 # arguments are NAME=VALUE, all required
rohi -o json action wireless wifi_scan
-o json with --help prints the schema. Every action declares the access it needs: read, mutate or
provision; the link must satisfy that under the authorization policy of the device. Access is independent of whether
the arguments are secrets. A refusal with a stable reason is reported as the device rejected the action: <reason> (for example
already_provisioned).
An action returns one of five result formats: nothing (Done), one record (name: value
lines), a collection (a table; No results when it is empty), a feed page or a stream. -o json says which one in format.
When an action returns a stream, its file bytes are written to stdout in the order reported by the device; file names and sizes are written to stderr. Stream output is raw bytes, not JSON.
Without the word action
Every action also runs as rohi SERVICE ACTION [ARG]..., with positional arguments. The positions are those of the
arguments in the schema the device reports (see rohi SERVICE ACTION --help), never their numeric ids:
rohi system # the actions of a service, from the device
rohi system reboot --help # arguments, kinds, enum variants and the access level
rohi system reboot # reboots the device shortly after answering
rohi system factory_reset # formats the configuration storage; does not reboot
rohi wireless wifi_scan
rohi -o json system factory_reset # global options may come before or after the service
For an action whose schema lists endpoint (string), enabled (bool) and timeout_ms (u64) in that order, the
words are given in that order, whatever the numeric ids of the fields are:
rohi SERVICE ACTION https://example.org true 5000. Put -- before a value that starts with -
(rohi SERVICE ACTION -- --odd); negative numbers need no --.
All arguments are required: a missing or extra word is refused before the device is contacted for the call. Values are
checked against their kind, an enum value must be one of the listed variants. A secret argument is read with -
(hidden prompt or stdin), never from the command line: rohi identity provision -. A service whose name is also a
command of rohi (status, config, …) is reached with rohi action SERVICE .... The listing and the help need the
device, because they come from it.
Identity
The identity is an ordinary service: no dedicated command.
rohi status identity # state, public key; never the secret
rohi action identity provision secret=- # 32-byte secret as hex, from stdin or a hidden prompt (or: rohi identity provision -)
rohi action identity erase
The secret is derived on a trusted machine (rohi::derive_identity, see Device identity) and
only the derived secret is sent. rohi system factory_reset erases it with the rest of the configuration storage. A malformed secret is reported
without echoing it.
Access and the TCP key
A device decides what a client may do. Over TCP the access mode says what a client without the device’s 32-byte pre-shared key (PSK) may do; a client that completes the handshake with the key may do everything, and everything it sends and receives is authenticated and encrypted. BLE is open in the current build: no pairing, no link encryption, and every client in radio range may do everything, including changing the configuration, provisioning the identity, resetting the device and asking for the TCP key.
There is one public service, control, and one config section, control, for both endpoints.
tcp_access_mode | Without the key | With the key |
|---|---|---|
open | read, change and provision, in plaintext | everything |
protected (default) | read only, in plaintext | everything |
private | nothing: a plaintext client is not served | everything |
| Transport | What it means |
|---|---|
| TCP | the mode above, set with tcp_access_mode; the handshake with the PSK unlocks everything, every record is authenticated and encrypted |
| BLE | open: no pairing, no encryption, no setting to change it; the control status raises the unsecured issue while it runs |
The mode is about who may do what. Whether a secret may travel is a separate rule: the action that generates the key
(tcp_generate_psk) runs only on an authenticated and encrypted connection of the current key, in every mode, so open
never makes the key travel in plaintext TCP. (Open BLE is the accepted exception of this phase.)
Open BLE is a deliberate, temporary, insecure state. Protecting TCP does not secure a device whose BLE is open. See Access control for the protocol, and what it does and does not give: in particular there is no forward secrecy, so whoever learns the key later can decrypt a recorded session.
Get the key from the device
The device generates the key; a client never chooses it.
rohi -D ble://ALTRUIST-URBAN-A12F action run control tcp_generate_psk
# PSK FINGERPRINT
# 0bca27b51a6f36f22bf416601de43452335375770144ba6e69475271216ef5df 0ca29e40355a303b
control tcp_generate_psk is an ordinary action. Every call makes a new key, stores it, ends the TCP connections of the
old one and returns the new key in the result; there is no action that reads the current key, and no way to set a key from a
client.
The generic action output prints the key. rohi has no special handling for this action: the PSK column of the result
is the key itself, in clear text on your terminal, in your scrollback and in whatever captures the output (a pipe, a CI log,
--output json). Run it where nobody can see the screen, do not log it, and save it straight into a file only you can read:
(umask 077; rohi -D ble://ALTRUIST-URBAN-A12F action run control tcp_generate_psk | awk 'NR==2 {print $1}' > tcp.key)
The FINGERPRINT is not a secret: it tells you which key a device holds. Over BLE the key also travels in the clear: run the
action where nobody else is in radio range.
The key file holds 64 hex characters; keep it secret. rohi refuses a key file that other users can read, and the key is
never a command line argument. Setting ROHI_PSK_FILE is the same as passing --psk-file. The status of control does not
show the key, whether one exists, or the mode.
Use a protected or private endpoint
Without a key rohi sends plaintext requests: a protected endpoint answers reads (status, config without changes,
info) and refuses changes. With the key, rohi does the handshake and encrypts every request, which is how you change or
provision a protected endpoint and the only way into a private one:
rohi -D tcp://192.168.1.50:9300 status control # plaintext read, protected endpoint
rohi -D tcp://192.168.1.50:9300 --psk-file tcp.key config wireless wifi_ssid=ROHI-LAB
rohi -D tcp://192.168.1.50:9300 --psk-file old.key action run control tcp_generate_psk # rotate (see below)
With another key the connection is refused: a device that does not know your key cannot complete the handshake and rohi
does not trust it, and a client that failed the handshake is never served in plaintext. If a request is refused:
| Reason | Meaning |
|---|---|
no_psk | no key is provisioned, so nobody can authenticate to the TCP endpoint; get one with rohi action run control tcp_generate_psk (over BLE) |
encryption_required | the request needs the authenticated link; connect with --psk-file |
Rotation. To replace the key, connect with the current key (--psk-file) and run rohi action run control tcp_generate_psk
(save its result as above), or run it over BLE. The device ends the TCP connections that used the old key, and a request of
such a connection that was still waiting for the device is not run at all: reconnect with the new key. A TCP session that is
interrupted by the change is not a failure of the request.
One slow client does not block the endpoint. The device serves one TCP client at a time. A client has 10 seconds in total to send its preamble and finish the handshake and 10 seconds in total for each request record, however slowly it sends the bytes; after that the connection is closed. A client that sends nothing at all after a record is closed after 60 seconds.
Settings and status
rohi config control # tcp_access_mode, tcp_bind_address, tcp_port
rohi status control # ble_sessions, tcp_sessions, tcp_state, requests, errors; health and issues
There is no enabled setting: a service that is part of the firmware always starts, with the defaults and your stored
values on top, and a failure to start shows as failed in tcp_state and as the endpoint_failed issue. The three settings
apply together at the next start (reboot); a saved setting is never partly applied. rohi config tells you when a reboot is
needed (restart_required). A factory reset restores the defaults and removes the key. Only a device with a TCP endpoint (the
std platform) has the control config section.
requests counts the requests the device handled since boot, including those refused by the access mode; errors counts
failures (a broken record, an I/O error, a handshake that did not authenticate), each once. A refused request is not an
error. The health is ok when every endpoint the device has works, degraded when one failed and another works, and error
when none works; the mode, the key and the number of sessions do not change it.
Recovery
If the key is lost: run rohi action run control tcp_generate_psk over BLE (and save the result), or rohi system factory_reset
(it also removes the configuration and the identity). On the std device, --control-psk-file FILE gives the process a key
for one run (it replaces the stored one and is never stored), --control-mode open|protected|private (or --control-open)
sets the access mode for one run (open is plaintext, loopback only).
Device log
The device keeps two logs of what its firmware reports through the standard Rust log facade (Wi-Fi came up, a request
timed out, a storage write failed):
- the latest records in RAM, a few of them, lost on a reset:
rohi logsshows them androhi logs -ffollows them; - the archive, a bounded ring of compressed files in internal flash (a file next to the configuration flash for the
simulated device) that survives a reset:
rohi logs downloadsaves it.
The log is the logging service with its own status, configuration section and three actions
(download, clear, tail). rohi logs reads the latest records in RAM with the read-only tail action, which returns one
bounded page (at most 512 bytes of text) per call, with no stream to open or close; rohi action logging tail session=0 after=0
shows such a page as it is (its metadata and text).
Status. The behaviour below is covered by host tests, including an emulated flash with power-loss injection, and by end-to-end tests of the
altruist-urbanhost process. It has not been run on a device: see the support matrix. The SD card backend is not implemented: internal flash is the only storage, and issue #26 is implemented only in part.
rohi logs # the latest records the device keeps in RAM, oldest first
rohi logs -n 5 # the latest 5 of them
rohi logs -f # follow new records like `tail -f` (Ctrl-C to stop)
rohi logs -n 5 -f # the latest 5, then follow
rohi logs download # save every retained archive file to the current directory
rohi logs download -d ./logs # ... to another directory
rohi logs clear # remove the archive of the active storage (asks first)
rohi -o json logs -n 5
-n N returns at most what the device keeps in RAM: 8 records on the ESP32-C3, 7 on the ESP32-C6 and 32 on the host, however
large N is. That is a window onto what just happened, not a way to read history: for anything older, rohi logs download.
The device answers with at most 512 bytes of whole lines per request, so rohi logs asks for the next page with the cursor of the
previous one until nothing newer is left. A line is never split across pages; a line whose escaped text is longer than a page is
shortened by the device (a * follows its level) so that every page makes progress.
A record is one line:
42 12345 2026-11-03T05:24:43.221Z WARN wifi: connected to home
the sequence number, milliseconds since boot, the wall-clock time in UTC (- while the device has no synchronized
time), the level (* after it when the message was cut), the target and the message.
The sequence number of rohi logs is the tail sequence: it starts at 1 on every boot, counts every record the device
accepted (also one that the archive later drops because its queue was full) and is not the number you find in a
downloaded file. A client keeps a session with the sequence: the device gives every start its own session, a random number
that does not come from the boot_count of rohi status system (that counter lives in the configuration storage, which can
fail to be read or written, and a repeated value would make a client take the records of a new boot for those of the old one).
A cursor of an earlier boot is therefore never mistaken for one of this boot, even when the boot counter could not be kept.
rohi logs -f asks the device for what is new once a second and prints each record once, in order. A client that is caught up
gets an empty page, and polling the tail writes no log records of its own, not even at the debug level of the persistent
log (the control plane and the service registry report a page action at trace, which the persistent log never keeps), so following never feeds the tail it
reads. It says so on stderr when something happened it cannot hide:
The device restarted: the log it keeps in RAM starts over: the session changed (the device reportsreset); the records of the new boot are shown from the start;N log record(s) were overwritten on the device before they could be read: more records came between two requests than the device keeps; the device counts them in thegapof the page and the sequence numbers jump.
-o json prints { "schema_version", "session", "records": [..] }; with -f it prints one such document per line.
The tail needs no flash: it answers while the archive is being written, is faulted, or is held by a download.
What is kept
rohi config logging shows and changes what the device persists. A change applies at once, without a reboot.
| Field | Meaning |
|---|---|
level | off, error, warn, info or debug. The default is warn in a release build and info in a development build. Only the persistent log is affected, not the serial console |
storage | an enum: internal (0, flash; a file on the host) or sd (1). sd is selectable but this firmware has no card: the service then reports storage_unavailable and does not fall back to flash |
compression | an enum for new segments only; old segments keep their form. A default firmware has one value, none (0, plain text). lz4 (1) exists only in a firmware built with the lz4 feature; a firmware without it does not list it and rejects it |
retention_bytes, segment_bytes | the budget of the history and the size at which a file is closed; the oldest files are dropped when the budget is used. The chip sets the defaults, and a value you set stays in force: on the ESP32-C3 the rohi-log partition is 128 KiB, so the default is 128 KiB in 8 KiB segments (the partition is not the journal: two 4 KiB sectors hold the format header, so 15 full segments, 120 KiB, are retained, of which about 98 to 116 KiB are text lines); on the ESP32-C6 and the host it is 1 MiB in 64 KiB segments, below the limit of 24 segments. A value you set is kept as it is, and one that is only valid next to the former 8 KiB segment (a budget below 128 KiB) makes the section invalid until you also set segment_bytes or remove it |
flush_interval | the longest a record waits in RAM before it is written |
Records are written in small batches and files are compressed one batch at a time, so a power loss costs at most the records not yet written, never the history. When the queue between the firmware and the log task is full, new records are dropped and counted, and the application is never slowed down.
rohi status logging shows the state: capacity_bytes, used_bytes and free_bytes of the active storage, the number of
retained segments and records, dropped_records, the oldest and newest sequence and the history. free_bytes = 0 is normal
for a full ring: the next write replaces the oldest file. At most 24 segments are retained, so with small segment_bytes the
count, not retention_bytes, limits capacity_bytes.
When the device starts, every sealed segment is checked against the checksum stored with it. A segment whose content does
not match is dropped whole (the rest of the history stays) and the service reports storage_corrupt. The records in RAM are not
affected.
Download
rohi logs download saves the retained files exactly as the device keeps them, oldest first: rohi1.log,
rohi2.log, … They are plain UTF-8 text. A firmware built with the lz4 feature writes rohi1.log.lz4, … instead,
standard LZ4 files:
less rohi*.log
lz4 -dc rohi*.log.lz4 | less # firmware built with `lz4`
A log written by an older format (before LZ4 became optional) is not read: the first start of a new firmware
reinitializes the rohi-log partition, and only that partition (configuration, application and NVS are never touched).
The old archive is discarded.
The device closes the file being written, starts a new one for the records that come next, and holds the retained files
until the download ends, so records logged meanwhile are not part of it. rohi does not overwrite existing files unless you pass
--force, and removes a file it could not finish.
Clear
rohi logs clear removes the archive of the active storage after you confirm (--yes skips the question, a script
must pass it). It does not touch the configuration, the identity or another storage. It destroys all retained log history
and physically erases the whole log region of the flash, one sector at a time, not only the headers of the files, so it takes
longer than the other actions (the time on a device is not measured yet). The history number grows, the log starts again
empty and keeps working; a reset in the middle of a clear leaves either the old history or an empty one, never a part of it.
A clear is refused as Busy while a download holds files, before anything is erased: close the download (rohi does it when it
ends) or wait until the device expires it (60 s without a read), then clear again. A download that was just started and a clear
that is called at the same time are ordered: whichever the device takes first wins, and the other one never sees a half-cleared
archive. It does not touch the records the device keeps in RAM:
rohi logs (and a running rohi logs -f) show them as before, and the session does not change.
First start and upgrades
The log region carries a format header in its last two sectors. A region without a valid one (a new device, a partition table that
moved the region over other data, an interrupted format) is erased once, sector by sector, and then the header is written; a region with a valid
header is never erased by a start, whatever else happens to be damaged in it. Only the rohi-log partition is formatted. The region
moved (on the ESP32-C3 it is now 128 KiB at 0x20000, right after the configuration region; on the ESP32-C6 it is the last 1 MiB): the old history is not migrated and the first start of the new firmware formats the new region
(see the firmware README). Records logged while it runs wait in a bounded queue.
Secrets
The log can be downloaded by anyone who can reach the device, so firmware must never log secrets. The Altruist Urban
firmware logs no Wi-Fi passwords, keys or provisioning secrets. Third-party drivers can log at debug, which is the highest level the persistent log can be set to: keep it at
warn or info unless you are diagnosing a problem, and review a download before you share it.
Automation
Every rohi command can run unattended: results go to stdout, prompts and diagnostics to stderr, -o json selects a versioned document, exit codes are stable and confirmations can be skipped. Combine these with the device selection of Discovery & connection.
Command results go to stdout. Prompts, progress, warnings and diagnostics go to stderr, so redirects and pipes stay
clean. -o json (--output json) prints a JSON document with a stable, versioned schema instead of text:
rohi -D A12F -o json status network | jq -r '.values.ip'
rohi -D A12F -o json status sensors | jq '.values["scd4x.co2"]'
rohi -D A12F -o json status | jq -r '.services[] | select(.health != "ok") | .service'
rohi -D A12F -o json config wireless | jq '.overridden' # {"section", "values", "overridden": [field names]}
Every JSON document has "schema_version": 1. The schemas are owned by the command line, not by the library types.
A closed pipe (rohi action | head -1) ends the command quietly.
| Exit code | Meaning |
|---|---|
0 | success |
1 | failure of the device, the link or the command (including a declined prompt) |
2 | command line usage error |
130 | interrupted with Ctrl-C |
Failures print an error: line and, where there is something to try, hint: lines:
$ rohi status
error: no ROHI device found
hint: make sure Bluetooth is enabled and the device is advertising
hint: try `rohi scan`
Destructive commands (config reset, config apply) ask for confirmation on a terminal; the actions of the device (system factory_reset) do not. Without a
terminal they fail with confirmation required in non-interactive mode unless --yes is passed. Secrets are never
accepted as command line arguments: a field or argument that is a secret is read with NAME=- from stdin, or from a
hidden prompt on a terminal.
Mobile application
Not implemented. This page describes the intended experience of the shared mobile application. No mobile application exists in this repository or is published. Everything that works today is the desktop application.
The intended application is a generic client of the control protocol: like rohi, it knows no
firmware by name and builds its screens from the schemas the device sends.
Discovery & connection
Connect directly over BLE, without Wi-Fi or a cloud account. The control transport the SDK implements today is BLE, which is what makes this possible. Pairing and encryption of the link are not implemented yet and would need to exist before the application is suitable for general use.
Configuration
Present the settings that the firmware defines: names, types, units, allowed values and secrets are described by the
device, so a new setting appears without an application update. The semantics are those of
rohi configuration: effective values, overrides and reset.
Status & diagnostics
Show the health of the device and of each service, its metrics and its active issues, as
rohi status does.
Actions
List the operations the firmware offers and invoke them with typed arguments, using the schemas the firmware provides (see Actions).
Firmware compatibility
The same application is meant to operate verified firmware and custom compatible firmware. Compatibility is defined by the control protocol, not by an approval list: see Compatibility.
Quick start
This section takes a developer from a minimal firmware to a device that generic ROHI clients can operate.
-
Set up the toolchain: Installation, then Workspace layout.
-
Run a sensor example on a board: First device. It uses the hardware independent drivers and the board module, with no networking, and shows how to work on it with an AI assistant.
-
Build and test the SDK: Build and test.
-
Flash the reference firmware and connect with
rohi:cargo run --release -p altruist-urban --features esp32c6 --target riscv32imac-unknown-none-elf rohi status(ESP32-C3:
--features esp32c3 --target riscv32imc-unknown-none-elf.) -
Learn the three concepts a firmware exposes: Config, Status and Action.
-
Add your own capability, also with an AI assistant: Create & customize. It becomes visible in generic clients with no client change.
Check that the board you target is listed in the support matrix and add your findings to it when you validate hardware: Validation.
The reference firmware is firmwares/altruist-urban;
complete one-sensor programs are in examples/.
Installation
For blazing-fast dependency installation, use the Nix package manager. If you already have Nix, skip to the Nix Way section.
Clone the SDK repository first.
git clone https://github.com/akagi-dev/rohi-sdk && cd rohi-sdk
Prerequisites
Rust & Cargo
Use the rustup.rs script for a quick Rust compiler installation.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
The required toolchain, components and both RISC-V targets (riscv32imc-unknown-none-elf for the ESP32-C3 and
riscv32imac-unknown-none-elf for the ESP32-C6) are listed in rust-toolchain.toml.
Run rustup inside the repository to install them (add rustup to your PATH if you’ve just installed it).
rustup toolchain install
Espflash
This tool is required for flashing ESP hardware. The SDK prepares the firmware and launches the flashing process, but
the espflash binary must be available in your PATH. For setup details, see the official
installation instructions.
Nix Way
The repository is a Nix flake. The development shell provides the pinned Rust toolchain, espflash, mdbook and the
linker, nothing else has to be installed. Intel Mac (x86_64-darwin) uses
nixpkgs-26.05-darwin: Nixpkgs 26.11 dropped that
platform, and nix-systems/default no longer lists it. dbus is Linux-only
(BLE on macOS uses Core Bluetooth). The e2e shell (edge) is not built for Intel Mac.
nix develop
Intel Mac (x86_64-darwin): macOS Bash is 3.2 and cannot enter nix develop directly. From the repository root this is the same shell:
nix run .
If the shell says command not found: nix after a multi-user install, Nix is on disk but not on PATH (a non-login terminal, or the installer snippet missing from zshrc). This is the default daemon profile, not a machine-specific path:
. /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
A single-user install uses ~/.nix-profile/etc/profile.d/nix.sh instead. Put the matching line in ~/.zshrc so new terminals see nix.
If the clone path contains non-ASCII characters, keep build artifacts off that path: CARGO_TARGET_DIR=/tmp/rohi-target cargo test. A path like ~/src/rohi-sdk does not need that.
Verify the installation
Run the First device example, then build and test the SDK as described in Build and test: cargo test on the host, and
cargo check-esp32c3 / cargo check-esp32c6 for the two chips. Documentation tooling (mdbook, link check) is covered
in Documentation style and policy; the Nix shell provides it.
Workspace layout
rohi-sdk/
├── crates/
│ ├── rohi-sensors measurements, sensor state, store, `sensors` service
│ ├── rohi-hal, rohi-hal-esp sensor drivers and runner / ESP board backend
│ ├── rohi-config, -derive, -esp configuration store / derive macro / ESP flash backend
│ ├── rohi-net, rohi-net-esp Wi-Fi control plane, IP data plane, BLE transport / ESP backend
│ ├── rohi-time, rohi-time-ntp monotonic clock, synchronized wall-clock time and its NTP source
│ ├── rohi-identity device identity: Ed25519 section and signer
│ ├── rohi-control-proto, -control, -ble control protocol: schema / dispatcher / BLE binding
│ ├── rohi-control-tcp control protocol over TCP: length-prefixed records
│ ├── rohi-net-std host DNS, TCP, UDP and the BlueZ BLE peripheral
│ └── rohi-sim simulated world for `std`: sensors, Wi-Fi, flash, scenarios
├── firmwares/altruist-urban product firmware: portable application + ESP and `std` platforms
├── examples one hardware example per sensor, config self-test
├── tools/rohi desktop client library and CLI
└── docs this book (mdBook)
The crate responsibilities and the allowed dependency directions are in Crate map.
Default members and targets
cargo test and cargo clippy at the repository root cover the portable crates, desktop tools and the portable part of altruist-urban (default-members). The std platform and its end-to-end tests need features: cargo test -p altruist-urban --features std,std-tcp,sensor-simulator. ESP firmware and examples are built per chip with the aliases from .cargo/config.toml; the repository
has no default embedded target. The chip is always selected explicitly by the esp32c3 or esp32c6 feature, never
globally. See Targets and features.
Toolchain
rust-toolchain.toml pins the toolchain, components and both RISC-V targets. The Nix flake provides the same toolchain
plus espflash, mdbook, protoc and the other tools, see Installation.
First device: Air Quality Terminal
The fastest way to learn ROHI is to run a real example on a board and then change it. This page runs one sensor
example, explains it, and shows how to work on it with an AI assistant. The commands assume the toolchain from
Installation (nix develop if you use Nix); Build and test comes next and
covers the full set of checks.
1. Pick an example
The Altruist board has one example per supported sensor in
examples/src/bin:
| Example | Sensor |
|---|---|
example-bmx280 | BMP280 / BME280 pressure, temperature, humidity |
example-scd4x | SCD40 / SCD41 CO₂, temperature, humidity |
example-sds011 | SDS011 particulate matter (PM2.5 / PM10) |
example-noise | I²S microphone noise level |
example-all-sensors | All of the above, concurrently |
example-config | configuration persistence self-test |
Check in the support matrix that your board carries the sensor: the Altruist Urban has an SDS011, a BME280 and a microphone, and no SCD4x. This page uses the SDS011 example. One cycle takes about two minutes: the sensor wakes up, warms up, takes several samples, and the aggregated PM2.5 / PM10 is printed before the sensor goes back to sleep.
2. Flash and run it
Connect the board with USB and run it like any Rust binary:
cargo run --release -p rohi-examples --features esp32c3 --target riscv32imc-unknown-none-elf --bin example-sds011
# ESP32-C6: --features esp32c6 --target riscv32imac-unknown-none-elf
Behind the scenes:
- the Rust compiler creates a RISC-V binary;
espflashdetects the board and flashes it;espflashopens the serial console and shows the log, where you should see the sensor state change and, after a cycle, a PM2.5 / PM10 measurement.
If nothing is printed, the sensor may not be wired as the pin map of your board revision says: see Boards. The ESP32-C6 pin map is not yet verified on hardware.
3. Read the example
///////////////////////////////////////////////////////////////////////////////
#![no_std]
#![no_main]
#![cfg_attr(
not(test),
deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::unreachable,
clippy::todo,
clippy::unimplemented,
reason = "firmware must not panic: handle the error, see AGENTS.md"
)
)]
//! SDS011 example: prints PM2.5 and PM10 once per duty cycle (about 2 minutes).
use altruist_urban::esp::sensors::sds011_task;
use esp_backtrace as _;
use rohi_examples::{print_events_task, run};
esp_bootloader_esp_idf::esp_app_desc!();
#[esp_hal::main]
fn main() -> ! {
run(|spawner, board| {
altruist_urban::tasks::spawn(spawner, "print_events_task", print_events_task());
altruist_urban::tasks::spawn(spawner, "sds011_task", sds011_task(board.sds011_uart));
})
}
- no_std. The file starts with
no_*declarations, typical for bare-metal software without an operating system or standard library. - Main task.
mainis a plain#[esp_hal::main]function.run()configures logging, theesp-rtosruntime that provides the time base of the Embassy Framework (with a small heap for its task stacks) and the board (I²C, UART and I²S pins are defined incrates/hal-esp/src/board/altruist_urban/), then starts the Embassy executor, which spawns the two tasks below. See the Embassy Docs. - Sensor task and events.
sds011_taskruns the SDS011 driver in aRunnerthat handles probing, polling and recovery. Drivers know nothing about networks or serialization: they publish typedSensorEvents (measurements, state changes, errors) into a bounded queue; a successful measurement alone marks the sensorReady.print_events_taskprints them. The production firmware has a single task that applies the events to aMeasurementStore(rohi-sensors) instead.
Each await puts the CPU to sleep until a waiting event occurs: a timer interval, or a measurement from a peripheral.
Instead of a busy loop the CPU enters a low-power mode, and other tasks can use the time.
4. Work on it with an AI assistant
The examples are small enough for an AI coding assistant to understand in one pass, which makes them the best starting point for a custom firmware. Open the repository in your assistant and try prompts like these, one at a time:
Understand it
Read examples/src/bin/sds011.rs and the sds011 driver in crates/hal/src/sensors/sds011.
Explain how a measurement gets from the UART to the print_events_task, and which
parts are hardware independent. Do not change any file.
Change it
In examples/src/bin/sds011.rs print the PM2.5 value together with a plain-language
air quality label (good / moderate / unhealthy). Keep the driver untouched.
Then run `cargo check -p rohi-examples --no-default-features --features esp32c6
--target riscv32imac-unknown-none-elf` and show me the result.
Combine examples
Using examples/src/bin/bmx280.rs and sds011.rs as a model, create a new example
that reads the BME280 and the SDS011 concurrently and prints one line per
measurement. Follow the structure of examples/src/bin/all-sensors.rs.
Check the claim
Look at docs/support/matrix.md (or device-matrix.toml). Is the sensor I am
using supported on the Altruist Urban ESP32-C6, and what is verified on hardware?
Answer only from the matrix and tell me what is missing.
Review what the assistant produces and run it on your board yourself: an assistant can make code compile, but only you can verify that it works on the hardware. The full workflow for changing a firmware with an assistant, with more prompts, is in Customize firmware with AI.
5. Talk to the device
The production firmware (altruist-urban, not the examples) advertises over Bluetooth LE, and the
rohi desktop application shows its status, sensors and Wi-Fi.
Next
Build and test runs the host tests and the ESP checks, and explains what each one proves.
Build and test
All commands run from the repository root (inside nix develop if you use Nix). The authoritative description of
targets, chip features and why they are never combined is Targets and features.
On the host
cargo test # portable crates, framing, dispatcher, rohi client end to end
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
No board is needed. What the host tests cover and what they cannot is in Host testing.
To run the Altruist Urban application itself on the host, use
cargo run -p altruist-urban --bin altruist-urban --features std,std-tcp,sensor-simulator, see
Run Altruist Urban on std. Its end-to-end tests need the features:
cargo test -p altruist-urban --features std,std-tcp,sensor-simulator.
For the ESP chips
cargo check-esp32c3 # ESP32-C3 (riscv32imc-unknown-none-elf)
cargo check-esp32c6 # ESP32-C6 (riscv32imac-unknown-none-elf)
cargo build-esp32c3 # release build
cargo build-esp32c6
Altruist Insight: headless ESP32-C6
The independent altruist-insight package reads the onboard SCD41 and serves ROHI Control over BLE. It does not
start Wi-Fi, an IP stack, TCP/HTTP services, NTP or telemetry uploads. Shared networking crates in its dependency
graph provide the BLE abstraction, not a running Wi-Fi/IP data plane. No network identity provisioning is needed
for sensing or BLE diagnostics. BME680, MicroSD, the display, LEDs and buttons are not initialized.
Run from the repository root:
cargo test -p altruist-insight
cargo check-insight
cargo build-insight
cargo clippy -p altruist-insight --features esp32c6 --target riscv32imac-unknown-none-elf -- -D warnings
cargo flash-insight
These are also the local ESP32-C6 validation commands; the existing Urban aliases still target Urban.
flash-insight selects the Insight binary and its own partition table, overriding the shared C6 target runner.
Do not flash Insight using a bare cargo run --target …: the default C6 runner selects Urban’s partition table.
Board and flash layout
The firmware uses the Insight HAL, not Urban GPIO assignments. The pinned Insight schematic identifies an ESP32-C6-WROOM-1-N8 module and maps SDA to GPIO19 and SCL to GPIO18; the HAL owns this mapping. The pinned Insight specification also specifies 8 MB flash for this module. Confirm the module marking and detected flash capacity on the actual board before flashing.
Insight’s partitions.csv reserves a 16 KiB rohi-cfg region at 0x10000 for the shared A/B configuration
store and places the factory application at 0x20000, ending at 0x800000. There is no Urban rohi-log partition:
diagnostic storage is RAM-only. Do not use this layout on a smaller-flash variant. Flashing over another firmware
can replace its application and partition layout; back up anything needed first.
Discover and connect
Build/install the rohi client from the same revision, enable Bluetooth on the computer and power the board:
rohi scan
rohi -D ble://ALTRUIST-INSIGHT-XXXX status
rohi -D ble://ALTRUIST-INSIGHT-XXXX status sensors
rohi -D ble://ALTRUIST-INSIGHT-XXXX status scd41
rohi -D ble://ALTRUIST-INSIGHT-XXXX config
rohi -D ble://ALTRUIST-INSIGHT-XXXX action
rohi -D ble://ALTRUIST-INSIGHT-XXXX logs
Replace XXXX with the MAC-derived suffix shown by the scan. One central can connect at a time; disconnect other
clients when troubleshooting. The transport uses the existing ROHI GATT service and client framing, not a text
terminal over a generic Bluetooth serial service.
| Available service or operation | Use |
|---|---|
| Device summary | Firmware/platform identity, uptime and service health |
sensors | Latest SCD41 CO₂ (ppm), temperature (°C) and relative humidity (%), health and fault reporting |
scd41 | Sensor model, lifecycle state, availability, error count, last error and last-success uptime |
logging | RAM diagnostic tail, download and clear actions; records do not survive reboot |
logging configuration | Existing logging settings, persisted in rohi-cfg; changes apply without a network identity |
system | System information and reset/crash diagnostics; rohi … system reboot and rohi … system factory_reset |
Use the discovered section/action help before changing settings. Internal logging means RAM on this firmware; selecting SD does not enable the board’s MicroSD hardware. The log has monotonic timestamps, not synchronized UTC. Factory reset formats only configuration, not application flash; it does not provision an identity.
Sensor startup and transactions use the shared SCD4x driver and bounded retry/timeout behavior. Readings are absent until available; faults are reported rather than stopping BLE or the whole runtime. Configuration storage failures also leave basic sensing and BLE diagnostics available.
BLE security and deployment limits
This endpoint is open. The current ESP BLE backend uses TrouBLE without its security feature; it implements no pairing, bonding, link encryption or authentication. ROHI BLE framing adds no cryptography. The firmware does not add a new security protocol and does not claim that a discovered device or connected central is authenticated.
Anyone in radio range can connect, read diagnostics, change exposed configuration, clear logs, reboot or factory-reset the device. A provisioned network identity would not secure this link. This behavior permits diagnostics before provisioning, but is suitable only for a trusted, supervised MVP/bench environment with no sensitive data. It is not suitable for unattended or adversarial deployment. Deployment owners must accept this limitation explicitly; real-world suitability and provisioning behavior remain unverified.
The security follow-up belongs in the shared BLE transport: supported pairing/bonding and authenticated encryption, accurate link-security reporting to Control, an access/provisioning policy and on-device security tests. Do not treat an advertised name, a MAC address or proximity as authentication.
Hardware verification still required
No physical Insight verification is claimed by this change. Before deployment, record the board revision and firmware commit, then check:
- USB serial boot/reset diagnostics and the detected flash capacity.
- Advertising, connection, MTU/framing, disconnect and reconnect using
rohi, before identity provisioning. - SCD41 discovery, periodic changes in readings and sensor state through Control.
- Sensor absence/read errors/timeouts without loss of BLE diagnostics, and recovery after the sensor returns.
- Configuration persistence, RAM log tail/download/clear, system information, reboot and factory reset.
- No Wi-Fi association or IP services; verify the open BLE access behavior, including unpaired access to mutations.
Record results in the support matrix only with hardware evidence. Compilation and host tests do not satisfy the on-device acceptance criteria.
Flash and run
Connect the board via USB:
cargo run --release -p altruist-urban --features esp32c3 --target riscv32imc-unknown-none-elf
# ESP32-C6
cargo run --release -p altruist-urban --features esp32c6 --target riscv32imac-unknown-none-elf
The runner flashes the chip’s partition table, which reserves the configuration region
(configuration store). Examples are built the same
way with -p rohi-examples --features esp32c3 --target riscv32imc-unknown-none-elf --bin example-<name>.
Documentation
mdbook build docs # the book
mdbook test docs # plain Rust snippets of the book
cargo doc --no-deps # API reference of the host crates
See Documentation style and policy for the checks that CI runs.
Next
Create & customize shows how to add your own capabilities, also with an AI assistant; Hardware testing lists what is validated on devices.
Core concepts: Config, Status, Action
A ROHI firmware offers three things to the outside world. Everything a generic client can show or do with your device is one of them.
| Concept | Responsibility | Typical user question |
|---|---|---|
| Config | typed settings, defaults, validation and persistence | what is the device set up to do? |
| Status | runtime health, metrics and diagnostic issues | what is it doing now? |
| Action | discoverable operations with typed arguments and results | what can I ask it to do? |
They are separate on purpose: configuration is desired, persistent state, status is observed, read-only state and an action is an explicit operation. An action is never smuggled into status, and a setting never doubles as a status value.
Composition in a firmware
Each feature crate (Wi-Fi, time, telemetry, sensors, identity, location, your own) describes its own settings, state and operations. The firmware lists them once, and everything else is generated or generic: the control protocol serves them over BLE to any client.
The reference composition is in firmwares/altruist-urban
(config.rs, control.rs).
Schema-driven discovery
Nothing in the client is written for a particular module. The device publishes, on request:
- the sections it has and, per section, a schema of its fields (name, type, unit, allowed values, writable, secret, optional);
- the services it has, a schema of their status fields and the names of their issue codes;
- the actions it has with their arguments and results.
A client fetches a schema when it needs it and renders and validates values by it. Ids are stable and only ever added.
Independent identities
Configuration does not depend on service identity: a section and a service are registered separately. A service can
exist without a section (a read-only sensor service), a section can exist without a service (a stored setting a runtime
reads), and one service can use several sections. By convention they share a name when they belong together
(location, connectivity). Renaming a persisted config type orphans its stored data unless its id is pinned: see
Add a ConfigSection.
Where the details are
This book teaches the concepts and the workflow. The contracts (traits, limits, ownership, cancellation) are in the crate
rustdoc, see SDK crates, starting with the rohi-service rustdoc and
the rohi-config rustdoc. How the concepts reach a client is the
control protocol.
Config
Config is what a user can set up: typed settings with defaults, validation and persistence. A firmware defines a section as a Rust struct; clients discover and edit it without knowing it.
- The struct is the effective configuration the runtime uses; its default is the firmware baseline.
- Only what the user overrides is stored. A setting the user never touched keeps following the firmware default, also after an update changes it.
- Field ids are stable and only appended: they are the stored layout, a persistent ABI.
- The whole effective result of every change is validated, so “unconfigured” must be a valid state.
- The store is transactional and power-fail-safe: a change is stored completely or not at all.
Once the firmware lists a section, it appears in every generic client; for a section named uplink, rohi shows:
rohi config uplink # effective values
rohi config uplink interval_s=120 # set an override
rohi config uplink interval_s=null # back to the firmware default
The user’s view of these operations is Configuration.
Go deeper
| Topic | Page |
|---|---|
| Step by step | Add a ConfigSection |
| The store, transactions, recovery, flash layout | rohi-config rustdoc |
| The section and field model, validation | rohi-service rustdoc |
Status
Status is what the device is doing now: the health, a few metrics and the active issues. It is read-only and describes live state, not stored data.
- Health is the one common indicator:
unknown,ok,degradedorerror. A connecting Wi-Fi isunknown, a telemetry service that cannot reach its backend isdegraded, and a disabled optional service isunknown, which is not an error. What more a service has to tell (a link state, a sensor state) is a field of its own. - Issues are problems that exist now, with a stable numeric code and a severity. There is no message text and no history.
- Values are typed fields with stable ids and units; a value that does not exist now is simply absent.
- The SDK adds a status revision, which changes with the health or the active issues; the device health is decided by the firmware.
Once a service is registered in the firmware, rohi status lists it and rohi status location shows its values and
issues. How users read this is Status & diagnostics.
Go deeper
| Topic | Page |
|---|---|
| Step by step | Add a service |
| Contracts, limits, device health rules | rohi-service rustdoc |
| A complete small example | rohi-location rustdoc |
Action
An action is an operation a user can ask the device to perform: scan for networks, reconnect, provision an identity. Actions are declared by a service, discoverable, and have typed arguments and results.
- Arguments are typed and all required; the SDK checks them against the declaration before the service runs.
- A result has one of five formats, fixed by the action: no data, one record, a collection of records, a cursor feed or a binary stream. A scan returns a collection with one record per network, a reconnect no data.
- An action declares the access it needs: read, mutate or provision. The link’s authorization policy decides whether a link has it; the service never checks. Secret arguments are a separate property: they are never logged, returned or kept, and they do not imply an access level.
- A refusal that a client may react to carries a stable code, for example
already_provisioned.
With the service registered, every client lists the action and builds its arguments and output from the schema:
rohi action # all actions
rohi action wireless wifi_scan --help # arguments and results, generated from the device
rohi action wireless wifi_scan
The user’s view is Actions.
Go deeper
| Topic | Page |
|---|---|
| The five result formats | Action result formats |
| Step by step | Add a control operation or an action |
| Declarations, privileges, errors | rohi-service rustdoc |
Action result formats
Every action returns its result in one of five formats. The service picks the format when it declares the action; the control protocol, discovery and every client then apply the same rules, whatever the service is. The format describes what the result is and what is guaranteed about it, not how many messages carried it: a collection is a collection whether it had zero, three or sixteen records.
| Format | What the action returns | Lifecycle | Example |
|---|---|---|---|
| Empty | nothing: the operation succeeded and has no data, by contract | one reply | wireless.wifi_reconnect, system.reboot |
| Inline | one record of named, typed fields | one reply | control.tcp_generate_psk (psk, fingerprint) |
| Records | a finite collection of records with one schema | snapshot, read page by page | wireless.wifi_scan (ssid, rssi, channel, security) |
| Feed | one bounded page of a source that keeps changing, addressed by a cursor | stateless polling | logging.tail |
| Stream | a binary snapshot of one or more named files | open, read chunks, close | logging.download, connectivity.get_payload |
An action has one format for good: a result never turns from Inline into Records or Stream because it got larger.
rohi action SERVICE ACTION --help -o json shows it as format in the action description, so a client knows what to
expect before it calls.
Choosing a format
- Nothing to report? Empty. An action that found nothing is not Empty: a scan that sees no network returns an empty Records result, because “no networks” is an answer.
- One bounded object (a generated key, the public key of a new identity)? Inline. It is one object, not a collection of one.
- A list whose length is not known in advance but is finite and produced by one operation (networks, catalog entries)?
Records. The control plane pages it; the service writes no paging code and the action takes no
offset. - Recent data of something that goes on while you read it (the log tail)? Feed.
- Binary data that is larger than a message, or that must be saved as files (the log archive, a signed packet)? Stream.
Empty, Inline and an empty collection
These are three different answers and rohi shows them differently:
| Result | Text | -o json |
|---|---|---|
| Empty | Done | {"format": "empty"} |
| Inline | one name: value line per field | {"format": "inline", "record": {...}} |
| Records, none | No results | {"format": "records", "records": []} |
| Records, some | a table, one row per record | {"format": "records", "records": [...]} |
Records: one operation, any number of pages
InvokeAction runs the operation once and returns the first page of the result. A page holds whole records only,
never part of one, and is limited both in records and in bytes, so a longer result continues on further pages:
rohi action wireless wifi_scan # all networks of one scan, the pages followed for you
rohi -o json action wireless wifi_scan
- One scan, not many. Reading the next page does not run the action again; an expensive operation (a Wi-Fi scan) never repeats to produce page two. A scan of 16 networks arrives as 6 + 6 + 4 records.
- Stable. While the result is held, the same page read again returns the same records in the same order.
- Held for you only. The device keeps the rest of a long result (in its compact native form, not as protocol records)
for the connection that ran the action. Another connection that presents the page token, a closed or expired token
or a malformed one gets
not foundand no records; pages need the same access as the action that created them. - Released.
rohicloses the result when it has read it. A client that stops early can close it, or just stop: the device releases it after a period without a read, when the connection ends and when the link is lost. A device holds a few results at once; while one is held, an action that needs another (a secondwifi_scan) answersbusy. - Retry. A lost reply to the first call is not retried by itself, because a new call could run the operation again. A lost reply to a later page is simply asked again.
- A result that fits one page is never held on the device.
Configuration and status are not paged by this mechanism: their responses always fit one message.
Feed: a cursor over a changing source
A feed is not a snapshot. It gains entries while you read and loses old ones when its retention is exceeded, so the page
says where the reader stands: the session of the source (a boot), the cursor (the last entry returned), the range
still held, whether the request started over (reset, because the session changed) and how many entries were lost to
overwriting (gap). An empty page means “caught up”, not “finished”. Nothing is kept for the reader, so any number of
clients can poll, and access is checked on every call. rohi logs --follow is a client of the log tail feed.
Stream: files read in chunks
A stream is a snapshot of files. The client reads each file by offset, in chunks, and closes the stream; the reads are
repeatable. The device holds a stream for the connection that opened it and releases it on close, after a period without
a read and when the connection ends. rohi logs download and the signed-packet export use streams; binary transfers never
use Records or Feed.
Access, secrets and cancellation
- The format changes nothing about access: the action declares what the link must be allowed to do, the policy of the link decides, and a page, a chunk or a close needs the same access as the call that created it. Whether a request arrived over an encrypted or authenticated link is established by the transport, never by anything in the request.
- A secret Inline result (a generated key) travels only on a link that the action requires (
secure_link) and is wiped after the reply is encoded. - A call that is cancelled or fails before its result is owned leaves nothing held for good: the device releases a result nobody owns after its period without a read.
Adding an action
Add a control operation or an action shows where a format is declared; the contract of the five
formats, the limits and the writer API are in the rohi-service rustdoc, the wire form in
the rohi-control-proto rustdoc, and the Rust client (invoke_outcome,
records_pages, records_all) in the rohi library.
Control protocol
Device identity
GetInfo reports the firmware name (no version), the board and the build identifier
<platform>/<version>+<sha8>.<YYYYMMDD>, for example urban-esp32c3/0.8.0+5c582f4a.20261122; rohi info and
rohi status show firmware and build. The firmware generates it in its build.rs: <sha8> is the Git commit
(ROHI_BUILD_SHA overrides it in CI) and the UTC date comes from the build time (SOURCE_DATE_EPOCH makes it
reproducible). The same text is the User-Agent of the telemetry HTTP requests. board stays for compatibility until
the protocol drops it.
Control protocol
The control protocol is the shared contract that lets a generic application operate any firmware. It exists so that a firmware author describes a device once, in Config, Status and Action, and every client can use it without a firmware-specific integration.
Firmware sections · services · actions
│ described by schemas the device publishes
Protocol request/response messages (protobuf), one schema, bounded sizes
│
Transport moves bytes: BLE today (GATT), others possible
│
Application rohi desktop · mobile app (planned) · your client
What it does
- Makes capabilities discoverable. Clients ask what sections, services and actions exist and fetch their schemas. Config becomes readable and editable settings, Status becomes health and metrics, Action becomes callable operations.
- Avoids per-firmware clients. The protocol, the dispatcher and the client know no module by name, so a new firmware module needs no client change.
- Separates concerns. The firmware owns meaning, the protocol owns the wire format and the transport owns delivery. The transport carries opaque bytes, so replacing it does not change the firmware or the clients.
Current state
| Aspect | State |
|---|---|
| Protocol | version 2; still under development: keep client and firmware on the same revision |
| Transport | BLE on devices and, on Linux, on the std Altruist Urban (BlueZ); independently, TCP (tcp://HOST:PORT: a preamble, then either 4-byte-length Protobuf records or the PSK handshake and encrypted records; no BLE frames) for the std Altruist Urban |
| Security | TCP is protected by default (plaintext reads; a handshake with a 32-byte pre-shared key unlocks everything, with authenticated and encrypted records; no forward secrecy); BLE is open (no pairing, no link encryption) in this build, an accepted insecure state; no TLS, see Access control |
| Scope | local control only; telemetry uplink is a separate service |
Access control
Requests have a privilege: Read (observe and discover), Mutate (change configuration, reboot, factory reset,
reconnect) or Provision (initialize protected state: the identity, the TCP pre-shared key). Every action declares its
privilege in its descriptor, and the schema shows it. secret_args marks sensitive arguments; it does not make an action
privileged.
The TCP endpoint has an access mode, the tcp_access_mode field of the control config section (it applies after a
restart). The BLE endpoint has none: it is open. There is one public service, control, for both.
| Request | TCP open | TCP protected | TCP private | BLE |
|---|---|---|---|---|
| Read, no key | allowed | allowed | denied | allowed |
| Mutate, no key | allowed | denied | denied | allowed |
| Provision, no key | allowed | denied | denied | allowed |
| Any request after the handshake with the key | allowed | allowed | allowed | n/a (BLE link: open, not encrypted and not authenticated) |
The default is TCP protected. The mode is authorization, not link confidentiality: secure_link actions (below) are an
additional rule in every mode. A missing key does not change the state of the endpoint (tcp_state stays running); it only
makes the authenticated rows impossible until a key is generated. An unencrypted BLE link is never reported as encrypted or authenticated; the policy
decides from the properties the transport reports, never from a configuration flag, so a restricted BLE mode can return
without changing the transports. A refusal is PermissionDenied with a stable reason (no_psk, encryption_required) and
the service never runs.
Security belongs to the transport. The common control layer (rohi-control) implements no encryption, no signature and no
challenge: it only reads what the transport established, as the encrypted and authenticated flags of the link, and nothing in a
request can change them. An action that carries key material of a transport (control.tcp_generate_psk) is additionally marked
secure_link: on TCP it runs only on the authenticated and encrypted connection of the current key and is refused as
encryption_required otherwise, so open never lets the key travel in plaintext. Open BLE counts as allowed for it in this phase: that is the one place where a secret
reaches an open link, and it is an accepted exception, not a design.
Preamble (TCP). A TCP connection starts with an explicit preamble that says how it goes on; nothing is guessed from other bytes:
| First bytes | Meaning | Served in |
|---|---|---|
"ROHP" | version 1 (5 bytes) | plaintext records follow: a 4-byte little-endian length and one Protobuf message each | open, protected |
"ROHI" | version 1 | client_nonce (the hello below) | the PSK handshake, then encrypted records | every mode |
| anything else, or another version | the connection is closed, one transport error is counted | n/a |
A plaintext connection is never authenticated and never encrypted: the policy of the mode decides what it may do. private
closes a plaintext connection after the first four bytes (an access refusal, not an error). A client that fails the
handshake is not served in plaintext afterwards, and a client cannot declare itself authenticated in a request.
Secure channel (TCP). A client that completes the handshake with a 32-byte pre-shared key (PSK) may do everything in every mode, and every record after it is authenticated and encrypted. Nothing is read or processed before the handshake verified, and there is never a fallback to plaintext:
ClientHello "ROHI" | version 1 | client_nonce[32]
ServerHello "ROHI" | version 1 | server_nonce[32] | server_proof[32]
ClientFinish client_proof[32]
prk = HKDF-Extract(salt = client_nonce || server_nonce, ikm = psk) (SHA-256)
server_proof, client_proof = HKDF-Expand(prk, label || SHA-256(transcript) [|| server_proof])
record = version(1) | length u16 BE | ciphertext | tag(16) XChaCha20-Poly1305, header as AAD,
nonce = prefix(12) || counter u64 BE || direction u32 (directional keys, counters count records)
The two proofs are bound to the whole transcript, so both sides are authenticated and the nonces of one connection are
useless in another. A malformed, replayed, reordered, truncated or tampered record, a counter that is used up and a key that
was replaced all end the connection with nothing written in plaintext. The key is never sent or logged and the derived keys
are wiped on drop. This is implemented by rohi-control-tcp alone (rohi_control_tcp::secure); BLE keeps the link security of
its host stack and gets no framing encryption.
Limits. The PSK design has no forward secrecy: whoever learns the key later can decrypt a recorded session and
impersonate the device or a client. There is no TLS, no certificate and no key agreement beyond the PSK. A network attacker can
still drop or delay traffic. BLE is open in this build: anyone in radio range can change the configuration, provision the identity, reset the device and
run tcp_generate_psk; restricting TCP does not secure a device that has BLE control. Telemetry payload encryption is a
separate, packet-level property and is not affected.
TCP key. The device always generates the key. control.tcp_generate_psk (Provision, secure_link) makes a new random key on
every call, stores it, ends the TCP connections of the old one and returns the new key in its result; no client chooses a key
and no action reads the current one. A factory reset removes it and restores the defaults. Without a key a private TCP
endpoint serves nobody and a protected one only reads; a client that asks for the handshake is refused and never falls back to plaintext. The first key is therefore fetched over BLE (open, so in
the clear) or over the connection of an existing key; a device whose key is lost is recovered with tcp_generate_psk or a factory
reset. The std host can also take the key from a file for one run (--control-psk-file). See Access and the TCP key.
One control worker
BLE and TCP are thin frontends: they frame bytes (BLE fragments, TCP records), own their connections and hand each
request to a slot of a bounded mailbox. One control_task owns the one Controller and runs Config, Status, Actions and
streams for every transport, one request at a time. A connection has one request in flight; a full mailbox is answered
Busy. A long action therefore delays the requests of other connections. Every connection has a session identity that is
unique across transports; closing it releases only its streams and result snapshots.
Where to go next
- Operate a device: Desktop application, Mobile application (planned).
- The authoritative definition is the schema
control.protoand the rustdoc ofrohi-control-proto,rohi-controlandrohi-control-ble, see SDK crates. - Extend the protocol: Add a control operation or an action.
Create & customize
A firmware is a composition of SDK components plus your own. These guides show how to add each kind of capability; every one of them becomes visible to generic clients without changing a client.
| I want to add… | Guide | Visible to clients as |
|---|---|---|
| a sensor | Add a sensor | status fields of the sensors service |
| a setting | Add a ConfigSection | a section in rohi config |
| a runtime part with state | Add a service | a service in rohi status |
| an operation | Add a control operation or an action | an action in rohi action |
| networking | Use IP networking | the wireless service |
| another board | Add or support a board | a new row in the support matrix |
With an AI assistant
Every guide above can be driven by an AI coding assistant. Customize firmware with AI explains the workflow, what to give the assistant and ready-to-use prompts for each kind of change.
The path from code to a client
- Write the portable logic in a feature crate and test it on the host (Host testing).
- Describe it: a config section for its settings, a service for its status and, if it has operations, its actions.
- Register it in the firmware (
firmwares/altruist-urban:config.rsfor sections,control.rsfor services). - Build for the chip and flash it (Quick start).
- Open it with
rohi:rohi status,rohi config,rohi actionshow it. - Record what you verified in the support matrix.
Complete examples
firmwares/altruist-urban: the reference firmware.examples/: one program per sensor and a configuration self-test.- Location: a small, complete service with a section, status and telemetry.
For the contracts behind each step, follow the links to the SDK component pages and the crate rustdoc in SDK crates.
Customize firmware with AI
An AI coding assistant is a good fit for ROHI firmware: the SDK is built from small, typed components with written contracts, a support matrix says what is verified, and a handful of commands tell the assistant (and you) immediately whether a change holds together. This page describes a workflow that keeps the assistant useful and honest, with prompts you can copy.
The assistant writes code; you verify it on hardware. Compiling, passing host tests and a CI build are not hardware validation, and an assistant must not claim otherwise. See Validation.
What to give the assistant
Open the rohi-sdk repository (or a repository that depends on it) in the assistant and tell it where the facts are:
| Source | What it answers |
|---|---|
Support matrix (device-matrix.toml) | what ROHI supports per board, firmware and capability, and what is verified |
Create & customize guides (docs/guides/) | the step-by-step procedure for each kind of change |
| Core concepts | what Config, Status and Action are |
firmwares/altruist-urban | the reference composition to copy from |
examples/ | one small program per sensor |
the crate rustdoc (cargo doc --no-deps) | APIs and contracts |
| Targets and features | the exact build commands per chip |
A short standing instruction in your assistant’s project instructions file helps. This one is a starting point:
This is a Rust no_std firmware workspace for ESP32-C3 and ESP32-C6 built on the ROHI SDK.
- Before changing anything read the matching guide in docs/guides/ and copy the structure of
firmwares/altruist-urban; do not invent APIs, read the crate source.
- Hardware facts (boards, pins, sensors) come only from device-matrix.toml and
crates/hal-esp/src/board/altruist_urban/mod.rs. If a fact is missing, say so; never guess pin numbers.
- Never claim that something works on hardware. Report what you ran: cargo test,
cargo check-esp32c3, cargo check-esp32c6.
- Drivers contain no pin numbers. Application code does not allocate. Config field ids are
only ever appended, never reused or renumbered.
- Keep changes small and update the support matrix and the docs in the same change.
The loop
-
Ask for a plan first. Have the assistant name the files it will touch and the guide it follows. Reject plans that edit the SDK crates when a firmware change is enough.
-
Make one small change. One sensor, one setting, one action.
-
Let it run the checks and read the result yourself:
cargo test # host tests, no hardware cargo check-esp32c3 && cargo check-esp32c6 # both chips type-check cargo clippy --all-targets -- -D warnings -
Flash and look. Run it on the board, then
rohi status,rohi config,rohi action: a correct change shows up in the generic client without any client change (Desktop application). -
Record the result, success or failure, in the support matrix.
Prompts
Replace the names in brackets. Each prompt follows the guide linked next to it.
Add a sensor
Add support for the [SCD41] sensor to the altruist-urban firmware.
Follow docs/guides/add-sensor.md. First check device-matrix.toml and tell me
whether the Altruist Urban has this part and what is already implemented. Reuse the
existing driver in crates/hal if there is one. Show me the plan and the files you will
change before editing. Afterwards run cargo test and cargo check-esp32c3 and
cargo check-esp32c6, and update the support matrix without marking anything verified.
Add a setting
Add a configuration section `sampling` with a field `interval_s` (u32, default 60,
allowed 10..=3600) and use it as the poll interval of the [SDS011] sensor task.
Follow docs/guides/add-config-section.md: typed section, stable field
ids, whole-section validation and a golden test of the stored bytes, so that
`rohi config sampling` works. Do not change the control protocol or the rohi tool.
Add a status service
Add a service `[battery]` that reports health and the field
`voltage` in volts, with an issue `low_voltage` below [3.3] V. Follow
docs/guides/add-service.md and copy the structure of the location service. Register it
in firmwares/altruist-urban/src/control.rs. Add host tests for
every health value and show me the expected `rohi status [battery]` output.
Add an action
Add a control operation or an action
Add an action `calibrate` to the `[sensors]` service that takes the argument
`reference_ppm` (u64) and needs mutate access. Follow docs/guides/add-control-operation.md,
check cancellation safety, and add a host test of the action including the
refusal case with a stable reason code.
Remove or trim a firmware
I only need the sensors and BLE control, no Wi-Fi, time or telemetry. List what
firmwares/altruist-urban starts in main.rs and what depends on what, propose the
smallest set of removals, and check that cargo check-esp32c3 still passes. Do not
change anything in crates/.
Support a new board
I have a board with [ESP32-C6, BME280 on I2C GPIO6/GPIO7, no other sensors].
Follow docs/guides/add-board.md: a new board module in crates/hal-esp and a new
firmware crate, with its own resource budget. Take the pins only from what I give you
here. Add the board to the support matrix with every hardware verification set to
not-verified and list what I have to test on the device.
Review a change
Review the diff against docs/guides/add-config-section.md and
the SDK rules: no allocation in application code, no pin numbers in
drivers, field ids only appended, cancellation-safe async, no secrets logged. List
violations only, with file and line.
Explain a failure
`cargo check-esp32c6` fails with the following error: [paste]. Explain the cause in
terms of the ROHI crates involved and propose the smallest fix. Do not disable a check
or add an allow attribute.
Pitfalls
- Hardware facts. Assistants invent pin numbers and part numbers. Pin maps live in the board module rustdoc; verified status lives in the support matrix.
- Compiles is not works. A passing build says nothing about wiring, timing or calibration.
- Wrong layer. A new feature usually belongs in a feature crate plus a firmware registration, not in the control protocol or the desktop tool; those need no change (Create & customize).
- Stable ids. Field ids, action ids, issue codes and section ids are part of the stored and wire contract. Do not let an assistant renumber or rename them.
- Secrets. Never paste Wi-Fi passwords or device keys into a prompt.
Add a sensor
A sensor is a driver in rohi-hal run by a generic runner that publishes rohi-sensors observations; the board crate supplies the bus and the firmware spawns
one task. Drivers know nothing about networks or serialization. The contracts (driver trait, runner, observations,
freshness) are in the rohi-sensors rustdoc, the rohi-hal rustdoc and the
sensor drivers.
- Model the observation in
rohi-sensors: add the sensor kind and its typed measurement with its units, grouped by the physical sensor (never merge readings of different sensors), and give it a freshness policy that outlasts its worst healthy cadence. - Write the driver in
crates/hal/src/sensors/<name>.rsagainst the driver trait: probe and configure, read the next observation, report an absent sensor differently from a failing one. - Test on the host with the mock bus and the recording delay: detection, a failing bus, recovery, warm-up and the exact decoding of datasheet examples. See Host testing.
- Wire the bus in the board module of
rohi-hal-espif the sensor needs pins or a new peripheral (see Add a board); drivers never name pins. - Spawn a task in
firmwares/altruist-urban/src/esp/sensors.rsand start it insrc/bin/firmware.rswith the other sensor tasks. - Expose it to the control plane if it should be visible: add its measurements and issue codes to the
sensorsservice (crates/sensors/src/managed.rs). The protocol and therohitool need no change; see Add a service. - Add a hardware example in
examples/src/bin/if useful and record the validation in Hardware testing. Update the support matrix (implementation, integration, evidence) without marking anything verified that was not run on hardware. - Update the docs (policy): the rustdoc of the driver and, for a new limit, the memory model.
One task owns one driver, and a bus transaction must not be cut short by a select; see the
cancellation rules. Do not allocate.
Add a ConfigSection
A configuration section is a typed group of settings that a user can read and change with rohi config. It is owned by
the feature crate that interprets it. What is stored on the device is only what the user overrides; everything else
follows the firmware default. The stored bytes are a persistent ABI, so read the rules in the
rohi-config rustdoc and the
versioning rules before choosing names and ids.
- Define the typed section in the feature crate with
#[derive(Config)]: bounded fields, aDefaultthat is the portable baseline, a stable numeric id per field, and the public section and field names, units and ranges. One declaration generates the stored overrides, the schema clients discover and the typed access. The attributes are documented in therohi-config-deriverustdoc and the model in therohi-servicerustdoc. - Validate the whole result. Write the validation for the complete effective configuration, and make “not configured” or “disabled” a valid state, because it runs on every change.
- Pin the stored encoding with a golden test on the exact bytes, as the existing sections do (for example the
Wi-Fi section in
rohi-net). - Register it in the firmware: describe the section once as a
Binding(firmwares/altruist-urban/src/bindings.rs: the firmware default overrides and the consumer that gets the effective value) and list it infirmware_configs!(firmwares/altruist-urban/src/config.rs). That one list drives registration, boot, commit, removal and factory reset; a section that needs a restart is published at boot only. - Use it in the runtime through the configuration handle. The configuration task is the only owner of the store; the runtime receives the effective value as desired state right after each commit (see the cancellation rules).
- Check it in a client.
rohi config <section>androhi config <section> FIELD=VALUEwork at once: the protocol, the client and the CLI need no change.FIELD=nonesets an optional field to an explicit no value;FIELD=nullremoves the override so the field follows the firmware default again. Secrets are write-only. - Later changes. Ids are only ever added, never reused or renumbered. Renaming the config type changes the stored section id and orphans the stored data unless the id is pinned explicitly. Changing the stored layout means a new version and, if old data must stay readable, a migration.
- Docs. Document the section in the rustdoc of its crate and, if a user can set it, in the Configuration page.
Per-section removal never touches sections of other features (for example the identity); there is deliberately no “erase everything” in the configuration handle.
Add or support a board
A board is a place where pins and buses are named. rohi-hal-esp is the single place for that; drivers, firmware tasks
and the portable crates never contain pin numbers. Existing example: rohi_hal_esp::board::altruist_urban
(Boards).
A new chip variant of an existing board (for example another ESP32 for the Altruist Urban):
- Add
esp32xx.rsnext toesp32c3.rs/esp32c6.rsinboard/altruist_urban/with the pin map and the peripheral types, and select it with a Cargo feature forwarded by the firmware and byrohi-hal-esp,rohi-config-esp,rohi-net-espand the other platform crates. - Add the matching
rohi-net-esp/esp-radiofeature, a partition table (firmwares/altruist-urban/partitions-<chip>.csv) mirrored by the layout ofrohi-config-esp(a host test keeps them in sync), and the Cargo alias plus runner entry in.cargo/config.toml(check-*,build-*). - Add the chip to the CI matrix, and to Targets and features. Chips are never
validated together with
--all-features.
A new board revision with a different pin map gets its own module instead of an edit of the existing tables.
A new board (new product):
- Create
board/<name>/inrohi-hal-espexposing a chip independent API that returns the configured buses (I²C, UART, I²S), ready for the sensor drivers; see the existing board module. - Create
firmwares/<name>/composing the portable crates. Put its static resource sizes in its ownsrc/resources.rsfollowing the memory model; the product owns its budget. - Document the pin map and its verification status in Boards, marking anything that has not been verified on hardware. Add the board and its capabilities to the support matrix in the same pull request.
Keep vendor types inside the platform crate and the portable APIs unchanged; if a portable crate needs to change for the new board, the seam was leaking (Portability).
Use IP networking
Open DNS and TCP connections through the network handle of rohi-net. Never use embassy-net or any vendor type
directly: code written against the standard embedded-nal-async and embedded-io-async traits is portable, testable on
the host and independent of the stack. The API, its errors and its limits are in the
rohi-net rustdoc.
Write portable code
Make your layer generic over the standard traits (see the example in the rustdoc) and handle the typed network errors:
- network unavailable: Wi-Fi is not connected or DHCP is incomplete; wait for the connection and retry. This is not a server problem.
- DNS or connect failure: the network is up but the name or endpoint failed; apply your own retry policy.
- no socket available: all TCP slots of the product are in use; the call does not wait. Close a connection first.
- reset or timeout: the connection is gone; reconnect.
Drop connections you no longer need and bound waits with your own timeout; dropping a pending connect is safe (cancellation).
Test on the host
rohi-net ships an in-memory fake network (the testing feature) that scripts DNS answers, refused connections,
readiness and slot exhaustion and lets the test play the peer. Use it from your crate’s tests.
Try it against real services
The Altruist Urban on std implements the same network handle on the IP stack of your computer (rohi-net-std), so code
that uses NetworkHandle can talk to 127.0.0.1, containers and local test servers without hardware.
On the device
The firmware creates the handle when it starts Wi-Fi and hands it to the component that needs it. Capacity is a product
decision in firmwares/altruist-urban/src/esp/resources.rs (see the
memory model). There is no TLS yet: do not send secrets in
clear text.
Telemetry profiles and delivery routes
Telemetry has two independent halves that you configure with ordinary Actions of the device, through the generic
rohi action command (see Add a control operation or an action):
- the
telemetryservice owns what a signed packet contains: two fixed profile slots,0and1. A profile has one public section and at most one recipient-private section that is encrypted to a recipient’s public key. The packet format is fixed (Robonomics); there are no names and no format choice; - the
connectivityservice owns where and how often a profile is delivered: two fixed route slots,0and1. A route has a profile slot, an interval, a primary endpoint (an opaque URI:http://host[:port], ormeshtastic+uart://!xxxxxxxxin a build with the Meshtastic backend) and at most one fallback endpoint.
Indices are stable: changing or clearing one slot never moves the other. A profile exists without any route (and
get_payload works without a network); a route only references a profile slot. Both profile slots start empty and disclose
nothing, and the device sends nothing until you set an endpoint on a route slot.
# Profile 0, for the community: the BME280 and PM10, in clear.
rohi telemetry set_public 0 bmx280,sds011.pm10
# Profile 1, for the owner: PM values in clear, the position and noise only for one key (a 32-byte Ed25519 key).
rohi telemetry set_public 1 sds011
rohi telemetry set_private 1 \
0xd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a \
location,microphone.average
rohi telemetry set_private 1 0xd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a none # remove it
rohi telemetry measurements 0 # the catalog: stable bit numbers and names the format can encode
rohi status telemetry # per profile: profile0_public, profile0_private, profile0_priv_selection, profile0_revision
# Deliver profile 0 every minute to an ingress from route slot 0, with one fallback for the same packet.
rohi connectivity set_endpoint 0 0 http://ingress.example.org
rohi connectivity set_interval 0 120
rohi connectivity set_fallback 0 http://backup-a.example.org
rohi connectivity set_fallback 0 "" # no fallback
rohi connectivity set_endpoint 0 0 "" # no route: the slot is empty
rohi status connectivity # per slot: route0_profile, route0_endpoint, route0_fallback, route0_state, route0_queue_depth, ...
# The sealed, signed packet of profile 1, with no route and no network (a standard stream).
rohi connectivity get_payload 1 > packet.bin
An absent endpoint is the empty string (""): set_endpoint with it deletes the route and set_fallback with it
removes the fallback. Positional arguments and named ones (rohi action connectivity set_endpoint index=0 profile_index=0 endpoint=) are equivalent.
Selections (bmx280,sds011.pm10, all, none) are names of the catalog; a sensor name stands for all of its
measurements. all never includes the position: location must be named. Names are turned into a 32-byte bitset by the
rohi client from the catalog Action; the device only ever sees the bits.
Rules worth knowing
- A slot is reusable, never stale. Changing the profile or the endpoint of a route, or deleting it and setting it again, starts a new route: it inherits no queued packet, counter, backoff or generation. A new route starts with an interval of 60 s. A fallback is another way to deliver the same packet, not another publisher.
- Policy changes win. Changing a profile (or clearing it by a factory reset) invalidates the packets that were built under the old policy before anything is sent again.
- Delivery. An acknowledgement from any path completes a packet: HTTP
202, or the matching routing ACK of every Meshtastic fragment (which proves the mesh delivered them, not that the gateway accepted the packet). A path that cannot carry this packet (too large for the mesh) hands it to the other path without a penalty. For HTTP: Failures try the next path at once;401/403also pause the failing path for ten minutes;400/413drop the packet without offering it to other endpoints. Retries send byte-identical bytes. Delivery is at-least-once, so the ingress deduplicates by the signed envelope. Every request carriesUser-Agent: <build>, thebuildofrohi info; it is not part of the signed payload. - Honest dating. A packet is dated at its capture; without a synchronized UTC clock, an identity or entropy the
packet is refused, never faked. The state of the last attempt is in
rohi status connectivity. - Stored data. There is no migration: the persisted
telemetryandconnectivitysections of the earlier named profiles and routes are not read. A device that stores one reports it in the log and starts with empty slots; the next change replaces it. - Limits. 2 profile slots with 1 private recipient each and 2 route slots with 1 fallback each: these are compile-time
capacities of the Altruist Urban firmware (the storage is sized for them, a stored table over capacity is refused, not
truncated, and the
connectivitystatus schema has exactly two route slots, with the fields of each slot in the flat status asroute0_*androute1_*). Endpoints are up to 64 bytes, checked with the schemes the build supports before they are stored, all within the 1 KiB persistent section of each service. What the Robonomics format cannot encode (the SCD4x, for example) is not in the catalog and is rejected, never published under another name.
Reference: rohi-telemetry,
rohi-telemetry-robonomics and
rohi-connectivity. The wiring of Altruist Urban is in
firmwares/altruist-urban/src/{telemetry,connectivity}.rs.
Meshtastic radio over UART
A device can use a local Meshtastic radio in two ways, both opt-in with the meshtastic-uart feature of
altruist-urban (cargo check-esp32c3 --features meshtastic-uart, the same for esp32c6):
- the
meshtasticservice manages and diagnoses the radio: its configuration, its health and a small send/receive test; - the
connectivityservice delivers sealed telemetry packets tomeshtastic+uart://!xxxxxxxxendpoints through that radio, as a primary or a fallback path of a route.
The radio is a separate Meshtastic device running Meshtastic firmware, not a bare LoRa chip. Its Serial module must
speak the protobuf PhoneAPI (PROTO mode) at the baud rate of the meshtastic section. Which UART and which pins carry it
is decided by the board (rohi-hal-esp), never by the configuration or by an endpoint.
| Chip | UART0 TX | UART0 RX | Status |
|---|---|---|---|
| ESP32-C3 | GPIO21 | GPIO20 | chip defaults, not verified against the board revision |
| ESP32-C6 | GPIO22 | GPIO20 | the pins the CN4 documentation reserves for the Meshtastic module; the direction is unverified, swap them if the radio stays silent |
UART1 stays with the SDS011. UART0 is also the boot console of the chip, so the firmware (every build of it, with or
without this feature) and the examples send their log over USB Serial/JTAG (esp-println feature jtag-serial)
and no longer to UART0 when no USB host is attached; the persistent log in flash is unchanged. The ROM bootloader still
prints on UART0 before the application starts.
Use 3.3 V logic and a common ground.
Configuration
rohi config meshtastic # baud_rate = 115200
rohi config meshtastic baud_rate=57600 # applies by starting a new session, no reboot
baud_rate is the only field: 9600, 19200, 38400, 57600, 115200 or 230400. There is no enabled field; the service runs
whenever the backend is built in.
Status and issues
rohi status meshtastic
| Field | Meaning |
|---|---|
node_id, firmware_version, hardware_model | what the radio said about itself; absent until known |
last_rx_age_s, session_age_s | seconds since the last valid message and since the session was established |
tx_frames, rx_frames | messages written to the UART and valid messages received |
framing_errors, decode_errors | invalid frame headers and frames that did not decode |
reconnects | session attempts after the first |
last_error | none, uart_io, uart_closed, handshake_failed, radio_rebooted, framing, decode, requested, baud |
The counters live in RAM, restart at zero with the device and saturate at the largest u64. Health is unknown until the
first synchronization finished or failed, ok while the session is up, degraded while it is recovered, error when the UART
cannot be used or the radio does not answer. The service is not essential: a missing radio does not make the device
unhealthy. Issues: uart_unavailable, radio_not_configured (the radio talks, but not the PhoneAPI: set the Serial module to
PROTO), radio_unresponsive, protocol_error, radio_reconnecting.
Actions
rohi action meshtastic send to=!deadbeef text="Hello ROHI" # TEXT_MESSAGE_APP, unicast, channel 0, want_ack
rohi action meshtastic inbox # six entries, newest first
rohi action meshtastic reconnect # new session without a reboot
send returns the packet_id once the local radio accepted the packet. That is not a delivery: the routing result
arrives later and shows up in inbox as an ack entry. inbox keeps the last six text messages and acknowledgements
of diagnostic sends in RAM, does not clear on reading, skips texts over 64 bytes and never shows telemetry traffic.
Delivering telemetry
rohi connectivity set_endpoint 0 0 meshtastic+uart://!deadbeef
rohi connectivity set_fallback 0 http://ingress.example.org
The URI is exactly meshtastic+uart://! and eight hexadecimal digits: the gateway node, not the local radio. No port,
path, query or device parameter exists. A build without the UART backend refuses the scheme (unsupported_endpoint_scheme),
and meshtastic+ble:// is refused everywhere: there is no BLE backend. A route may mix transports; the sealed packet is
never rebuilt, re-signed or changed.
The framing is Meshtastic Transport v1 (219-byte MTU, at most 16 fragments and 3376 bytes), every fragment a PKI-encrypted unicast with a routing acknowledgement request. The delivery succeeds when every fragment got its matching successful routing ACK. That proves the mesh delivered the fragments, not that the gateway reassembled, validated or published them. A packet too large for the mesh is not an error of the route: it is offered to the other path, and only a packet no path can carry is dropped and counted. Delivery is at-least-once; the gateway deduplicates by the signed envelope.
If a firmware without the backend reads a stored route that uses it, the stored data stays untouched, connectivity
reports unsupported_scheme and sends nothing until the route is removed or replaced (set_endpoint 0 0 "").
Reference: rohi-meshtastic and
rohi-connectivity-meshtastic. The wiring is in
firmwares/altruist-urban/src/{meshtastic,connectivity}.rs and src/esp/meshtastic.rs.
Add a service
A service makes a runtime part of the device visible and controllable: its state (rohi status <name>), optionally
its configuration (rohi config <name> ...) and its actions (rohi action <name> ...). It needs no change
to the protocol, the dispatcher, the client or the CLI: you implement the rohi-service traits in the crate that owns
the runtime and add the result to the firmware. The contracts are in the
rohi-service rustdoc; the Location service
(rohi-location) is a small complete example.
1. Status
Give the service a name with #[derive(Service)] (its numeric id comes from the name) and implement Status over a
handle to the live runtime state, without a duplicated status struct. A good status:
- reports one health: a disabled service is
unknown, not an error, a working one with reduced capability isdegraded; a service-specific state is a status field, not a common one; - reports issues as currently active problems with a stable numeric code and a severity, never message text or history;
- gives every field a stable id and unit; a value that does not exist now is simply not written;
- is a cheap, non-blocking snapshot: do not wait on slow hardware inside it.
The SDK adds the status revision and the time in the current state; the firmware decides the device health.
2. Config (optional)
If users configure it, add a section as in Add a ConfigSection. Name the section like the
service when they belong together (location, connectivity, wireless).
3. Actions (optional)
Operations the service offers implement Action, see Add a control operation or an action.
4. Register in the firmware
In firmwares/altruist-urban/src/control.rs add the service instance to the firmware’s services, construct it in
device() and add a reference to the status tuple if it reports status and to the action tuple if it offers actions
(the Embassy control task needs the concrete types). A duplicate id is a build error. A config section is not added
there but in firmware_configs! (see Add a ConfigSection). If the runtime must react to a
stored section, the configuration owner publishes it in the commit step through the section’s binding.
5. Tests
- The feature crate: the status in every state (summary, issues, values) and the schema, and for a section the validation and a golden test of the stored bytes.
- End to end:
tools/rohi/tests/common/mod.rsbuilds the fake device from the real sections and services; add yours there and testrohi config <name> FIELD=VALUEandrohi status <name>against it.
6. Docs
Document the service in the rustdoc of its crate (what it reports, issue codes, fields), list it in Status & diagnostics, and update the SDK crates page if it is a new crate.
Add a control operation or an action
The control plane is generic: you almost never touch the protocol. Decide what you are adding, then use the matching
recipe. The wire contract is in the rohi-control rustdoc and
rohi-control-proto.
| You want a client to… | It is a… | Recipe |
|---|---|---|
| set how a module behaves, persistently | config section | Add a ConfigSection |
| see what a module is doing now | service status | Add a service |
| make a module do something (scan, reconnect, provision) | action | below |
| something that fits none of these | a new protocol operation | A new request |
An action
An action is a capability of a service, so adding one is a change inside the service’s crate; see the
rohi-service rustdoc for the contract.
- Describe it in the service’s action table: a stable numeric id that is never reused, a name, typed arguments (all
required) and its result format (
.format(ResultFormat::...)):Empty(the default),Inline,Records,FeedorStream, see Action result formats.InlineandRecordsalso list the fields of the record. A longer collection stays in the service as a snapshot (ActionOutput::snapshot) that the control plane reads page by page withAction::read_records; the action has no paging argument of its own. - Declare the access. Every action states what the link must be allowed to do:
ActionAccess::Readfor a scan,Mutatefor an action that changes the runtime or the configuration,Provisionfor one that changes what identifies the device (the identity, the whole configuration storage). A secret argument is a separate property (.secret()): it only makes the argument wiped after the call and never logged, and it does not change the access. - Implement it in the service’s
invoke. The arguments are already checked against the description, and the output refuses anything but the declared format. Refuse with a stable, machine readable reason that a client may react to. - Mutation rule. If the action commits durable state that a runtime must react to, the commit and the publication happen in the owner task. Long-running actions bound their own wait and must be cancellation safe, see the cancellation rules.
- Tests: the action against the registry (arguments checked, the result of its format, refusals) and, if the privilege matters, through the dispatcher.
- Docs: the rustdoc of the service.
rohi action <service>lists the action and generates its help from the device; no protocol, dispatcher, client or CLI change is needed.
A new request
Only when the operation fits none of the planes (config, status, actions, info):
- Schema in
crates/control-proto/proto/rohi/control/v2/control.proto: add the messages and aoneofentry with a new field number; bound every repeated, string and bytes field inbuild.rsand keep the memory budget test green. Prefer a result format to a larger response. An incompatible wire change raisesPROTOCOL_VERSION; the client and the firmware are updated together. - Dispatch in
rohi-control: handle the call, decide its privilege and map the types; protobuf types do not leak into other crates, and secrets are never returned or logged. - Backend: if the dispatcher needs something from the firmware, add it to the control backend and update its
implementations (the device, the fakes in
rohi-control-bleand thetools/rohitests). - Client: add the generic method to the
rohilibrary and, if useful, a CLI subcommand. - Tests: protocol golden bytes and bounds, dispatcher authorization and validation, an end-to-end loopback, and a cancellation test if the operation is long-running.
- Docs: the rustdoc of
rohi-controlandrohi-control-proto.
Run Altruist Urban on std
The Altruist Urban application also runs as a normal process on your computer. It is not a set of test mocks and not a
separate firmware: it is the same altruist-urban package, built from the same portable crates, on the std
platform instead of the ESP32 platform. Use it to develop and test the ROHI desktop and mobile applications without a
board, to test configuration, control and network flows end to end and to reproduce sensor, network and storage failures
on demand.
altruist-urban
shared application and services
Config · Status · Action
│
rohi-control
common controller
│
┌───────────────┴───────────────┐
rohi-control-ble rohi-control-tcp
┌─────┴──────┐ │
ESP BLE BlueZ BLE rohi-net-std
│ │ host TCP
ESP32 std Altruist Urban ────────┘
│
rohi-sim (optional sensors)
The platform changes only what is ESP-specific. The measurement runtime, the configuration store, the Wi-Fi manager, the control dispatcher, identity, time and the telemetry profiles, the connectivity routes and the publisher are the ones the firmware runs (a packet needs a synchronized UTC clock, so on the host it is built once NTP has answered).
| On the device | On std |
|---|---|
| I²C / UART / I²S sensor drivers | simulated sensors (sensor-simulator) that feed the same measurement runtime; without the feature no sensor is reported |
rohi-cfg flash partition | a file that follows NOR flash rules (erase before rewrite, 1→0 programming, 4 KiB sectors) |
| Wi-Fi radio | a model of access points behind the same Wi-Fi manager (rohi-sim) |
embassy-net IP stack | the IP stack of your computer (DNS, TCP, UDP), including localhost (rohi-net-std) |
| BLE peripheral (TrouBLE) | optional BlueZ peripheral on Linux (std-ble, see Linux BLE) |
| control over BLE | control over BLE and/or TCP (std-tcp, rohi-control-tcp); the protocol is the same |
Cargo features
| Feature | Purpose |
|---|---|
std | build and run on a host OS; the binary altruist-urban; the development-management interface |
std-tcp | control over TCP; requires std (implied) |
std-ble | control over a BlueZ BLE peripheral; requires std (implied), Linux only |
sensor-simulator | simulated BMx280, SCD4x, SDS011 and noise sensors and scenarios; requires std (implied) |
esp32c3, esp32c6 | the hardware targets; cannot be combined with std |
std-tcp, std-ble and sensor-simulator are independent: any subset builds. Combinations of the platforms are
rejected when the crate is built, and std-ble is rejected outside Linux. Without sensor-simulator no sensor is
fabricated: the sensors service reports every sensor as not detected. Without std-ble the BLE peripheral is
disabled and says nothing to the wireless health; it never pretends to advertise over TCP.
Run it
# Desktop development: control over TCP, simulated sensors
cargo run -p altruist-urban --bin altruist-urban --features std,std-tcp,sensor-simulator
# Mobile development on Linux: control over BLE
cargo run -p altruist-urban --bin altruist-urban --features std,std-ble,sensor-simulator
No ESP toolchain and no flashing tools are needed. TCP and BLE can be used together
(--features std,std-tcp,std-ble,sensor-simulator). The process prints a READY line with the interfaces that run once
it is up:
READY control=127.0.0.1:9300 manage=127.0.0.1:9301 ble=default
Stop it with Ctrl-C or SIGTERM: it flushes its storage and exits cleanly. Startup problems (a storage file that cannot be opened, an invalid scenario, a port that is already in use) are reported with a message and a non-zero exit status, never with a panic.
| Option | Meaning |
|---|---|
--name | device name used in logs |
--bind ADDRESS | address of the control and management listeners (default 127.0.0.1) |
--unsafe-allow-remote | allow a non-loopback --bind, see Security |
--control-port | port of the TCP control transport (std-tcp; default 9300, 0 picks a free port) |
--manage-port | port of the management interface (default: control port + 1) |
--ble-adapter | the Bluetooth adapter, for example hci0 (std-ble; default: the default adapter of BlueZ) |
--storage FILE | configuration flash image (default .altruist-urban/device.flash); the persistent log is kept next to it in device.log.flash |
--ephemeral | keep the flash and the persistent log in memory only |
--scenario FILE | scenario file, see below |
--seed N | seed of every random sequence of the simulation |
--log-level | error, warn, info, debug, trace (RUST_LOG overrides it) |
What it validates, and what it does not
It validates application logic, service boundaries, state machines, protocols, persistence (including interrupted writes), network behaviour and failure handling. The BlueZ peripheral lets a real phone discover and operate it.
It does not simulate CPU timing, RF behaviour, the real Wi-Fi association and BLE controller behaviour, electrical behaviour of I²C and UART, DMA, the ESP memory layout, power consumption or radio coexistence. Those stay hardware-validation concerns, see Hardware testing. In the support matrix this is software integration testing, not hardware validation.
Control over TCP and the rohi tool
The normal rohi commands work unchanged; only the target differs:
rohi --device tcp://127.0.0.1:9300 status
rohi --device tcp://127.0.0.1:9300 status sensors
rohi --device tcp://127.0.0.1:9300 action wireless wifi_scan
echo 'a long password' | rohi --device tcp://127.0.0.1:9300 config wireless wifi_ssid=ROHI-LAB wifi_password=-
rohi --device tcp://127.0.0.1:9300 status wireless
rohi system reboot restarts the process in place and keeps its ports; rohi system factory_reset formats its flash
and does not restart (run rohi system reboot afterwards if a restart is required). TCP is an
independent transport of the same protobuf messages, with its own framing and no BLE concepts (no fragmentation, no
connection state faked from BLE). A plaintext connection starts with the five-byte preamble ROHP + version 1 (a
connection that starts with ROHI is the PSK handshake instead, see the security section); then each message is a record:
+--------------------+------------------------------+
| length: u32 LE | length bytes of Protobuf |
+--------------------+------------------------------+
A client sends Request records and gets one Response record for each, in order. The length is checked against the
limits of the protocol (768 bytes for a request, 2048 for a response) before any payload is read; a length of 0 or above
the limit is answered once with an InvalidArgument error and the connection is closed, because the stream cannot be
resynchronized. A record that is not valid Protobuf is answered with InvalidArgument and the connection stays open. One
client is served at a time; another connection waits until the first closes. The contract and its tests are in the
rustdoc of rohi-control-tcp.
Security
The management interface is a development transport with no encryption and no authentication. The control endpoint is protected by its access mode (see Access control):
- the TCP endpoint is protected by default (
control.tcp_access_mode): a plaintext client may read, and a client that completes a handshake with the 32-byte pre-shared key may do everything, with every request and response authenticated and encrypted.rohi --psk-file FILEdoes it automatically.openallows everything without the key andprivateserves only the authenticated, never falling back to plaintext; - without a key a
protectedendpoint only reads and aprivateone serves nobody; the listener still runs and reportstcp_state=running. Give the process the key with--control-psk-file FILE(64 hex characters or 32 raw bytes, for that run; it replaces the stored key and is never stored or logged) or let the device generate it:rohi action control tcp_generate_psk(every call makes a new key, a client never chooses one; the generic action output prints the key, see Access and the TCP key).--control-mode open|protected|privatesets the mode for one run;--control-openis--control-mode open: unauthenticated, for loopback development only, and even then the key itself is never accepted over plaintext; - the stored
controlsection (tcp_access_mode,tcp_bind_address,tcp_port) is read at start, on top of the defaults (an empty storage is the defaults, there is noenabledflag);--bindand--control-portoverride the stored address and port for that run. A change applies as a whole at the next start. If the stored or default port is taken the endpoint isfailedin its status and the rest of the device starts; a port given on the command line that is taken is a startup error; - both listeners bind to
127.0.0.1by default; a non-loopback address, from--bindor from the section, is refused unless--unsafe-allow-remoteis given: with the endpoint protected a remote client still needs the key to change anything; with it open (--control-open) anyone who can reach the port can read and control the device; - BLE (BlueZ) is open: no pairing and no link encryption, and the link is never reported as encrypted or authenticated.
Anyone in radio range can do everything, including
tcp_generate_pskandsystem factory_reset; protecting TCP does not secure the device while BLE control runs.
A signature gives no confidentiality; none of this is production-secure.
Storage
The configuration lives in a flash image file and survives restarts. The process uses the real configuration store on it,
so the A/B slots and the commit-last recovery behave as on the device. Use --ephemeral for throw-away runs and
--storage /tmp/device-a.flash to keep several devices apart. A storage file can be used by one process at a time.
The persistent device log is a second image file next to it (device.flash is paired with
device.log.flash), a 1 MiB image with the geometry of the rohi-log partition (256 sectors of 4 KiB), so rohi logs works against the process and the
history survives a restart. A new file is formatted on its first start and kept on the next ones. A log image of the former 256 KiB layout is not migrated: the process refuses it at startup and names the file, delete it to start a new log. There is no SD card on the host: logging.storage = sd reports storage_unavailable.
Scenarios
A scenario is a TOML file that describes the initial sensor values, the Wi-Fi networks and a timeline of events. It is
separate from the persistent device configuration. Three are checked in under crates/sim/scenarios/: office.toml,
sensor-failure.toml and network-flap.toml.
[sensors]
temperature = 22.5 # °C
humidity = 45.0 # %
pressure = 1013.0 # hPa
co2 = 600 # ppm
pm25 = 8 # µg/m³
pm10 = 12
noise = 42 # dB
interval = "1s" # time between measurements
warm_up = { scd4x = "5s" }
[freshness]
stale_after = "10s" # measurements older than this are stale
[wifi]
networks = ["ROHI-LAB", { ssid = "Office", rssi = -60, security = "wpa2", password = "secret" }]
[[events]]
at = "30s" # uptime of the device
action = "set"
sensor = "co2"
value = 1200
[[events]]
at = "60s"
command = "fail sds011"
The default device has the sensors BMx280, SCD4x, SDS011 and the noise microphone, and the networks ROHI-LAB, Office
and Guest. Values reach the control plane through the normal measurement runtime; nothing writes a snapshot directly,
so a simulated change is visible through ordinary control operations. With --seed N the same scenario, seed and
configuration produce the same simulated sequence.
Development management and fault injection
The management interface is a line-based text protocol on its own port. It is separate from the device control protocol,
is not part of rohi-control-proto and only concerns the simulation. Ordinary device operations always go through the
control transport.
printf 'set co2 1200\nfail scd4x\nstatus\n' | nc -N 127.0.0.1 9301
| Command | Effect |
|---|---|
set <value> <number> | change temperature, humidity, pressure (hPa), co2, pm25, pm10, noise (needs sensor-simulator) |
fail <sensor> [unavailable|init|read|timeout|nodata], recover <sensor> | sensor faults; nodata is a warm-up or a stale measurement (needs sensor-simulator) |
network down, network up | all access points disappear or return |
ap <ssid> down|up|rssi <dBm> | one access point |
wifi fail association|authentication|dhcp, wifi recover, wifi delay <ms>, wifi drop, wifi flap <up ms> <down ms>|off | connection failures, delays, a lost or flapping link |
ip fail offline|dns|connect|reset, ip recover, ip latency <ms>, ip drop-next | faults of the IP data plane above the sockets |
storage power-loss program|erase <bytes> | the device loses power after that many bytes; the process ends like a device would |
storage corrupt crc|commit | damages the active configuration slot (seen at the next start) |
measurements, status, shutdown | the measurement snapshot with freshness, the simulated world, a clean stop |
A scenario can run any of these at a given uptime. Sensor failures travel through the normal sensor lifecycle: the sensor becomes degraded, then failed, and recovers with the usual backoff. The simulated sensors use shorter retry waits than the firmware so that scenarios stay short.
Several instances
Every instance needs its own storage and ports:
altruist-urban --name urban-a --control-port 9301 --manage-port 9401 --storage /tmp/urban-a.flash
altruist-urban --name urban-b --control-port 9302 --manage-port 9402 --storage /tmp/urban-b.flash
Instances are separate processes with no shared state. Two instances must not use the same Bluetooth adapter.
Integration tests
cargo test -p altruist-urban --features std,std-tcp,sensor-simulator # unit and end-to-end tests
cargo test -p altruist-urban --features std,std-tcp --test std_plain # without simulated sensors
cargo test -p altruist-urban --features std,std-tcp,std-ble --test std_ble
cargo test -p rohi-net-std --features ble # BLE bridge, no adapter needed
The end-to-end tests start the process on free ports with its own storage, wait for the READY line (no sleeps), talk to
it with the real rohi client library and stop it. They cover startup, sensors and freshness, sensor failure and recovery,
configuration persistence, recovery from an interrupted write, the Wi-Fi manager (connect, back off, recover), an
abandoned request, TCP framing errors, reconnection, readiness and the refusal of a remote bind. The harness is in
firmwares/altruist-urban/tests/common. None of them needs an ESP board or a Bluetooth adapter.
Local edge end-to-end
Identity, time and the telemetry uplink run on the host network. Provisioning a test identity and sending telemetry to a
local robins edge is possible by hand (rohi action identity provision, set a telemetry profile and a route:
rohi telemetry set_public 0 bmx280,
rohi connectivity set_endpoint 0 0 http://127.0.0.1:PORT), but an automated end-to-end test against a local edge is not
implemented yet. There is no TLS yet.
Linux BLE peripheral and mobile testing
With the std-ble feature the std Altruist Urban advertises the real ROHI Control Service through BlueZ, so a phone
running the ROHI mobile application can discover and operate it without a board. The GATT service, UUIDs, framing and
request/response behaviour are the ones of the ESP32 firmware (rohi-control-ble); the mobile application needs no
special mode.
cargo run -p altruist-urban --bin altruist-urban --features std,std-ble,sensor-simulator
Requirements
| Requirement | Why |
|---|---|
Linux with a recent BlueZ and bluetoothd running | the peripheral is a BlueZ GATT application and advertisement, reached over D-Bus |
| A Bluetooth adapter with LE peripheral (advertising) support | check btmgmt info; some virtual machines and containers do not expose an adapter at all |
| Access to the system D-Bus and permission to register GATT applications | normally the bluetooth group or a D-Bus policy for your user; running as root also works |
libdbus-1 development files to build (libdbus-1-dev, or dbus in the nix shell) | bluer links libdbus |
| The adapter is not blocked and not in use by another peripheral application | rfkill unblock bluetooth; bluetoothctl power on |
Check the adapter first:
systemctl status bluetooth # bluetoothd is running
bluetoothctl show | grep -E 'Powered|Roles|Name' # an adapter, Powered: yes
btmgmt info | grep -i 'current settings' # le is listed
What to expect
The device advertises the service UUID of the ROHI Control Service with the name ALTRUIST-URBAN-<last two bytes of the adapter address>, or the ble_name of the wireless configuration section (read at start, so a change applies after a restart).
The wireless service has no BLE field: a working peripheral (advertising or connected) reads as ok.
If BlueZ, the D-Bus socket or the adapter is missing, the device still starts and serves TCP; the wireless service reports
the failure as its health and issues and bringing BLE up is retried every few seconds. Use rohi --device tcp://127.0.0.1:9300 status wireless
to see it, or the log (--log-level debug).
Smoke test with a phone
firmwares/altruist-urban/scripts/ble-smoke.sh automates the setup checks and starts the device:
firmwares/altruist-urban/scripts/ble-smoke.sh # default adapter
firmwares/altruist-urban/scripts/ble-smoke.sh hci1 # another adapter
With the device running, in the ROHI mobile application:
- Scan:
ALTRUIST-URBAN-XXXXappears. - Connect. Open the configuration: read the
wireless,time,locationandconnectivitysections. - Change a value (for example the
location) and read it back; restart the device with the same storage and check the value persisted. - Open the status of every service, including the
sensorsandidentitydiagnostics. Withsensor-simulator, runprintf 'set co2 1500\n' | nc -N 127.0.0.1 9301(the management port is also on loopback) and watch the value change. - Invoke an action (
wireless wifi_scan). - Disconnect, then connect again: the device advertises again after every disconnect.
The same steps work with the desktop tool over BLE from another machine or a second adapter: rohi scan,
rohi --device ALTRUIST-URBAN status.
Limitations
- Software integration only; not verified on physical hardware. The automated tests exercise the transport bridge
with
rohi-control-bleon top and the process with and without an adapter; they never talk to BlueZ or a phone. No adapter-and-mobile-app smoke-test result is available for this change. Keep Linux BLE at software-integration status until discovery, connection, Config, Status, Action and reconnection have been exercised on a real adapter and phone, and the result and platform limitations are recorded in the support matrix. - Open: no pairing. BLE control has no pairing and no link encryption in this build, and no setting changes that. The
link is never reported as encrypted or authenticated, and every client in range may change the device, provision the
identity, reset it and run
control tcp_generate_psk. Use it only in trusted environments; it is not secure. - Connection detection. BlueZ does not report an ATT connection to a GATT application. A central counts as connected when it subscribes to the TX characteristic or writes the RX characteristic, and as disconnected when its notification session ends. A central that never subscribes cannot receive responses and is not tracked.
- One central at a time, as on the device.
- macOS. CoreBluetooth peripheral support is not implemented; the
std-blefeature is Linux only. TCP control is expected to work on macOS but is not tested there.
SDK crates
The crate rustdoc is the reference for each SDK crate: its responsibilities, public interface, contracts and integration points. This book teaches the concepts and the workflows. Build the API documentation of the whole workspace with:
cargo doc --no-deps --open
Released crates are also published on docs.rs, for example rohi-sdk (the entry point and cross-cutting concepts) and rohi-hal. The source is in crates/.
| Crate | What it is |
|---|---|
rohi-sensors | typed measurements, sensor state, the store, the event bus and the sensors service |
rohi-hal, rohi-hal-esp | physical sensor drivers and their runner; ESP boards |
rohi-config, rohi-config-derive, rohi-config-esp | transactional configuration store, derive macros and flash backend |
rohi-service, rohi-service-derive | the config, status and action model and registries |
rohi-net, rohi-net-esp, rohi-net-std | Wi-Fi and IP networking, BLE transport traits, ESP backend, host (std) backend |
rohi-control-proto, rohi-control, rohi-control-ble | the control protocol, its dispatcher and its firmware-side BLE binding (the rohi tool reuses only its frame and uuid modules) |
rohi-control-tcp | the control protocol over TCP: independent length-prefixed records and the serving loop |
rohi-sim | the simulated world of a std application: sensors, Wi-Fi, IP faults, flash file, scenarios |
rohi-connectivity, rohi-connectivity-http, rohi-telemetry-robonomics | signed telemetry: the transport-neutral delivery core, HTTP delivery, the packet format |
rohi-meshtastic, rohi-connectivity-meshtastic | the meshtastic service (UART session, radio link, diagnostics) and Meshtastic delivery of telemetry (guide) |
rohi-time, rohi-time-ntp | wall-clock time |
rohi-identity | device identity and signer |
rohi-location | device location |
rohi-logging | persistent logging: the log sink, segment format, storage backends and the logging service |
rohi-system | the system service: reboot and factory reset Actions over a platform adapter |
rohi (tools/rohi) | desktop client library and CLI: Desktop application |
rohi-sdk | umbrella crate: re-exports the crates above behind Cargo features (service, hal, net, esp, …); the firmware depends on it alone |
The dependency rules and “where does new code go” are in the rohi-sdk rustdoc.
Reading the support matrix
The support matrix is the authoritative statement of what ROHI supports, on which board, with which firmware, and what has been verified. It is published in two forms generated from one source:
| Form | Location | For |
|---|---|---|
| Machine-readable | device-matrix.toml | tools and AI assistants |
| Human-readable | Support matrix | users and developers |
Hardware that exists is not the same as hardware ROHI supports, and compilation is not the same as hardware validation. The matrix never merges the layers below into one “supported” flag.
The layers
- Upstream hardware. Designs, schematics and datasheets live in airalab/hardware. The matrix links to them and never copies them.
- Other firmware. airalab/altruist-firmware is an independent
firmware with its own devices and features. Its claims are listed as
externaland are not ROHI support. - ROHI SDK. Drivers and services in
crates/(implementation). - ROHI firmware. What a firmware in
firmwares/actually starts (integration). - Software validation. Host tests, simulation and CI target builds.
- Hardware validation. A recorded run on a physical board.
Status definitions
Every entry describes one capability on one board with one firmware.
| Field | Values | Meaning |
|---|---|---|
board_part | documented, undocumented, not-on-board, not-applicable | Whether the board carries the hardware the capability needs, according to upstream documentation. undocumented means upstream does not say; not-applicable is for services without a dedicated part. |
implementation | implemented, partial, not-implemented, external | Whether ROHI implements the capability. external means only another firmware project does. |
integration | integrated, not-integrated, not-applicable | Whether this firmware starts it. |
host_tests | passing, none | Tests that run in CI without hardware (cargo test). |
simulation | yes, none | Peripheral-level emulation of the device. Host tests with mocked buses are not simulation. |
target_build | ci-built, not-built, not-applicable | The firmware builds for the board’s chip in CI. |
hardware_verification | verified, failed, not-verified, not-applicable | A recorded run on a physical board. |
not-verified means no evidence either way: it is neither success nor failure. verified and failed require
hw-report evidence: what device and revision, which firmware revision, the procedure and the result.
Each entry also carries limitations (calibration, units, accuracy, incomplete behaviour) and evidence, links to source
code, tests, CI, hardware reports or upstream documentation. The kinds of evidence are source, test, ci,
hw-report and upstream.
A board has one of three rohi_support values: supported (a ROHI firmware targets it), other-firmware-only (only
another project’s firmware targets it) and not-integrated (SDK pieces may exist, nothing targets it).
Common questions
These answers come from the matrix at the time of writing; the matrix is authoritative.
Does ROHI support Altruist Insight? The headless altruist-insight firmware targets ESP32-C6 with SCD41 sensing
and open BLE Control, without Wi-Fi/IP. Display support is not implemented. Neither the board mapping nor BLE/sensing
has been verified on hardware. See build and connection instructions.
Can I measure CO₂ with Altruist Urban? Not on the stock board: the Urban has no SCD4x. The ROHI Urban firmware starts the SCD4x driver, so a sensor on the I²C bus might work, but upstream does not document how to attach one and it is not verified.
Which Altruist Urban capabilities have been tested on ESP32-C6 hardware? None are recorded as verified. Every capability has host tests and a CI build for the C6, and the C6 pin map comes from the upstream schematic and is not verified on hardware.
Can I measure environmental noise, and how is it calibrated? Partly. The level is unweighted dB SPL (not dBA) from the nominal ICS-43434 sensitivity, with no per-device calibration, so it is not comparable to a calibrated sound level meter. See Sensors.
Can I build a water-quality monitor with the existing firmware? No. There are no water-quality sensor drivers, board or firmware. The SDK services (configuration, Wi-Fi, telemetry, BLE control) can be reused by a new firmware.
Maintenance policy
- A pull request that changes a board module, a sensor driver, a firmware’s wiring or a hardware result updates the matrix in the same pull request.
- A hardware result is added only together with a hardware report: add an
evidenceitem of kindhw-reportwith the board revision, the firmware revision, the procedure and the result. - After editing
device-matrix.toml, regenerate the page withcargo run -p rohi-devices -- render --write. - Set
reviewedwhenever the data is reviewed against upstream. cargo test -p rohi-devices(part ofcargo testin CI) checks the schema, that every referenced board, firmware, capability and evidence exists, that repository paths exist, that every sensor driver incrates/hal/src/sensorshas a capability, that the claims of an entry do not contradict each other and that the rendered page is current.- Upstream links point to a fixed commit of airalab/hardware; move them forward when re-reviewing.
Support matrix
Reviewed on 2026-11-30, schema version 1. The data is published as device-matrix.toml; how to read the statuses is explained in Reading the matrix.
Boards
| Board | Revision | Chip | ROHI support | Firmware | Upstream documentation |
|---|---|---|---|---|---|
| Altruist Urban | ES-ALTRUIST-URB-1, ESP32-C6-WROOM-1-N8 | esp32c6 | supported | ROHI altruist-urban (ROHI SDK) altruist-firmware (other project) | upstream airalab/hardware: Altruist Urban |
| Altruist Urban (legacy) | legacy ESP32-C3 Urban | esp32c3 | supported | ROHI altruist-urban (ROHI SDK) altruist-firmware (other project) | upstream airalab/altruist-firmware README |
| Altruist Insight | ESP32-C6 (airalab/hardware, Altruist/Insight) | esp32c6 | supported | ROHI altruist-insight (ROHI SDK) altruist-firmware (other project) | upstream airalab/hardware: Altruist Insight |
- Altruist Urban (esp32c6): Outdoor air-quality station: SDS011, BME280 and ICS-43434 microphone. The ROHI C6 pin map is taken from the upstream schematic and is not yet verified on hardware.
- Altruist Urban (legacy) (esp32c3): Legacy ESP32-C3 variant of the Urban. The ROHI pin map is checked against the Urban pinout, but airalab/hardware documents only the ESP32-C6 board, so there is no upstream schematic for this variant.
- Altruist Insight (esp32c6): Indoor station with an SCD41 CO2 sensor. ROHI provides headless SCD41 sensing and open BLE Control without Wi-Fi/IP; display support is not implemented. Board mapping, sensing and BLE are not verified on hardware.
Firmware
| Firmware | Maintainer | Chips | Location |
|---|---|---|---|
| ROHI altruist-urban | ROHI SDK | esp32c3, esp32c6 | firmwares/altruist-urban |
| ROHI altruist-insight | ROHI SDK | esp32c6 | firmwares/altruist-insight |
| altruist-firmware | other project | esp32c3, esp32c6 | https://github.com/airalab/altruist-firmware |
- ROHI altruist-urban: Rust firmware of this repository, selected per chip by the
esp32c3/esp32c6feature. - ROHI altruist-insight: Headless ESP32-C6 firmware: SCD41 sensing, configuration, RAM diagnostics and system actions over open BLE Control; no Wi-Fi/IP runtime.
- altruist-firmware: Independent PlatformIO firmware of the Altruist devices with its own feature set; ROHI has not assessed it and its claims are not ROHI support.
Capabilities per board and firmware
Altruist Urban with ROHI altruist-urban (esp32c6)
Limitations of BMP280 / BME280 environment:
- The ESP32-C6 pin map comes from the upstream schematic and is not verified on hardware.
- The driver handles BMP280 (no humidity) and BME280; the Urban documents a BME280.
Limitations of SCD40 / SCD41 CO2:
- The Urban sensor list has no SCD4x; the firmware starts the driver anyway and reports no measurement and an unhealthy sensor state when none answers on the I²C bus.
- Attaching an external SCD4x is not documented upstream and not verified.
Limitations of SDS011 particulate matter:
- The ESP32-C6 pin map comes from the upstream schematic and is not verified on hardware.
- The schematic names the SDS011 nets PM_TX and PM_RX without a viewpoint; swap the pins if the sensor stays silent.
- The SDS011 accuracy is ±10 µg/m³ or ±15 % (upstream datasheet figure).
Limitations of I²S microphone noise level:
- The ESP32-C6 pin map comes from the upstream schematic and is not verified on hardware.
- Unweighted dB SPL (not dBA) from the nominal ICS-43434 sensitivity (-26 dBFS at 94 dB SPL); no per-device calibration, so values include the microphone response and the device’s own noise.
- Not comparable to a calibrated, A-weighted sound level meter.
Limitations of Wi-Fi station and IP networking:
- Scan, connect, reconnect, wrong password, heap minimum and 24 h stability are listed as not yet measured on hardware.
Limitations of Time synchronisation (NTP):
- Depends on a working Wi-Fi connection; no hardware run recorded.
Limitations of Telemetry (profiles, packets and delivery routes):
- Depends on Wi-Fi, time and a provisioned device identity; no hardware run against a connectivity provider is recorded.
- The independent altruist-firmware reports to Robonomics through its own mechanism; the two are not interchangeable.
Limitations of BLE control plane:
- One heap measurement exists (Wi-Fi and BLE running, chip not recorded); advertising, coexistence, MTU and 24 h stability are not measured.
- BLE control runs open in this build: no pairing, no link encryption and no mode to change it, and the host stack is built without pairing support (an accepted, temporary insecure state, suitable only for trusted environments); open BLE control is not verified on a device.
- Static analysis only (
scripts/memcheck.sh, CI job Memcheck): 121 816 B main stack; the frames of the control request path (rohi status,config,action) are below 1.8 KB since #63, but the stack peak is not measured on a device and the exception reported forrohi status loggingandrohi logs clear --yesis not shown to be fixed.
Limitations of Persistent configuration store:
- The flash self-test (example-config) exists, but no run is recorded.
Limitations of Device identity:
- The hardware checklist (provision, reboot, erase, re-provision) has no recorded results.
Limitations of Persistent logging:
- Only the internal-flash backend exists; the SD backend is not implemented (issue #26 is implemented only in part) and
storage = sdreportsstorage_unavailable. - Flash erase and programming stall the whole CPU for tens of milliseconds per sector; the effect on Wi-Fi, BLE and the microphone DMA ring is not measured.
- Persistence across reset, power-loss recovery (including payload checksum validation and the history generation), flash rotation, coexistence with the configuration partition and the transfer speed of
rohi logs downloadover BLE are covered by host emulation only; no hardware run is recorded. - Static analysis only (
scripts/memcheck.sh, CI job Memcheck): 121 816 B main stack; the frame of invoking the logging service fell from 8 016 B to 5 808 B whenlogging.readwas replaced by the RAM-only tail (#70), which is now thelogging.tailaction returning one bounded page (no stream; since #78 thecontrol_taskpool is 560 B larger and the largest frame is unchanged), but the stack peak is not measured on a device and the exception reported forrohi status loggingandrohi logs clear --yesis not shown to be fixed.
Limitations of Managed control endpoints and transport security:
- BLE is open by default: anyone in radio range can change the configuration, provision the identity and enroll the administrator key; restricting TCP does not secure the device while BLE stays open.
- A signature authenticates one request; there is no confidentiality and the device is not authenticated to the client (no TLS or Noise).
- The stack high-water mark of the control worker are not measured on a device.
Limitations of System actions:
- The chip reset after the grace period and the formatting of the configuration partition by
system.factory_resetare not run on a device; the host process stands in for them in the tests. - Both actions are Mutate: open to any client in BLE range (the BLE control endpoint is open in this build) and, over TCP, need the authenticated and encrypted connection of the pre-shared key unless the mode of the endpoint (
tcp_access_mode) isopen.
Limitations of Meshtastic radio over UART:
- Opt-in: build with the
meshtastic-uartfeature. It needs a separate Meshtastic radio whose Serial module speaks the protobuf PhoneAPI (PROTO) on UART0. - UART0 uses GPIO22 (TX) and GPIO20 (RX), the pins the CN4 documentation reserves for the Meshtastic module; which signal is TX is not documented, so the direction is unverified: swap them if the radio stays silent.
- The firmware log goes over USB Serial/JTAG, so UART0 is free; the ROM bootloader still prints on UART0 at reset.
- The routing ACK of every fragment is the delivery proof; interoperability with the robins edge ingress is not verified on hardware. BLE is not implemented.
Altruist Urban with altruist-firmware (esp32c6)
| Capability | Board part | Implementation | Integration | Host tests | Simulation | Target build | Hardware | Evidence |
|---|---|---|---|---|---|---|---|---|
| BMP280 / BME280 environment | documented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README, upstream Altruist Urban sensor specification |
| SDS011 particulate matter | documented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README, upstream Altruist Urban sensor specification |
| I²S microphone noise level | documented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README, upstream Altruist Urban sensor specification |
Limitations of BMP280 / BME280 environment:
- Claimed by the altruist-firmware README; ROHI has not built or verified it.
Limitations of SDS011 particulate matter:
- Claimed by the altruist-firmware README; ROHI has not built or verified it.
Limitations of I²S microphone noise level:
- Claimed by the altruist-firmware README; ROHI has not built or verified it.
- Reports the level in dBA, a different metric from the unweighted dB SPL of ROHI; the values must not be compared.
Altruist Urban (legacy) with ROHI altruist-urban (esp32c3)
| Capability | Board part | Implementation | Integration | Host tests | Simulation | Target build | Hardware | Evidence |
|---|---|---|---|---|---|---|---|---|
| BMP280 / BME280 environment | undocumented | implemented | integrated | passing | none | ci-built | not-verified | source bmx280.rs, test bmx280 tests, source firmware sensor tasks, source C3 board module, source Boards, ci CI, source Hardware testing status |
| SCD40 / SCD41 CO2 | undocumented | implemented | integrated | passing | none | ci-built | not-verified | source scd4x.rs, test scd4x tests, source firmware sensor tasks, source C3 board module, source Boards, ci CI |
| SDS011 particulate matter | undocumented | implemented | integrated | passing | none | ci-built | not-verified | source sds011, test sds011 tests, source firmware sensor tasks, source C3 board module, source Boards, ci CI, source Hardware testing status |
| I²S microphone noise level | undocumented | implemented | integrated | passing | none | ci-built | not-verified | source noise.rs, test noise tests, source firmware sensor tasks, source C3 board module, source Boards, ci CI, source Sensors |
| Wi-Fi station and IP networking | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-net, test rohi-net tests, source firmware startup, ci CI, source Hardware testing status |
| Time synchronisation (NTP) | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-time-ntp, test rohi-time-ntp tests, source firmware startup, ci CI, source Hardware testing status |
| Telemetry (profiles, packets and delivery routes) | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-connectivity, test rohi-connectivity router and publisher tests, source firmware startup, ci CI, source Hardware testing status |
| BLE control plane | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-control-ble, test rohi-control-ble tests, source firmware startup, ci CI, source Hardware testing status, source memcheck task memory and stack budget analyzer, source Resource budget: static task memory, stack and frame results |
| Persistent configuration store | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-config-esp, test rohi-config store tests, source firmware startup, ci CI, source Hardware testing status |
| Device identity | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-identity, test rohi-identity tests, source firmware startup, ci CI, source Hardware testing status |
| Persistent logging | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-logging, source altruist-urban logging task and log backend, test rohi-logging service and storage tests, test altruist-urban host process: logging service, file-backed log flash, restart, test rohi logs against the real logging service, ci CI, source Hardware testing status, source memcheck task memory and stack budget analyzer, source Resource budget: static task memory, stack and frame results |
| Managed control endpoints and transport security | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-control-endpoints, rohi-control-tcp (secure channel), rohi-control (hub, access policy), test altruist-urban host process: access modes, pre-shared key and the secure channel over TCP, test rohi positional actions and the system actions against the in-memory device, ci CI, source Hardware testing status |
| System actions | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-system, source altruist-urban system service adapter (deferred reboot, storage-aware factory reset), test rohi-system service tests, test altruist-urban host process: system.reboot and system.factory_reset, test rohi positional actions and the system actions against the in-memory device, ci CI, source Hardware testing status |
| Meshtastic radio over UART | not-applicable | implemented | integrated | passing | none | ci-built | not-verified | source rohi-meshtastic, source rohi-connectivity-meshtastic, test rohi-meshtastic session, link and service tests, test rohi-connectivity-meshtastic transport and mixed-route tests, source Boards, ci CI, source Hardware testing status |
Limitations of BMP280 / BME280 environment:
- The ESP32-C3 pin map is checked against the Urban pinout, but this variant has no schematic in airalab/hardware and no recorded hardware run.
- The driver handles BMP280 (no humidity) and BME280; the Urban documents a BME280.
Limitations of SCD40 / SCD41 CO2:
- No upstream documentation of the variant’s sensors; the firmware starts the SCD4x driver and reports no measurement and an unhealthy sensor state when none answers.
Limitations of SDS011 particulate matter:
- The ESP32-C3 pin map is checked against the Urban pinout, but this variant has no schematic in airalab/hardware and no recorded hardware run.
- The UART wiring was not recorded in a hardware report.
- The SDS011 accuracy is ±10 µg/m³ or ±15 % (upstream datasheet figure).
Limitations of I²S microphone noise level:
- The ESP32-C3 pin map is checked against the Urban pinout, but this variant has no schematic in airalab/hardware and no recorded hardware run.
- Unweighted dB SPL (not dBA) from the nominal ICS-43434 sensitivity (-26 dBFS at 94 dB SPL); no per-device calibration, so values include the microphone response and the device’s own noise.
- Not comparable to a calibrated, A-weighted sound level meter.
Limitations of Wi-Fi station and IP networking:
- Scan, connect, reconnect, wrong password, heap minimum and 24 h stability are listed as not yet measured on hardware.
Limitations of Time synchronisation (NTP):
- Depends on a working Wi-Fi connection; no hardware run recorded.
Limitations of Telemetry (profiles, packets and delivery routes):
- Depends on Wi-Fi, time and a provisioned device identity; no hardware run against a connectivity provider is recorded.
- The independent altruist-firmware reports to Robonomics through its own mechanism; the two are not interchangeable.
Limitations of BLE control plane:
- One heap measurement exists (Wi-Fi and BLE running, chip not recorded); advertising, coexistence, MTU and 24 h stability are not measured.
- BLE control runs open in this build: no pairing, no link encryption and no mode to change it, and the host stack is built without pairing support (an accepted, temporary insecure state, suitable only for trusted environments); open BLE control is not verified on a device.
- Static analysis only (
scripts/memcheck.sh, CI job Memcheck): 21 976 B main stack; the frames of the control request path (rohi status,config,action) are below 1.8 KB since #63, but the stack peak is not measured on a device and the exception reported forrohi status loggingandrohi logs clear --yesis not shown to be fixed.
Limitations of Persistent configuration store:
- The flash self-test (example-config) exists, but no run is recorded.
Limitations of Device identity:
- The hardware checklist (provision, reboot, erase, re-provision) has no recorded results.
Limitations of Persistent logging:
- Only the internal-flash backend exists; the SD backend is not implemented (issue #26 is implemented only in part) and
storage = sdreportsstorage_unavailable. - Flash erase and programming stall the whole CPU for tens of milliseconds per sector; the effect on Wi-Fi, BLE and the microphone DMA ring is not measured.
- Persistence across reset, power-loss recovery (including payload checksum validation and the history generation), flash rotation, coexistence with the configuration partition and the transfer speed of
rohi logs downloadover BLE are covered by host emulation only; no hardware run is recorded. - Static analysis only (
scripts/memcheck.sh, CI job Memcheck): 21 976 B main stack; the frame of invoking the logging service fell from 8 016 B to 5 808 B whenlogging.readwas replaced by the RAM-only tail (#70), which is now thelogging.tailaction returning one bounded page (no stream; since #78 thecontrol_taskpool is 560 B larger and the largest frame is unchanged), but the stack peak is not measured on a device and the exception reported forrohi status loggingandrohi logs clear --yesis not shown to be fixed.
Limitations of Managed control endpoints and transport security:
- BLE is open by default: anyone in radio range can change the configuration, provision the identity and enroll the administrator key; restricting TCP does not secure the device while BLE stays open.
- A signature authenticates one request; there is no confidentiality and the device is not authenticated to the client (no TLS or Noise).
- The stack high-water mark of the control worker are not measured on a device.
Limitations of System actions:
- The chip reset after the grace period and the formatting of the configuration partition by
system.factory_resetare not run on a device; the host process stands in for them in the tests. - Both actions are Mutate: open to any client in BLE range (the BLE control endpoint is open in this build) and, over TCP, need the authenticated and encrypted connection of the pre-shared key unless the mode of the endpoint (
tcp_access_mode) isopen.
Limitations of Meshtastic radio over UART:
- Opt-in: build with the
meshtastic-uartfeature. It needs a separate Meshtastic radio whose Serial module speaks the protobuf PhoneAPI (PROTO) on UART0. - UART0 uses GPIO21 (TX) and GPIO20 (RX), the chip defaults; they are not verified against the C3 board revision, and no hardware run against a radio is recorded.
- The firmware log goes over USB Serial/JTAG, so UART0 is free; the ROM bootloader still prints on UART0 at reset.
- The routing ACK of every fragment is the delivery proof; interoperability with the robins edge ingress is not verified on hardware. BLE is not implemented.
Altruist Urban (legacy) with altruist-firmware (esp32c3)
| Capability | Board part | Implementation | Integration | Host tests | Simulation | Target build | Hardware | Evidence |
|---|---|---|---|---|---|---|---|---|
| BMP280 / BME280 environment | undocumented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README |
| SDS011 particulate matter | undocumented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README |
| I²S microphone noise level | undocumented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README |
Limitations of BMP280 / BME280 environment:
- Claimed by the altruist-firmware README; ROHI has not built or verified it.
Limitations of SDS011 particulate matter:
- Claimed by the altruist-firmware README; ROHI has not built or verified it.
Limitations of I²S microphone noise level:
- Claimed by the altruist-firmware README; ROHI has not built or verified it.
- Reports the level in dBA, a different metric from the unweighted dB SPL of ROHI; the values must not be compared.
Altruist Insight with ROHI altruist-insight (esp32c6)
Limitations of SCD40 / SCD41 CO2:
- Uses the schematic-backed Insight I²C bus and shared SCD4x driver. No sensor acquisition or error-recovery run on physical Insight hardware is recorded.
- Local ESP32-C6 check/build commands are documented; there is no dedicated Insight CI build yet.
Limitations of BLE control plane:
- Open BLE: no pairing, bonding, encryption or authentication. Nearby centrals can read diagnostics, change exposed settings and invoke system actions.
- Advertising, reconnects and Control actions require physical Insight verification; suitable only for a trusted, supervised MVP environment.
Limitations of Persistent configuration store:
- Only the configuration sections composed by Insight are exposed; flash persistence has not been verified on a board.
Limitations of Persistent logging:
- RAM diagnostics only; no persistent flash log archive or MicroSD. Logs are lost on reboot.
Limitations of System actions:
- System information and actions are exposed over open BLE; reboot and reset behavior require on-device verification.
Limitations of Display:
- ROHI has no display driver.
Altruist Insight with altruist-firmware (esp32c6)
| Capability | Board part | Implementation | Integration | Host tests | Simulation | Target build | Hardware | Evidence |
|---|---|---|---|---|---|---|---|---|
| SCD40 / SCD41 CO2 | documented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README, upstream Insight SCD4x datasheet |
| Display | documented | external | not-applicable | none | none | not-applicable | not-verified | upstream airalab/altruist-firmware README, upstream airalab/hardware: Altruist Insight |
Limitations of SCD40 / SCD41 CO2:
- Claimed by the altruist-firmware README; ROHI has not built or verified it.
Limitations of Display:
- Claimed by the altruist-firmware README (display and QR code); ROHI has not built or verified it.
Use cases
| Use case | Verdict | Summary |
|---|---|---|
| Measure CO2 with Altruist Urban | unsupported | The Urban board carries no SCD4x. The firmware runs the SCD4x driver and would read a sensor wired to the I²C bus, but no wiring is documented upstream and nothing was verified. |
| Measure environmental noise with ROHI | partial | The Urban microphone yields unweighted dB SPL from the nominal ICS-43434 sensitivity. There is no per-device calibration and no A-weighting, so it is not dBA and not comparable to a calibrated sound level meter. |
| Run ROHI on Altruist Insight | partial | The headless altruist-insight firmware integrates SCD41 sensing and open BLE Control without Wi-Fi/IP. Display support is absent, and sensing, BLE advertising and actions are not verified on hardware. |
| Build a water-quality monitor with existing ROHI firmware | unsupported | ROHI has no water-quality sensor driver (pH, turbidity, conductivity, temperature probes), no such board and no firmware. A new device would reuse the SDK services but needs all sensing work. |
Still missing for “Measure CO2 with Altruist Urban”:
- An upstream-documented way to attach an SCD4x to the Urban
- A hardware report with an SCD4x on the Urban
Still missing for “Measure environmental noise with ROHI”:
- A-weighting (dBA)
- Per-device calibration against a reference meter
- Hardware verification on a board
Still missing for “Run ROHI on Altruist Insight”:
- Display driver
- Hardware verification
Still missing for “Build a water-quality monitor with existing ROHI firmware”:
- Sensor drivers
- A board definition and firmware
- Calibration procedures
- Hardware verification
Compatibility
Three different questions are easy to confuse. ROHI keeps them apart.
| Question | Answered by | Needs approval? |
|---|---|---|
| Protocol compatibility: can a ROHI client operate this firmware? | the firmware implements the control protocol | no |
| Publisher provenance: who built and published this firmware? | the publisher’s identity and the firmware’s source | no, it is a fact about the firmware |
| Physical hardware verification: was it shown to work on this board? | a recorded hardware run: support matrix | no, it is evidence |
A firmware that implements the protocol is compatible. Compatible custom firmware does not require central approval:
nobody has to list, sign or accept it for rohi to operate it.
Kinds of firmware
| Kind | Meaning | What to expect |
|---|---|---|
| Developer-verified | built from this repository and verified by the ROHI developers on named hardware | claims in the support matrix with hw-report evidence |
| Community | published by someone else for others to use | compatible by protocol; its support claims are the publisher’s own, listed in the matrix only as external unless ROHI has assessed them |
| Custom | yours, built for yourself | compatible by protocol; nothing is claimed about it |
Today the only developer-verified claims are those in the matrix, and its hardware verification is mostly not recorded yet: absence of a result means not verified, neither working nor broken. There is no certification program.
What compatibility does not mean
- Compatible does not mean verified on your board: check the support matrix.
- Compatible does not mean secure: the control link is not paired or encrypted yet, see Control protocol.
- Compatible does not mean the same revision: the protocol is still under development, so keep client and firmware on one revision.
- Hardware being documented upstream does not mean ROHI supports it. See Reading the support matrix.
Validation
Validation is how a claim gets evidence. ROHI distinguishes the levels and never lets one stand in for another: compilation is not hardware validation.
| Level | How | Where |
|---|---|---|
| Host tests | cargo test, in-memory devices and mocked buses, no hardware | Host testing |
| Target builds | cargo check-esp32c3, cargo check-esp32c6 and the firmware builds in CI | Targets and features |
| Resource budget | measured flash, RAM and stack | Resource budget |
| Hardware | a recorded run on a physical board | Hardware testing |
Validating on hardware
- Build and flash the firmware or an example for your board (Quick start).
- Follow the procedure and checklist of Hardware testing for the capability you are checking.
- Record the result: device and revision, firmware revision, procedure, outcome and logs, in a report you can link.
- Add the result to the support matrix: change
hardware_verificationand attach the report ashw-reportevidence. The validator rejectsverifiedorfailedwithout it.
Sharing results
A hardware report can be a pull request that adds the report and updates the matrix, or an issue with the same content.
A failure is as valuable as a success and is recorded as failed.
Host testing
Most of the SDK is testable without hardware. This page defines the test pyramid, what should normally be proven on the host and the cancellation test pattern.
host unit tests
↓
host service / integration tests
↓
ESP compile checks
↓
hardware functional validation ← Hardware testing
↓
long-running stability tests ← Hardware testing
| Level | Command | What it proves | Hardware needed |
|---|---|---|---|
| Host unit tests | cargo test | codecs, state machines, bounds, error mapping, golden encodings | no |
| Host service / integration | cargo test | owner + handle + mock backend: reconnect logic, reconciliation, dispatcher, framing, rohi client end to end against the real dispatcher, cancellation | no |
std platform end to end | cargo test -p altruist-urban --features std,std-tcp,sensor-simulator | the composed application on the host (sensors, storage, Wi-Fi, TCP control, restarts) driven through the real rohi client; see Run Altruist Urban on std. The BLE peripheral is tested without an adapter; a real adapter and phone are a manual smoke test, not hardware validation | no |
| ESP compile checks | cargo check-esp32c3, cargo check-esp32c6, cargo build-esp32c3/6, ESP clippy | the platform crates and firmware type-check and link for both chips | no |
| Hardware functional validation | flash + examples/firmware | radios, flash, buses, pins, heap high-water mark | yes (Hardware testing) |
| Long-running stability | 24–72 h soak | leaks, deadlocks, recovery under churn | yes |
What should be testable without hardware
Everything in the portable crates, behind its seam trait:
- sensor drivers and their runner (mock buses, recording delay);
- the configuration store, including power-fail safety (injected write and erase faults at every byte);
- the Wi-Fi manager and the IP data plane (scripted backends, no radio, no Internet);
- the time service and the NTP source (fake clock and sources);
- the control protocol, dispatcher, framing and the
rohiclient (in-memory transport); - cancellation of all of the above.
What the host cannot prove: radio and coexistence behaviour, flash timing, DMA, pin maps, real heap use. If a bug is found in one of those, add a host test for the logic part and record the hardware check.
Fakes and mocks
Every hardware seam has a host implementation (in-memory storage, mock radios, a fake IP stack, scripted BLE transports,
mock buses), and the whole composed application runs on the host as the std Altruist Urban; the seams and their fakes are described in the portability rustdoc.
Cancellation tests
For every public async operation with non-trivial cancellation semantics (Async and cancellation) test the hazard by starting the operation, polling it once and dropping it while pending:
start the operation ── poll once (pending) ── drop it ── then verify:
- the service still responds
- channel / slot / pool capacity is not permanently lost
- a stale answer is not delivered to the next caller
- nothing stays locked
- the next operation succeeds
Existing tests cover dropped Wi-Fi scans, configuration changes while connecting, cancelled network operations,
cancelled control requests and dropped sensor steps; find them with cargo test cancel.
Book examples
Rust code shown in the book is either compiled by cargo test and included with {{#include file:anchor}} (for example
crates/net/tests/network_example.rs) or marked ignore/text when it cannot run on the host (hardware snippets).
mdbook test docs runs plain snippets. See Documentation style and policy.
Hardware testing
What the host tests cannot prove — real radios, flash, buses and long-term stability — is validated on devices. The test pyramid and what must be covered without hardware is in Host testing. This page lists the hardware checks, their procedure and their current status. Anything not listed as measured has not been validated on hardware yet. The per-board, per-capability status and evidence is in the support matrix.
Procedure
Build and flash with the per-chip commands in Targets and features; the runner
flashes the chip’s partition table. Examples (one per sensor and a configuration self-test) live in examples/ and print
typed results; the firmware logs a snapshot summary every 30 s.
EXAMPLE="cargo run --release -p rohi-examples --features esp32c3 --target riscv32imc-unknown-none-elf"
$EXAMPLE --bin example-bmx280
$EXAMPLE --bin example-scd4x
$EXAMPLE --bin example-sds011
$EXAMPLE --bin example-noise
$EXAMPLE --bin example-all-sensors
$EXAMPLE --bin example-config # configuration persistence self-test
(ESP32-C6: --features esp32c6 --target riscv32imac-unknown-none-elf.)
Sensors
Combined test checklist: BMx280 keeps updating; SCD4x keeps updating; SDS011 completes its duty cycle and sleeps; noise
windows keep arriving; no sensor starves another. Hot-reconnect check: unplug and replug an I²C sensor and confirm
Error → Initializing → Ready without a reboot; repeat for the SDS011 UART. The ESP32-C6 pin map is not yet verified
on hardware (see Boards).
Configuration store
example-config verifies persistence: every boot checks what the previous boot stored (typed write + reboot + read,
several sections, replacement preserving unrelated sections, repeated write cycles) and logs SELFTEST PASS or
SELFTEST FAIL. On the third boot it corrupts the newest slot on purpose and checks that the store reports Recovered
and falls back to the previous generation.
Persistent logging
Not validated on hardware. The log ring is host-tested on an emulated NOR flash (4-byte write words, a word programmed at
most twice, power-loss injected at every write) and on a RAM medium with power loss injected at every write and every
sector erase of a format and of a clear. The log lives in the rohi-log partition (128 KiB at 0x20000, right after rohi-cfg, on ESP32-C3;
1 MiB at 0x700000, the last partition, on ESP32-C6), see the firmware README. Checklist for a device
(record the results here; the issue is #67):
- Flash and first boot (ESP32-C3):
cargo flash-esp32c3from a device that ran an earlier layout, so that the partition table and the firmware are rewritten (the ESP32-C3 app moved from0x20000to0x40000). Read the partition table back (espflash read-flash 0x8000 0xC00 pt.binandespflash partition-table pt.bin) and confirmrohi-logat0x20000(0x20000bytes, 128 KiB) andfactoryat0x40000(0x3C0000bytes) on ESP32-C3;factoryat0x20000androhi-logat0x700000(0x100000bytes) on ESP32-C6. The console showsNo valid format header, the region was formatted(targetlogging) once and no panic; measure the time from boot toRunningofrohi status logging, and watch Wi-Fi, BLE and the sensors meanwhile. Reset: no second format message, the earlier records and thehistorynumber are still there. Record whether boot records were dropped (dropped_records). rohi logsshows boot records; reboot (rohi system reboot) and confirm the earlier records are still there and the sequence continues.- Pull power while
rohi config logging level=debugis active and the device logs heavily; after power-uprohi logsshows a contiguous history,rohi status logginghas nostorage_corruptissue or only the one for the cut segment. Repeat with the power cut during the first format (erase a fresh board withespflash erase-flashfirst, then flash and cut power a few seconds after boot) and duringrohi logs clear: the next start must finish the work and no old record may come back. rohi logs download -d DIRwhile Wi-Fi is connected: all files are readable text (lz4 -dfirst on a firmware built withlz4), and record the time it takes over BLE (8 KiB segments on ESP32-C3, 64 KiB on ESP32-C6).- Watch Wi-Fi, BLE and the microphone (noise windows keep arriving) while the log fills its budget (128 KiB on ESP32-C3, 1 MiB on ESP32-C6) and the oldest segments are erased: measure how long a flush stalls the CPU.
- Fill beyond the retention, confirm
dropped_recordsstays 0 at the defaultwarnlevel in normal operation. rohi logs clear --yeswith a full log: record how long it takes (it must stay below the 40 s action timeout of the client, also over BLE), that Wi-Fi/BLE/sensors keep running meanwhile, that the status shows an empty log and a newhistory, and that logging continues after a reset.- Download and clear: start
rohi logs downloadand, from a second client while it runs,rohi logs clear --yes: the clear must be answeredBusy, the download must finish with every file decodable androhi status loggingmust show the samehistoryandstored_recordsas before. Clear again after the download ended, and after a download was abandoned (killrohimid-download, wait 60 s): both must succeed. - Tail and follow (both chips):
rohi logsandrohi logs -fover BLE and over Wi-Fi/TCP. A page is at most 512 bytes of whole lines, so check thatrohi logsshows every record the RAM holds (8 on ESP32-C3, 7 on ESP32-C6) in order, once. Withrohi config logging level=debugletrohi logs -frun for several minutes on an idle device: no line about the control plane, BLE or the tail itself may appear (polling must not generate records), and a burst of records (a Wi-Fi scan) must show up once each, or asN log record(s) were overwrittenwhen more arrive between two polls. - Session across reboots: with
rohi logs -frunning,rohi system reboot: the client must sayThe device restartedand show the new boot from its first record. Repeat with the configuration storage unable to keep the boot counter (a full or erasedrohi-cfgregion: erase it withespflashand keep reboot-looping):boot_countmay repeat but the client must still notice every restart. - Retained panic records (both chips): provoke a panic (the
crash-injectfeature), reboot and confirm thatrohi logs downloadhas the panic record of the previous run before the records of the new one, once, and thatrohi logsof the new boot starts at sequence 1.
Wi-Fi and IP
Not yet measured on hardware: scan, connect/DHCP, reconnect after reboot, wrong password, access point loss,
configuration change while connecting/backing off/connected, DNS and TCP through NetworkHandle (no component uses it
yet), BLE + Wi-Fi coexistence, minimum free wireless heap (idle, scanning, connected), 24 h stability. Record results
here together with the final WIRELESS_HEAP_SIZE.
Device identity
The hardware checklist (provision, reboot, erase, re-provision) is in the rohi-identity rustdoc (see also Device identity); its results are not yet recorded.
Meshtastic radio over UART
No hardware run is recorded. Run on both ESP32-C3 and ESP32-C6 with a Meshtastic radio whose Serial module is in
PROTO mode (build with --features meshtastic-uart, see Meshtastic radio over UART):
- Boot; the radio answers and
rohi status meshtasticshows itsnode_idandfirmware_version. rohi action meshtastic send to=<second node> text=...; the second node receives the text.rohi action meshtastic inboxshows the routing ACK, and an incoming text after the second node replies.- Restart the radio; the session recovers by itself (
reconnectsgrows, health returns took). rohi action meshtastic reconnectresynchronizes without rebooting the ESP32.- Unplug the radio; sensors, Wi-Fi and the control plane keep working,
rohi status meshtasticreports the issue. - Plug it back; normal operation resumes.
- Telemetry: a route with
meshtastic+uart://!<gateway>and an HTTP fallback delivers one SINGLE and one FRAGMENT packet to arobins edgegateway and receives the routing ACK of every fragment. - Pins: confirm the C3 GPIO21/GPIO20 and the C6 GPIO22/GPIO20 directions and that the log reaches USB Serial/JTAG.
BLE control
First hardware data point (96 KiB heap, Wi-Fi + BLE running, chip not recorded): 14 656 B free, 11 120 B minimum free, i.e. about 87 KB peak use, too little margin, hence 128 KiB. Re-measure the minimum free with the larger heap during BLE connected + Wi-Fi scan/reconnect.
Not yet measured: BLE advertising with Wi-Fi disconnected and connected, BLE connected with Wi-Fi connected / scanning / reconnecting, minimum free wireless heap for each, MTU negotiation, and a 24 h (preferably 72 h) stability run exercising BLE connect/disconnect, sensor reads, config reads and updates, Wi-Fi status, scan and reconnect. Expected outcome: no panic, no allocator exhaustion, no deadlock, no permanent BLE or Wi-Fi failure.
Control plane stack
The stack high-water mark of the control path (rohi status with Wi-Fi and identity configured and all services active,
config and action requests, factory reset) is not yet measured. The procedure, the scenarios and the table for the
results are in Resource budget.
Static evidence (task pools, main-stack allocation, function frames) comes from scripts/memcheck.sh and is not a
measurement of stack use. A measured peak is attached to its report as a hardware observation, see
Task memory and stack budget.
Sensor stability test
Run altruist-urban without networking for at least 24 h (preferably 72 h) with all sensors attached and record the
following. The table is filled in after each hardware run:
| Item | Result |
|---|---|
| Duration | |
| Unexpected reboots / panics | |
| Sensor errors per sensor | |
| Successful recoveries | |
dropped events (log) | |
| Task stalls (snapshots stop updating) | |
| Stale measurements | |
| Memory stability |
Control worker stack high-water
scripts/memcheck.sh reports static frames, not the stack depth that a request reaches. Measure it on the device before
any claim about the shared control_task: fill the main stack with a pattern at boot, run each of the paths below over BLE
(BLE control is open and unencrypted in this build), then read how much of the pattern is overwritten.
- Config read and patch, Status of every service,
rohi status logging; - an expensive action (
rohi connectivity get_payload 0), a stream (rohi logs download) and its close; rohi action wireless wifi_reconnect;- one request while a second central is refused (
Busy) and a disconnect during a running action.
Record the result and the margin in the support matrix before the resource budget is lowered. Also connect a phone or a Linux adapter to the open BLE endpoint and record that Config, Status and Actions work without pairing: that path is implemented but not verified on a device. After removing the pairing code of the host stack (#83), also check advertising, connection, writes, notifications, disconnect and reconnect of an image built without it.
Resource budget (measurements)
Measured sizes of the firmware and the libraries, per hardware or build run. The limits themselves (queue depths, buffer sizes, heap size) are defined and explained in Resource limits; this page only records what was measured with them. Numbers here are history, not contracts: they change with every dependency update and are re-measured when the limits change.
The before/after report of the compact firmware change (optional LZ4, a 128 KiB log on the ESP32-C3, compile-time route and telemetry capacities, a smaller signed packet, TCP-only encryption) is Compact firmware report; its numbers replace the older ones of this page where they differ.
Altruist Urban firmware (Wi-Fi + BLE control)
Measured with size on the release build (cargo build-esp32c3 / cargo build-esp32c6), baseline = Wi-Fi only,
before the BLE control plane was added:
| ESP32-C3 before | ESP32-C3 after | ESP32-C6 before | ESP32-C6 after | |
|---|---|---|---|---|
.text (flash) | 970 092 | 1 149 952 | 1 012 322 | 1 335 452 |
.data | 10 024 | 15 640 | 12 876 | 18 396 |
.bss | 106 984 | 181 248 | 111 288 | 185 056 |
wireless heap (in .bss) | 73 728 | 131 072 | 73 728 | 131 072 |
.bss without heap | 33 256 | 50 176 | 37 560 | 53 984 |
Statically allocated control buffers: reassembly 256 B + response 2 048 B + chunk 244 B (control task), BLE RX/TX queues 4 × ~250 B each, TrouBLE host resources, and the task futures. The application code stays heapless; only the radio drivers use the wireless heap.
Sensor runtime (rohi-sensors, rohi-hal)
cargo build-esp32c3, ESP32-C3 (before Wi-Fi/BLE/TLS):
| Item | Size |
|---|---|
.text (flash) | 114 370 B |
.rodata (flash) | 24 096 B |
.rwtext + .data (RAM) | 1 700 B + 2 132 B |
.bss (RAM, includes task futures) | 9 160 B |
| Heap | fixed radio heap only (see Memory model); application code does not allocate |
| Event queue | 16 events |
| Noise buffers | 256 samples (1 KiB) stack + 8 KiB DMA ring |
Task stack usage is not measured yet.
Stack and the control plane
All embassy tasks are polled on the one main stack, which on the ESP32-C3 build of altruist-urban is the linker .stack
section: 22 024 B on the firmware-profile build at ca17cb6 (121 848 B on ESP32-C6; an earlier revision of this page recorded about 42 KB, and the stack is what the linker leaves after the statics, so it shrinks when they grow) and it sits directly above .bss, so an
overflow corrupts task state (observed as a Load access fault in the embassy timer queue with the ASCII of a service
name in the registers). The control task builds and moves protobuf responses on that stack, so response sizes are
bounded by the compact protocol layout and by explicit budgets, see Control protocol types.
The static future of control_task is 17 440 B of .bss (firmware profile, ESP32-C3, from the size of altruist_urban::esp::control::control_task::POOL; the earlier 11 856 B were a release build of an older revision). Task memory and stack budget reports every task pool, the stack and the frames in CI. Stack depth under load is not measured yet: it needs a
device, see the plan to measure it. The stack is what the linker leaves after .bss, so every
static byte and every deep frame on the config or control path costs stack: a decoder that builds a large section from
temporaries (the former wifi section, about 200 B) needed ~900 B of frame and overflowed the stack on a rohi config request;
WifiConfig was decoded in place for that reason; WirelessConfig is the one section now, so its frames are checked by memcheck. Check _stack_end and the frames of the config and control path
when a section or a static grows.
Control protocol types
The generated types of the control protocol keep every bounded field inline, so their size is the size of their largest
possible content. generated_types_stay_within_their_memory_budgets (rohi-control-proto, runs in CI) asserts a budget
for each; the sizes are size_of on the host (64-bit), before and after the compact layout of the protocol (numeric
ids and enum values, f32, compact FieldDescriptor, enums and issue names in the schema, no descriptions, no
summary in the detailed status, no pagination):
| Type | Before | After | Budget |
|---|---|---|---|
Request | 760 | 736 | 768 |
Response | 2 616 | 1 824 | 1 900 |
FieldDescriptor | 352 | 48 | 56 |
FieldValue | 88 | 56 | 64 |
GetServicesStatusResponse | 792 | 1 048 (16 services; 792 for 12) | 1 088 |
GetServiceStatusResponse | 1 272 (8 values) | 1 192 (20 values) | 1 280 |
GetConfigSectionResponse | n/a | 1 504 | 1 536 |
PatchConfigSectionRequest | n/a | 728 | 768 |
The Response is the largest of its variants (the service schema). The before column paged status values by eight, schemas by
four; the after column holds a whole service status (20 values), a whole schema (20 fields, an enum table, 12 issue
names) and 12 actions in one response. GetConfigSectionResponse carries the effective values plus the compact list of overridden field ids (overridden), and PatchConfigSectionRequest its set / clear mutations; both are new rows, measured after the overrides model. Raising a budget is a deliberate decision: measure the control task again and
update this table.
Measuring the control task
The stack high-water mark of the control path has to be measured on a device, so that a future change has a concrete
baseline to be compared with. Not measured yet: the table below is the record to fill in. What is known without a
measurement: rohi status completes with Wi-Fi configured, an identity provisioned and all services active (reported
on the pull request that introduced the generic services); the previous stack overflow is not reproducible. How much
headroom remains is not known.
Procedure. Build the release profile of altruist-urban for the target (cargo build --release -p altruist-urban --no-default-features --features esp32c3 --target riscv32imc-unknown-none-elf, esp32c6 with
riscv32imac-unknown-none-elf) and read the stack size from the ELF (_stack_start - _stack_end, e.g. with
riscv32-esp-elf-nm or rust-nm). Paint the stack with a known pattern at boot (fill the region between _stack_end
and the current stack pointer, keeping a guard word at the bottom), run one scenario at a time from the table, then read
the stack with a debugger or dump it from a debug-only command and find the lowest address whose pattern changed. Use
the same firmware build for every row and reboot between scenarios. Maximum usage is _stack_start - lowest touched address; headroom is the stack size minus that.
Scenarios, each with the device in the stated state (all services active, i.e. the Wi-Fi and BLE services running):
- unconfigured device (no Wi-Fi, no identity)
- Wi-Fi configured
- identity provisioned
- Wi-Fi and identity both configured:
rohi status(the regression scenario) androhi status <service>for every service rohi config <section>androhi config <section> FIELD=VALUEof every section- Wi-Fi scan and
wireless wifi_reconnectaction invocation - identity
provisionanderaseaction invocation rohi system factory_resetrohi system reboot
Record per target:
| Field | ESP32-C3 | ESP32-C6 |
|---|---|---|
| Hardware (board, chip revision) | ||
| Firmware build (commit, profile) | ||
| Stack size (bytes) | ||
Static control_task future (bytes, nm -S) |
| Scenario | ESP32-C3 max usage / headroom | ESP32-C6 max usage / headroom |
|---|---|---|
| 1. unconfigured | ||
| 2. Wi-Fi configured | ||
| 3. identity provisioned | ||
4. rohi status, Wi-Fi + identity | ||
4. rohi status <service>, worst service | ||
5. config <section> read / FIELD=VALUE patch, worst section | ||
| 6. Wi-Fi scan / connect | ||
| 7. identity provision / erase | ||
| 8. factory reset | ||
| 9. reboot request |
Safety margin (proposed). Until measured, no margin is claimed. When the table is filled in, state the lowest headroom of any row and keep at least 25 % of the stack (or 4 KB, whichever is larger) free in the worst row; a change that cuts into it needs another measurement. The generated-type budgets in Control protocol types stay in CI independently of this measurement.
Task memory and stack budget (memcheck)
scripts/memcheck.sh builds the Altruist Urban firmware for a chip twice (the production image and an analysis image
with -Z emit-stack-sizes, same compiler and flags otherwise) and runs memcheck (tools/memcheck) on them. CI does
this for ESP32-C3 and ESP32-C6 (job Memcheck), publishes task-memory-esp32c3.json, task-memory-esp32c6.json and
task-memory-report.md (complete) and task-memory-summary.md (only what needs attention), and compares a pull request
with its base branch built from identical inputs. The pull request comment is the summary: one row of numbers per chip, then
failed or close-to-limit (90 %) budgets, errors and warnings, new, removed and grown tasks, changed sections and frame
growth, each list cut after eight entries. The complete report is the job summary of the run and the task-memory-report
artifact; the comment links to it.
scripts/memcheck.sh images esp32c3 out && scripts/memcheck.sh analyze esp32c3 out # one chip
scripts/memcheck.sh report out # task-memory-report.md and task-memory-summary.md
What each number is, and what it is not:
| Quantity | Source | Meaning |
|---|---|---|
| Task pool bytes | size of the task’s POOL static in the production ELF | RAM reserved for all instances of the task. A static value, exact. The number of instances is not in the symbol table and is reported as unknown |
| Main stack | linker symbols _stack_start / _stack_end | the stack all Embassy tasks are polled on. Allocation, not use |
| Frame | LLVM .stack_sizes of the analysis image | the stack of one function. It is not the stack depth of a task: call chains, inlining, dynamic dispatch, async suspension and interrupts are not analyzed. Functions without metadata (assembly, ROM and vendor blobs) have an unknown frame |
| Peak use, headroom | hardware observation only | not measured until a device run is attached; never inferred from the above |
| Native RTOS threads, interrupt contexts | not in the image | not_detectable_statically / runtime_only; a list of ELF symbols is not a list of run-time threads |
The budgets (firmwares/altruist-urban/memcheck-budgets.toml) are per chip: .data, .bss, the sum of the task pools,
a minimum for the main stack and a maximum single frame, plus the largest allowed growth against the base. A run fails
when a budget is exceeded, when the main stack is below its minimum, when the task inventory or the .stack_sizes
metadata is missing (an approved exception in the budget file is the only way around that), or when the base was built
with different inputs. Growth that stays below the limits is listed but allowed. The main stack is what the linker leaves
after the statics, so every static byte removed from .bss or .data is stack gained; a regression of the stack is a
budget failure.
Baseline (master at ca17cb6, ESP32-C3 firmware profile and ESP32-C6 release profile, Rust 1.99.1; all values
from the ELF, nothing measured on a device):
| ESP32-C3 | ESP32-C6 | |
|---|---|---|
.data (with .data.wifi) | 29 792 | 33 084 |
.bss (includes the 131 072 B wireless heap and the task pools) | 204 824 | 208 928 |
| Task pools, 15 tasks | 40 360 | 40 336 |
control_task pool | 17 440 | 17 440 |
ble_task pool | 7 064 | 7 040 |
connectivity_task pool | 3 624 | 3 624 |
logging_task pool | 2 304 | 2 304 |
Main stack (.stack, placed directly above .bss) | 22 024 | 121 848 |
Largest frame, Controller request handling | 30 112 | 29 104 |
Frame of Logging read path (removed with logging.read, #70) | 8 400 | 4 432 |
| Frames with metadata | 1 520 of 3 827 (39.7 %) | 1 947 of 5 383 (36.1 %) |
The largest frame on both chips, the generic Controller request path, is larger than the whole ESP32-C3 main stack.
The analyzer reports this as a frame-exceeds-stack warning: a frame is not a peak, but a function with that frame
cannot run on a 22 KB stack, and it is the first candidate for a device investigation and for issue #63.
Hardware observations. To attach a measured stack peak, write a JSON file and pass it with --hardware
(scripts/memcheck.sh analyze <chip> <out> --hardware observations.json):
{"observations": [{
"chip": "esp32c3", "stack": "rtos/main", "scenario": "rohi status logging",
"firmware_sha": "<commit of the flashed image>", "peak_used_bytes": 18200,
"guard_state": "enabled", "notes": "board, revision, how the stack was painted"
}]}
Omit peak_used_bytes for a scenario that was not measured (not measured is not 0). The report computes
headroom = allocated - peak and requires at least 25 % of the stack or 4 KiB, whichever is larger, unless the
observation sets a justified required_margin_bytes. Embassy tasks share the main stack, so there is no per-task stack
to measure; per-task attribution would need executor-aware instrumentation. The scenarios to record are the ones in
Measuring the control task plus rohi status logging, rohi logs clear --yes, a log
flush with compression and BLE traffic. Without an observation the outcome is NEEDS HARDWARE DATA, never PASS. An observation whose firmware_sha differs from the analyzed image (--git-sha) is ignored with a hardware-sha-mismatch warning, so it cannot turn the outcome into PASS.
Stack pressure of logging and the Control API (#63)
Measured with memcheck on the same toolchain, profile and flags, against master at ca17cb6 (ESP32-C3 firmware
profile, ESP32-C6 release profile). Frames are the stack of one function: they show where a large frame went, not the
depth of any call chain. “At most N B” means the function left the 50 largest frames of the report, so N is the smallest
frame that remained in it (an upper bound, not a measurement). Nothing here was measured on a device.
| Change | Function | ESP32-C3 before → after | ESP32-C6 before → after |
|---|---|---|---|
Streams are removed in place and only their segment ids are kept (Logging::release_streams, close_stream) | Logging::release_streams | 8 400 → at most 1 728 | 4 432 → at most 1 808 |
lock closure around release_streams | n/a | 6 304 → at most 1 808 | |
ActionRegistry::close_stream | 2 352 → at most 1 728 | 2 352 → at most 1 808 | |
Every backend call is polled through rohi_service::Isolated; every request has its own function in Controller | Controller::execute poll | 30 112 → at most 1 728 | 29 104 → at most 1 808 |
control_task poll (inlines the request path; approved growth in the budget file) | 7 072 → 8 608 | 6 128 → 9 248 | |
| largest frame of the image | 30 112 → 12 240 (async main future, unchanged) | 29 104 → 9 248 (control_task poll) | |
| Static RAM | .data, .bss, task pools, main stack | 0, −8, −8, +8 B | −32, 0, −8, +32 B |
What changed and why it works:
release_streamscollected the released streams by value into a secondVec<Open<READ>, 2>(two stream payloads ofREAD= 2 048 B plus bookkeeping; thereadaction and its buffers no longer exist, see below). Streams are now removed in place withretain_mutand only the ids of the segments they pinned (at most 2 × 24u32) are kept, then unpinned outside the stream table.close_streamtakes the storage lock first and removes and unpins in one step, so a caller that gives up while waiting leaves the stream to expire with its pins instead of leaking them (before, the stream was removed first and the pins were released after the await). Regression tests:clear_releases_one_and_two_open_streams,two_downloads_release_their_shared_segments_independently,an_expired_stream_is_released_while_the_other_keeps_its_pins,a_lost_link_releases_every_stream_at_once,closing_streams_in_any_order_leaves_the_other_one_intact,closing_a_stream_twice_is_an_error_and_releases_nothing_more,repeated_clear_and_logging_after_it_keeps_working; each also checks the segments the storage still holds pinned.- The 30 KB frame was not the response types: it was the poll of every config section, status and action of the device
inlined into
Controller::execute, each with its own copies of its bounded collections (SectionValues,ServiceStatus,Records, a few KiB each), which LLVM does not overlap.rohi_service::Isolatedpolls a future through a function that is never inlined, so only the call that runs has a frame. The registries ofrohi-servicepoll each section, status and action through it, andControllerdoes the same for each request. Wrapping onlyControllerleft a 19–22 KB frame in the status registry; wrapping the registries brought it below 1.8 KB. - A first attempt, writing every response into one caller-provided slot, made the frame larger and the task future 1.5 KB
larger (the slot lives across
awaits) and was dropped: the response types were not the cause.
Not done, with the reason:
| Item | Status |
|---|---|
Status serialized without the Collector and the protobuf Vec at once; zero-result actions without a RecordCollector | not implemented: after the change above the frames of these paths are below the 1.8 KB reporting floor, and the control_task future (17 432 B) did not move; a smaller future needs the state of the largest await, which this analysis does not attribute |
RingStorage::scan_open (2 056 B chunk + 2 048 B text) | not implemented: the recover poll frame (6 608 B on C3) is not on the control path; shrinking it needs a streaming LZ4 decoder, which changes recovery logic and needs a flash-damage test matrix |
Logging::collect() / SegmentDecoder staging buffers | not implemented: a staging state machine needs a measured benefit, and the collect closure frame was 2 160 B on both chips, is at most 1 728 B on ESP32-C3 after this change (side effect of inlining) and unchanged on ESP32-C6 |
LZ4 HASH_BITS 10 → 9 → 8 | not benchmarked: needs representative firmware logs (compression ratio, flash writes, segment rotation), which the repository does not contain |
Outstanding hardware verification: the control path (rohi status, status logging, logs, logs download,
logs clear --yes) on ESP32-C3 and ESP32-C6, with a main-stack high-water mark attached as a hardware observation; the
static result does not show that the exception seen on the device is fixed.
Configuration store
The store uses no heap; see Resource limits for its bounds. Its RAM cost is a few words of state plus the stack workspace during a call.
IP stack, TCP and UDP pools
Not measured: no SDK component opens TCP connections yet, and the UDP pool (one socket, 2 x 128 B plus packet metadata)
used by the NTP time source has not been measured on hardware either; the ntp_task stack and the time service state
are small and also not measured. Measure the .bss contribution of NetResources and the
minimum free wireless heap with an open connection when the first uplink component lands, and record it here.
How to measure
cargo build-esp32c3 && size target/riscv32imc-unknown-none-elf/firmware/altruist-urban-firmware
cargo build-esp32c6 && size target/riscv32imac-unknown-none-elf/release/altruist-urban-firmware
scripts/memcheck.sh images esp32c3 out && scripts/memcheck.sh analyze esp32c3 out # task pools, stack, frames
The minimum free wireless heap comes from rohi_net_esp::wireless_heap() (the firmware logs it with its snapshot; the
heap-stats feature adds the minimum).
Persistent logging (rohi-logging)
Release build of altruist-urban, measured with nm -S on the ELF (cargo build-esp32c3 / cargo build-esp32c6):
| Item | ESP32-C3 | ESP32-C6 |
|---|---|---|
altruist_urban::esp::logging::LOGGING (queue, batch, RAM tail, download streams, status; initialized data in RAM) | 10 544 B | 10 352 B |
altruist_urban::esp::logging::logging_task future (.bss) | 2 304 B | 2 304 B |
The limits are in firmwares/altruist-urban/src/logging.rs (QUEUE_DEPTH 24 records, TAIL_RECORDS 8 on the ESP32-C3 and
7 on the ESP32-C6, about 200 B each; at most two download streams, and none for the tail) and in rohi_logging (batch of 1 KiB of text; with the lz4 feature one compressed block of at most 1 032 B).
Flash. ESP32-C3 (4 MB): rohi-log is 128 KiB (0x20000) at 0x20000, right after the configuration region; 32 sectors of 4 KiB,
30 for the ring and the last two for the format header; with 8 KiB segments it retains 15 full segments (120 KiB; 98 to 116 KiB of text
lines on an emulated medium, 80 to 160 B lines, see the_esp32c3_log_retention_is_measured). The factory partition follows at 0x40000 and is
0x3C0000 B (it ends the flash). ESP32-C6 (8 MB): factory is 0x6E0000 B at 0x20000 and rohi-log is the last partition, 1 MiB at 0x700000,
256 sectors, 254 for the ring. On both chips the app area starts and ends on a 64 KiB boundary, for future A/B OTA slots (#29; not implemented). scripts/image-fits.sh <chip> (CI job Firmware) runs espflash save-image, which
refuses an image that does not fit: the ESP32-C3 firmware-profile image was 1 361 472 B of the former 3 538 944 B (0x360000) factory partition (38.5 %;
the partition is now 0x3C0000, 3 932 160 B), the ESP32-C6 release image 1 845 552 B of 7 208 960 B (25.6 %); the C3 partition holds the image
with 2.1 MB to spare.
RAM does not scale with the flash. The default retention is 128 KiB in 8 KiB segments on the ESP32-C3 and 1 MiB in 64 KiB segments on the ESP32-C6 (at most 24 segments are kept), and
nothing is allocated per sector or per segment byte: a format or a clear erases one 4 KiB sector at a time and yields
between two erases (no flash lock is held across the region), the recovery reads through 20 B to 128 B buffers, a sealed
segment is checked with a streaming CRC-32 and the metadata is at most 24 segments. Static analysis of this change against
master at 72caa63 (scripts/memcheck.sh, same toolchain and flags, nothing measured on a device):
| ESP32-C3 | ESP32-C6 | |
|---|---|---|
.data | +16 B (29 840 B) | +24 B (33 108 B) |
.bss | 0 (204 824 B) | +8 B (208 936 B) |
Task pools (logging_task 2 304 B) | unchanged (40 352 B) | unchanged (40 328 B) |
| Main stack | −16 B (21 976 B) | −32 B (121 816 B) |
| Largest frame | unchanged (12 240 B) | unchanged (9 232 B) |
Logging frames (Logging::step, invoke_of<LoggingService>, observe) | +16 B each | +16 B to +32 B |
The growth of LOGGING (+8 B) is the index of the active format header slot that the ring keeps. The log lines for a failed open, recover or clear
are out of line (#[cold]): inlined into the config publication they enlarged the EspWifi::new frame by 832 B in a
trial build. The new Recovery::formatted flag and the format loop add no buffer.
TailLogs instead of logging.read (#70; the request itself became the logging.tail action in #78, see below). read decoded archive segments into a 2 048 B buffer held in each open
stream slot and polled the decoder and its scratch inside the control_task future. The tail only copies records of a RAM ring
out one at a time, formats at most 512 B of whole lines and writes them straight into the data field of the reply: there is
no stream (no table, no id, no timeout, nothing to close and nothing that can be overwritten between selecting a window and
reading it), no buffer besides the reply that is built anyway, no SegmentDecoder, no flash read and no LZ4 on its path. The
reply has the capacity of a stream chunk, so the largest response, and with it the stack of the control_task, does not grow:
Controller::tail_logs is a function of its own (#[inline(never)]), the page is written into the Vec of the reply, and
a record copied out of the ring (about 200 B) is the only temporary. Static analysis of this change (scripts/memcheck.sh images|analyze, same toolchain and flags; nothing was measured on a device), where “before” is the stream-based
logging.tail of the commit before:
| ESP32-C3 before → after | ESP32-C6 before → after | |
|---|---|---|
.data (limit 30 000 / 33 500) | 29 992 → 29 944 B | 33 492 → 33 380 B |
.bss | 186 088 → 186 088 B | 190 200 → 190 200 B |
| Task pools | 37 992 → 37 992 B | 37 968 → 37 968 B |
control_task pool | 14 752 → 14 752 B | 14 752 → 14 752 B |
LOGGING | 10 616 → 10 544 B | 10 424 → 10 352 B |
| Main stack | 40 560 → 40 608 B | 140 168 → 140 280 B |
| Largest frame | 12 256 → 12 256 B | 8 560 → 9 232 B |
The tail table of LOGGING (two TailOpen slots) is gone, so .data shrinks by 72 B on each chip. All budgets of
memcheck-budgets.toml hold with the same limits (NEEDS HARDWARE DATA: the static evidence is within them and no stack peak is
measured); none was raised. The largest frame of the ESP32-C6 is the control_task poll, as before; compare it with the base
branch in CI (--base) rather than with the figure of an older commit.
logging.tail as a regular action (#78). The dedicated TailLogs request is gone: the tail is the read-only action
logging.tail whose result is a cursor page, a third result kind next to records and streams. The service renders the page into a
512 B buffer in a frame of its own (#[inline(never)], not part of the future of invoke, which awaits the archive), hands it to the
action output, and Controller::page_reply (also #[inline(never)]) copies it into the response. A page is thus held twice for a
moment, and ActionResult::Page (512 B of data) lives in the future of Controller::invoke. Static analysis, same toolchain and flags as
above, “before” being the commit before this change (nothing was measured on a device):
| ESP32-C3 before → after | ESP32-C6 before → after | |
|---|---|---|
.data (limit 30 100 / 33 900) | 29 992 → 30 000 B | 33 612 → 33 636 B |
.bss (limit 194 000 / 198 100) | 192 496 → 193 056 B | 196 600 → 197 160 B |
| Task pools (limit 41 200) | 40 048 → 40 608 B | 40 024 → 40 584 B |
control_task pool | 13 120 → 13 680 B | 13 120 → 13 680 B |
| Largest frame (limit 12 300 / 8 500) | 12 256 → 12 256 B | 8 400 → 8 400 B |
| Main stack (declared minimum 32 600 / 131 900) | 34 744 → 34 176 B | 134 264 → 133 680 B |
The 560 B growth of the control_task pool is the page the future of invoke now holds; the frames of invoking the logging service
and of the controller did not grow. All budgets of memcheck-budgets.toml hold with their limits unchanged
(NEEDS HARDWARE DATA, as before). Polling the tail is reported at trace by the controller and the registry, so that following does not
feed the tail it reads.
The RAM tail is TAIL_RECORDS × 200 B inside LOGGING (1 600 B on the ESP32-C3, 1 400 B on the ESP32-C6); the 4 096 B of
READ buffers of two streams are gone, and a download slot no longer has the size of a record buffer. .data fits the
budgets by 56 B (ESP32-C3) and 120 B (ESP32-C6): the whole LOGGING static is initialized data (it holds a pointer to the clock and the initial
configuration), so one more record (200 B) would exceed the budget of both chips, which is why the ESP32-C6 keeps 7. The budgets were not raised. After the merge with the telemetry and connectivity rewrite (#58, #59, #66) .data measured 30 400 B (ESP32-C3) and 33 740 B (ESP32-C6), so max_data was raised to 30 500 and 33 800 B; the other budgets hold.
What is left of the invoke_of<LoggingService> poll is mostly download (the pinned file table and the stream
description). Not measured: the stack high-water mark of the main task during repeated rohi logs, which needs a device.
Not measured: the share of .text the logging code adds, stack depth of the logging task while it compresses (the
LZ4 compressor keeps a 2 KiB table and the writer a 2 KiB chunk on the stack), the CPU time of a flush, how long a
flash sector erase stalls Wi-Fi, BLE and the microphone DMA ring, how long the first format of the 128 (ESP32-C3) or 256 (ESP32-C6) sectors takes, how long
rohi logs clear takes (it has to stay below the 40 s action timeout of the client) and how long recovery spends on the checksums
of up to 1 MiB of sealed segments at boot (the CRC-32 is computed bit by bit). These need a device.
Shared control worker and BLE frontend (#56)
BLE and TCP no longer call the Controller in their own poll chain. One control_task owns the Controller; the BLE
frontend is its own control_ble_task and the request and response buffers are the slot of the ControlHub (one slot on
the ESP, two on the host). Measured with scripts/memcheck.sh (static analysis, not a runtime high-water mark):
| Metric | Before (reference CI run, PR #69) | After, ESP32-C3 | After, ESP32-C6 |
|---|---|---|---|
control_task::POOL | 17 512 B | 15 128 B | not recorded |
control_ble_task::POOL | n/a | 2 784 B | not recorded |
ControlHub slot (.bss) | n/a (buffers in the pool) | 3 272 B | not recorded |
control_task poll frame | 9 504 B | 9 456 B | not recorded |
control_ble_task poll frame | n/a | 640 B | not recorded |
| all task pools | 43 040 B | 45 008 B | 44 984 B |
.data | 30 400 B | 31 144 B | 34 956 B |
The tasks share the one executor stack, so splitting them lowers the depth only because the transport and controller
poll chains no longer nest. The new .data and task RAM come from the second task, the new sections and services and
the host stack (trouble-host); the .data of the hub itself is kept at zero (it holds no reference
until bind), so it lands in .bss. No saving of stack or RAM is claimed: the stack high-water mark was not
measured on hardware, see Hardware testing. The budgets of
memcheck-budgets.toml were raised by 700 B (.data, ESP32-C3), 1 200 B (.data, ESP32-C6) and 1 700 B (task RAM).
Action result formats
An action returns one of five result formats (Empty, Inline, Records, Feed, Stream), the records of a long
Records result are read page by page from a snapshot the service holds, and the control protocol is version 2 (see
Action result formats). Measured with scripts/memcheck.sh against the commit before the
change (101cc16), same toolchain and features; not measured on hardware.
| Item | Before | After |
|---|---|---|
size_of::<Response>() (host) | 2 184 B | 2 200 B (budget 2 200 B; the page token) |
RecordsPage worst case, encoded | n/a | fits MAX_RESPONSE_LEN with the envelope (test the_worst_records_page_fits_the_response_limit) |
ESP32-C3 .bss | 192 976 B | 191 880 B |
ESP32-C3 .data | 29 952 B | 29 976 B |
| ESP32-C3 task pools | 40 544 B | 38 768 B |
| ESP32-C3 largest frame | 12 256 B | 12 256 B |
ESP32-C6 .bss / .data / task pools | not measured on the base | 195 992 B / 33 660 B / 38 744 B |
| ESP32-C6 largest frame | not measured on the base | 9 632 B (Controller::read_result_page) |
The held scan of wireless is one WifiScanResults (up to 16 networks) in the service, in .bss. The control task shrank
because the first page of a result is built without a second copy of the records and because a stream or a snapshot that
is closed after the reply (an eviction, a result that fitted its first page) is queued and closed once the reply is encoded,
so the reply is not kept across that wait. The poll frames of registry::invoke_of grew by 0.5 to 1.5 KB (approved in
memcheck-budgets.toml) and the ESP32-C6 frame limit went from 8 500 B to 9 700 B for read_result_page. The stack
high-water mark was not measured on hardware, and neither were the BLE round trips of a three-page scan (the number of
pages follows from 16 networks, 6 records per page); both need hardware data.
Altruist Insight memory report
The report measures the linked ESP32-C6 Insight firmware, not the Urban firmware and not a host build. It does
not build the image or generate a map. From the repository root, with the ESP toolchain, Python 3, GNU size and nm,
espflash, rustc and git on PATH:
mkdir -p target/insight-memory
map="$PWD/target/insight-memory/insight.map"
RUSTFLAGS="-C force-frame-pointers -C link-arg=-Map=$map" cargo build-insight
scripts/measure.sh insight --map "$map" --out target/insight-memory/report
The map path must be absolute, and the map must be produced by the same link as the ELF. If Cargo considers a prior
build fresh, ensure a fresh link produces the requested map (CI can use cargo clean -p altruist-insight --target riscv32imac-unknown-none-elf --profile firmware first). --elf PATH selects a non-default linked ELF. The
default ELF is target/riscv32imac-unknown-none-elf/firmware/altruist-insight-firmware, respecting CARGO_TARGET_DIR. The script records the
standard alias’s chip, target, profile, features (esp32c6) and flags (-C force-frame-pointers); use --features
and --flags to identify a different build. The caller is responsible for matching this metadata and the map to the
ELF. SHA-256 hashes identify both inputs; they do not prove the files belong together.
The output directory contains deterministic memory-report.md and memory-report.json, copies firmware.elf and
firmware.map, sections.txt from size -A, and app.bin generated using espflash save-image. For image generation,
factory-partition.csv contains only the factory app entry with its Insight offset and capacity: some espflash versions
reject Insight’s custom configuration data subtype. In particular, espflash 4.7.0 panicked in
esp-idf-part-0.6.0/src/partition/mod.rs with called Option::unwrap() on a None value when given the original
CSV. The original CSV is retained as partitions.csv. The script checks explicit partition ranges for factory overlap
and 8 MiB bounds, but the factory-only table does not validate the whole layout and must not be used for flashing.
The image size is the
binary’s length, not an estimate from ELF sections or the total flash
footprint: bootloader, partition table and configuration partition are separate reserved areas. Factory app capacity is
read from firmwares/altruist-insight/partitions.csv; an empty or oversized image is an error. ELF sections include their
addresses and sizes; .data*, .bss* and .noinit* are summed as static RAM. Static heap or stack allocations in
those sections are included; other stacks and RAM code may not be. It is not the full runtime usage. Dummy and debug
sections are not added to it. The main stack’s linker-bounded span (not a measured peak or necessarily a fixed
reservation) and the linked wireless heap symbol are reported when identifiable; the latter is already included in
static RAM. A linker dram_seg region is
reported only if unambiguously present in the map’s GNU ld Memory Configuration; otherwise its capacity is unknown.
This linker region is not necessarily all physical RAM. Heap usage, free RAM, and stack high-water are not measured
by this tool, and remaining RAM region capacity is unavailable. No device or hardware result is implied.
To compare compatible builds:
scripts/measure.sh insight --map "$map" --out target/insight-memory/report \
--baseline path/to/baseline/memory-report.json --max-growth-bytes 1024 --max-growth-percent 5
Limits are optional, nonnegative, and apply independently to every metric. Exceeding either specified limit fails the command after writing the reports (exit 1). Negative deltas do not fail; a positive delta from a zero baseline exceeds any finite percentage limit. Incompatible build metadata or malformed inputs fail with exit 2. Comparison without limits is informational (a warning is left to the caller); limits enable failure. The first successful default-branch report can be selected as the baseline and retained separately; CI must not compare until a baseline has been selected. The tool does not automatically select one. Rust compiler, espflash, size, build metadata and partition table identity must match. Keep the baseline outside the current output directory when comparing. These example limits are not project budgets or measured results.
Run the focused tool tests with python3 -m unittest discover -s scripts -p 'test_measure_insight.py'.
Compact firmware report (#73)
Before and after of the change that made the Altruist Urban firmware smaller at compile time: optional LZ4 log compression and a 128 KiB log on the ESP32-C3, compile-time route and telemetry capacities, a signed packet built in one buffer, and transport-owned TCP security without signed control requests.
How to read the numbers. Measured means taken from a built image or a host test run with the commands below. Static means derived from the source and the schema without a device. Not measured means that nothing here backs it. No number on this page comes from hardware: nothing was flashed, no stack high-water mark was read and no flash was written by a device. The host tests run the log, the secure channel and the control plane on emulated media and sockets.
What was compared
| Baseline | 5f445be (the head of PR #72, feat: auth based control), built in a clean worktree |
| After | this branch (feat/compact-firmware) |
| Toolchain, flags | rustc 1.99.1, the firmware profile on the ESP32-C3 (riscv32imc) and release on the ESP32-C6 (riscv32imac), -C force-frame-pointers, the same features (esp32c3 / esp32c6) |
| Image sections | scripts/measure.sh <chip> [features] (GNU size -A of the production ELF) |
| Task pools, frames, main stack | scripts/memcheck.sh images <chip> out && scripts/memcheck.sh analyze <chip> out --base <baseline json> |
| Variants | LZ4 off (default) and on (--features lz4), packet export on (default) and off |
flash is what the image occupies in flash: .text, .rodata, .rwtext, .trap, the application descriptor, the Wi-Fi
sections and the initial values of .data. RAM (static) is .data + .bss, which includes the 112 KiB wireless heap.
Image size, default build (LZ4 off, packet export on)
| Metric | C3 before | C3 after | Δ bytes | Δ % | C6 before | C6 after | Δ bytes | Δ % |
|---|---|---|---|---|---|---|---|---|
.text | 1 276 856 | 1 259 632 | −17 224 | −1.35 | 1 806 988 | 1 776 564 | −30 424 | −1.68 |
.rodata | 184 152 | 175 352 | −8 800 | −4.78 | 217 592 | 208 776 | −8 816 | −4.05 |
.data | 31 144 | 30 056 | −1 088 | −3.49 | 34 956 | 33 884 | −1 072 | −3.07 |
.bss | 199 264 | 193 912 | −5 352 | −2.69 | 203 376 | 198 016 | −5 360 | −2.64 |
| flash image | 1 592 860 | 1 565 752 | −27 108 | −1.70 | 2 195 680 | 2 155 368 | −40 312 | −1.84 |
| RAM (static) | 230 408 | 223 968 | −6 440 | −2.80 | 238 332 | 231 900 | −6 432 | −2.70 |
Measured. The ESP32-C3 partition for the application is 0x3C0000 B (3 932 160 B) after this change; the image uses 39.8 %.
Runtime RAM: task pools, frames, main stack
| Metric | C3 before | C3 after | Δ | C6 before | C6 after | Δ |
|---|---|---|---|---|---|---|
| Embassy task pools (total) | 45 008 | 41 136 | −3 872 (−8.6 %) | 44 984 | 41 112 | −3 872 (−8.6 %) |
connectivity_task pool | 5 840 | 3 736 | −2 104 | 5 840 | 3 736 | −2 104 |
control_task pool | 15 128 | 13 840 | −1 288 | 15 128 | 13 840 | −1 288 |
logging_task pool | 2 304 | 1 824 | −480 | 2 304 | 1 824 | −480 |
| largest function frame | 13 120 | 12 256 | −864 (−6.6 %) | 9 744 | 8 400 | −1 344 (−13.8 %) |
| main stack allocation | 26 232 | 32 672 | +6 440 (+24.6 %) | 125 528 | 131 960 | +6 432 (+5.1 %) |
Measured (statically, from the images). The main stack is what is left of the RAM after the statics, so it grows by what the statics and task pools gave back. The high-water mark of the stack was not measured on hardware. The deepest call chain under the largest frames is unknown: the numbers say that the largest poll frame shrank, not how deep the stack gets. A smaller wire message is not a proof of a smaller stack; the frame table is the evidence that the stack did not grow.
The memcheck budgets of firmwares/altruist-urban/memcheck-budgets.toml were lowered to the new measurements (ESP32-C3:
max_data 31 200 → 30 100, max_bss 210 800 → 194 000, max_task_ram 45 100 → 41 200, max_frame 13 200 → 12 300,
min_main_stack 15 800 → 32 600; ESP32-C6 analogously). No limit and no approved frame growth was raised. While measuring, the
control_task poll frame and config::start showed frame growth against the baseline only because the compiler had inlined
helpers differently; publish_section, publish_boot and publish_factory_reset are #[inline(never)] again and the controller’s
dispatch_call goes through rohi_service::isolated, which restored the layout instead of widening an approval.
Variants
| Variant | C3 flash | Δ vs default | C3 RAM (static) | C6 flash | Δ vs default | C6 RAM (static) |
|---|---|---|---|---|---|---|
| default (LZ4 off, export on) | 1 565 752 | 223 968 | 2 155 368 | 231 900 | ||
--features lz4 | 1 570 018 | +4 266 (+0.27 %) | 223 968 | 2 163 022 | +7 654 (+0.36 %) | 231 892 |
| packet export off | 1 566 552 | +800 (+0.05 %) | 223 312 (−656) | 2 148 022 | −7 346 (−0.34 %) | 231 324 (−576) |
Measured. The image without LZ4 has no LZ4 symbol (scripts/measure.sh fails the build otherwise); the codec costs 4.3 KB (C3)
and 7.7 KB (C6) of flash when it is compiled in.
Packet export (connectivity.get_payload)
The export pool and its action cost 656 B of RAM on the ESP32-C3 (576 B on the ESP32-C6) and no flash on the ESP32-C3 (the image
without it is 800 B larger there, a layout effect), 7.3 KB of flash on the ESP32-C6. It is kept on by default: removing it
loses the ability to fetch a freshly sealed packet for a profile without a route (rohi connectivity get_payload 0), which is the way
to check a profile and a recipient by hand, and the gain is below 0.3 % of the RAM. It is a feature (connectivity-packet-export of
rohi-sdk, listed in the feature list of altruist-urban; remove it from that list to build without it, and
cargo test -p rohi-connectivity --no-default-features covers the build without it).
Log (ESP32-C3: 128 KiB at 0x20000)
Layout, right after the configuration region (this deliberately differs from the issue, which kept the log at the end of the flash):
| Partition | Offset | Size |
|---|---|---|
rohi-cfg | 0x10000 | 0x4000 |
rohi-log | 0x20000 | 0x20000 (128 KiB, 32 sectors: 30 for the ring, 2 for the format header) |
factory | 0x40000 | 0x3C0000 (ends the flash, both ends 64 KiB aligned) |
The ESP32-C6 is unchanged (factory at 0x20000, rohi-log the last 1 MiB). The ring has 15 segments of 8 KiB (120 KiB). A
device flashed with an earlier layout must be reflashed with the new table (the app moves) and the first start formats the
rohi-log region only: nothing is migrated and the old archive is discarded (host tests: a format cut at every erase and write
leaves the neighbours, here the application and the configuration, byte for byte as they were).
Retention (measured on an emulated 128 KiB medium, plain text, the_esp32c3_log_retention_is_measured). Text lines of 80 to
160 bytes, written until three times the ring has passed, batch of up to 1 KiB per flush. Every cell is records / payload bytes of
text kept, 15 segments retained in all cases. The theoretical ceiling is 122 880 B (15 × 8 KiB, before segment and batch overhead).
| Line | flush after 1 record | after 6 | after 20 | after 64 |
|---|---|---|---|---|
| 80 B | 1 207 / 103 802 | 1 260 / 107 100 | 1 320 / 110 880 | 1 256 / 105 504 |
| 100 B | 993 / 104 868 | 1 056 / 110 880 | 991 / 103 064 | 1 025 / 106 600 |
| 120 B | 807 / 100 875 | 882 / 110 250 | 880 / 109 120 | 960 / 119 040 |
| 160 B | 708 / 104 784 | 732 / 108 084 | 754 / 110 838 | 747 / 109 638 |
That is 98 to 116 KiB of text kept (82 % to 97 % of the 120 KiB ring), not the ~119 KiB estimate in the issue, which no flush pattern
reaches because a segment is sealed once a batch would not fit. The batch was reduced from 2 KiB to 1 KiB of text for this: with
2 KiB, 85 to 107 KiB (87 462 to 109 988 B) were kept, and the Batch in the logging static shrank by 1 KiB. A reboot keeps the same records (tested for every
cell). Reboot and corruption recovery are covered by the cut-at-every-write tests across format, clear, version mismatch and
recovery, for both codecs. Not measured: the time of a format or of a download on the device, flash wear.
Telemetry packet
| Before | After | |
|---|---|---|
MAX_SENSORS_PER_MESSAGE | 9 | 8 (one per measurement the encoder supports) |
MAX_PRIVATE_SECTIONS | 2 | 1 (one recipient per profile) |
MAX_PRIVATE_PLAINTEXT_LEN | 128 B | 115 B (the sum of the largest entries of the 8 supported measurements) |
MAX_ENCRYPTED_LEN | 232 B | 207 B (as this SDK writes it) |
MAX_MESSAGE_LEN | 780 B | 352 B |
MAX_ENVELOPE_LEN = packet buffer | 920 B | 473 B (−447 B per pool slot; three slots, the pool and one export slot, −1 341 B in the pool and export statics) |
| typical packet (2 public, 1 private section of 2), signed | not measured before | 284 B (measured) |
| largest packet (8 public, 8 private) | not measured before | 419 B, message 298 B (measured); the limit is exactly the largest message that the compiled capabilities allow (352 B message, 473 B envelope), checked by a test that builds it from the schema |
The bounds follow the compiled capabilities, not the schema alone: the schema permits a list of eight GPS entries (510 B as a
message), the encoder never writes more than one entry per supported measurement. A section that would exceed them fails with TooLarge;
nothing is truncated.
One buffer instead of five. RobonomicsFormat::seal used to hold the sensors, the plaintext (128 B), the ciphertext (144 B), an
Encrypted value, an encoded Message (780 B), a separate Ed25519 preimage (828 B) and a SignedEnvelope (944 B) at the same time. Now the
message is encoded to its final place in the caller’s packet buffer, sensor_id || nonce is staged right in front of it (that is the
exact preimage), the signature is computed over those bytes and the envelope fields are written over the staged bytes. The private
section is encrypted in place in one 131 B buffer and its Encrypted message is written from the parts. The signed bytes, the
Ed25519 prehash (none: the preimage is signed whole), the XChaCha20-Poly1305 semantics, the order of the entropy draws and the byte
output are unchanged: tests decode every packet, re-encode the envelope, the message and the private section with the generated
types and compare byte for byte, and verify the signature over the preimage for message sizes on both sides of the length-prefix
boundaries.
Snapshot. SNAPSHOT_OBSERVATIONS was CATALOG.len() (18); it is the number of measurements the compiled encoder supports (8),
and a capture stores only those (capture_accepting): a source that also reports an unsupported measurement (the SCD4x, the gas
sensors) is not discarded for it. The diagnostics array holds 2 sources (the sensors, the location) instead of 8. Per-source
atomicity, freshness, validation and the distinction between capture time and observation time are unchanged; the local sensors and
their status do not go through the snapshot. A snapshot of 8 observations and 2 reports is about 0.4 KB smaller than one of 18 and 8 (static, 32 B per observation).
Connectivity and telemetry capacities
ROUTES = 2 and PROFILES = 2 are const generics (since #75 the route and profile slots are indexed 0 and 1, with one fallback per route and one private recipient per profile, so there are no FALLBACKS and RECIPIENTS parameters) through Routes, ConnectivitySection,
ConnectivityState, Router, Publisher, ConnectivityService (and the store trait), TelemetryConfig, TelemetrySection,
TelemetryState, TelemetryService. The storage is the capacity (a third route has no room), the status schema is written
out for the route count (Slots<2>; any count outside 1 to 2 does not compile) with stable ids, names and kinds, and a stored
section over capacity does not decode: it is refused, not truncated (tests with three routes and three profiles; the sections were redefined by #75 with no
migration: an older section is not read). Retry and backoff, fair scheduling, generation and stamp checks, outbox
handling and profile invalidation keep their tests unchanged in meaning (they run with more slots than a device keeps, the SDK-side
tests cover more than a device keeps).
TCP security
rohi-control-tcp owns the security of the TCP endpoint; rohi-control has no cryptography and consumes only the
encrypted/authenticated flags that a trusted transport sets (a request field cannot raise them). A client that starts with the handshake preamble (every mode; the TCP
access mode is protected by default, plaintext reads only without it) is served only after the handshake (32-byte pre-shared key, HKDF-SHA256, random nonces, mutual proofs bound to
the transcript, directional keys, XChaCha20-Poly1305 with a counter and direction nonce, versioned authenticated record framing,
no processing before the handshake verified, no fallback to plaintext). The key is always generated by the device:
control.tcp_generate_psk (a secure_link action) makes a new key on every call and returns it, over the TCP connection of the current
key or, in this phase, over open BLE (an accepted, insecure exception: BLE has no pairing or encryption); there is no forward secrecy. Signed requests, the challenge and the administrator key are gone from the protocol,
the control core, the services, the firmware and the rohi CLI (rohi admin became the generic action rohi action control tcp_generate_psk; --admin-key became
--psk-file). The ControlHub request slot is 128 B smaller (896 → 768) because it no longer has to hold a signed wrapper.
Negative tests (host): tampered (every bit of header, data and tag), replayed, reordered, dropped and truncated records, a record of another connection and of the other direction, a counter that is used up (stops for good), a wrong key on either side, a client that sends plaintext or a bad final message (ends in silence, counted, never processed), no key or no random source (serves nobody), a key that was replaced while connected (ends the connection, and a request of it that was already queued is not run), a client that sends the handshake or a record one byte at a time (absolute deadlines of 10 s, cut off), the end of a connection when the worker queue is full (the streams are still closed) and cancellation (the session is released). Not covered: TCP is a host (std) transport; there is no TCP endpoint on the ESP firmware, so none of this ran on a device.
Functionality intentionally removed or reduced
- Signed control requests,
GetAuthChallenge, the administrator key androhi admin(replaced by the pre-shared key and the TCP channel). - LZ4 log compression from the default build (the
lz4feature brings it back) and every reader of older log formats: a log of another format version is discarded, not read. - The ESP32-C3 log shrank from 512 KiB to 128 KiB (120 KiB ring) and moved in front of the application.
- A third route, a second fallback, a third profile, a second private recipient and a second private section per message; the Robonomics format is the only compiled telemetry format; unsupported measurements are no longer stored in a snapshot.
- A TCP client can no longer connect without the key unless the endpoint is explicitly open (plaintext, loopback development).
BLE without pairing (#83)
The host stack (trouble-host) is built without its security feature: the peripheral is open and never pairs, so the
Pairing::handle_input handlers (20.2 KiB for the peripheral in the ESP32-C3 cargo bloat before the change, plus the
central one and smaller pairing functions) and the aes, cmac, dbl, p256 and primeorder crates are no longer in
the image. cargo bloat of the ESP32-C3 image has no Pairing symbol after the change. The TCP secure channel, the
identity and the telemetry cryptography do not use these crates and are unchanged.
Metric (scripts/measure.sh, default features, the same toolchain and profiles) | C3 before | C3 after | Δ bytes | C6 before | C6 after | Δ bytes |
|---|---|---|---|---|---|---|
.text | 1 223 758 | 1 128 684 | −95 074 | 1 728 406 | 1 575 126 | −153 280 |
.rodata | 173 112 | 167 496 | −5 616 | 205 648 | 202 080 | −3 568 |
.data | 29 984 | 29 512 | −472 | 33 668 | 32 796 | −872 |
.bss | 191 936 | 190 120 | −1 816 | 196 048 | 194 232 | −1 816 |
| flash image | 1 527 562 | 1 426 400 | −101 162 | 2 103 866 | 1 946 146 | −157 720 |
| RAM (static) | 221 920 | 219 632 | −2 288 | 229 716 | 227 028 | −2 688 |
Measured from built images. The saving is larger than the two handlers alone because the dependent cryptography and the
shared code went with them. max_data and max_bss of memcheck-budgets.toml were lowered to match. BLE is open and
unencrypted and a link is always reported as unencrypted and unauthenticated; suitable only for trusted environments.
Advertising, connection, writes, notifications, disconnect and reconnect were not run on a device.
Meshtastic UART (opt-in)
--features meshtastic-uart adds the meshtastic service, the radio session task and the Meshtastic transport. Measured with
scripts/measure.sh esp32c3 meshtastic-uart against scripts/measure.sh esp32c3 (same commit, bytes):
| Metric | Default | meshtastic-uart | Delta |
|---|---|---|---|
.text | 1 090 150 | 1 124 388 | +34 238 |
.rodata | 168 920 | 172 600 | +3 680 |
.data | 29 536 | 29 672 | +136 |
.bss | 190 152 | 193 576 | +3 424 |
| flash (text, rodata, data) | 1 389 314 | 1 427 368 | +38 054 |
static RAM (.data + .bss) | 219 688 | 223 248 | +3 560 |
.data stays below the max_data budget of the ESP32-C3. The link (queues, inbox, counters) is built on first use so that it
stays in .bss; it holds the six-entry inbox of 64-byte texts, one outgoing message of 260 B and 16 routing results. The ESP32-C6
was not measured. The default image (without the feature) passes scripts/memcheck.sh for the ESP32-C3.
Not measured, not verified
- Everything on hardware: boot time, the time of a log format and a download, stack high-water marks, flash wear, BLE control without pairing and the link security of a real central, the 128 KiB layout flashed to a board and the move of the application.
- Throughput or latency of the secure channel (the host tests do not time it).
- The cost of the removed signed-request code in flash separately from the other changes of this branch (the totals above are for the whole change; the per-feature variants are the LZ4 and packet export rows).
Reproduce
git worktree add /tmp/base 5f445be && (cd /tmp/base && scripts/memcheck.sh images esp32c3 /tmp/base-out && scripts/memcheck.sh analyze esp32c3 /tmp/base-out)
scripts/memcheck.sh images esp32c3 out && scripts/memcheck.sh analyze esp32c3 out --base /tmp/base-out/task-memory-esp32c3.json
scripts/measure.sh esp32c3 # the image sections; again with `lz4` as the second argument
cargo test -p rohi-logging retention -- --nocapture # the retention table
cargo test -p rohi-telemetry-robonomics --test seal -- --nocapture # the packet lengths
Firmware distribution
Not implemented. ROHI has no firmware registry, update service or signing infrastructure. This page says what exists today and what a firmware author can do.
Today
- The source of the reference firmware is this repository. Build it for your chip and flash it with
cargo run, see Quick start. No pre-built images are published. - A custom firmware needs no approval to be operated with
rohi: it only has to implement the control protocol (Compatibility). - To share a firmware, publish its source and say which board and chip it targets and which ROHI revision it was built against. The control protocol is still changing, so the revision matters.
- To make hardware claims visible, record validation as described in Validation and, for boards and capabilities of this repository, update the support matrix.
Planned
Distribution of verified and community firmware, with provenance and update mechanisms, is a goal of the ecosystem and is outside this SDK for now. When it exists it will keep the three questions of Compatibility separate.
Documentation style and policy
Where things are documented
| Place | Content |
|---|---|
README.md | project landing page and the shortest quickstart, with links to this book and the API docs |
This book (mdBook, docs/) | product vision, current capabilities, user journeys (Use a Device, Build Firmware, Verify & Share), tutorials and navigation |
Rustdoc (cargo doc --no-deps, docs.rs) | the authoritative technical documentation of each crate and of the cross-cutting concepts (rohi-sdk): APIs, contracts, ownership, cancellation, resource constraints, integration examples; do not copy API listings into the book |
| Crate and module comments | local implementation contracts: invariants, cancellation semantics, safety |
| Source and protocol definitions | authoritative schemas (control.proto), implementations, tests, platform behaviour |
| Support matrix | hardware compatibility, firmware support, verification levels and evidence |
The book explains how to use and extend ROHI; the crates explain how ROHI works internally. All 19 crates carry their technical documentation in rustdoc, and the book has no technical reference section: no API listings, contracts, limits tables, ABI or protocol details. Link to the rustdoc instead (see SDK crates) and put a new contract in the crate that owns it.
How to write and validate crate rustdoc (structure, templates, doctest policy, agent workflow, checklist): Rustdoc authoring guide.
One authoritative location per concept
A fact lives on exactly one page; other pages link to it. Canonical pages:
| Concept | Where |
|---|---|
| Resource limits and constants | the product constants in firmwares/altruist-urban/src/esp/resources.rs and the rohi-sdk memory rustdoc |
| Persistent ABI rules | the rohi-config rustdoc and the rohi-sdk versioning rustdoc |
| Targets, features and commands | the rohi-sdk portability rustdoc |
| Control protocol and its limits | the rohi-control-proto rustdoc; concept: Control protocol |
| Cancellation rules | the rohi-sdk cancellation rustdoc |
| Measurements and sizes | Resource budget |
| Supported boards, firmware and verification evidence | Support matrix |
Style
- Mark what is implemented, planned and not verified explicitly; never describe a plan as a feature (see the mobile application page).
- Describe the current product behaviour and workflows with concrete examples (commands, what a client shows). Keep Rust API names, contracts, limits and architecture out of the book: link to the rustdoc instead of pasting them.
- Do not leave obsolete work-package terminology or history in normative pages; history belongs to the commit log and the measured-data tables of the validation pages.
- Mark claims that are not validated on hardware explicitly (“not yet measured”, “not verified on hardware”).
- State security limitations plainly (BLE is open: no pairing or encryption, no TLS yet).
- Prefer tables for support and verification status, and short paragraphs.
- Examples are compiled where possible: put host-compilable code in a test file, show it with
{{#include path:anchor}}and mark the blockrust,ignore; usetextorrust,ignorefor hardware-only snippets.
Update policy
A change must update the SDK book in the same pull request when it changes:
- public architecture or crate responsibility,
- public API usage,
- persistent ABI or the wire protocol,
- target support,
- resource defaults,
- the developer workflow.
- a board, a sensor driver, a firmware wiring or a hardware result: update the support matrix in the same pull request.
Pure internal refactors with unchanged public behaviour do not need documentation churn.
Checks
mdbook build docs # the book builds
mdbook test docs # plain Rust snippets compile
cargo doc --no-deps # rustdoc of the host crates builds without warnings
lychee --offline --include-fragments docs/book # internal links and anchors resolve (CI)
cargo test -p rohi-devices # support matrix schema, references and generated page
CI runs these in the docs job (and the support matrix test in the host job). A broken internal link is a defect: fix the link or the page, do not exclude it.
Rustdoc authoring guide (for developers and AI coding agents)
Crate-level rustdoc is the authoritative technical documentation of every ROHI SDK crate. A reader must understand a crate from its docs.rs page without reverse-engineering the implementation. This guide is the canonical procedure for writing and maintaining it. Follow it literally; where it says must, the PR is not done otherwise.
Where documentation lives (book vs rustdoc vs source) is defined in Documentation style and policy. This page only covers rustdoc.
Principles
- Code is the source of truth. Verify every claim against the implementation, tests and Cargo features before writing it. If the code and an old doc disagree, the code wins and the doc is fixed.
- Explain before listing. Purpose, concepts and usage first; the item list is generated by rustdoc.
- Document guarantees explicitly: errors, ownership, concurrency, cancellation, resource bounds, persistent and wire compatibility, safety.
- Never invent. No invented guarantees, numbers, behaviours, examples or hardware results. If you did not read it in code, a test, a schema or the support matrix, do not write it. Write “not measured” or “not verified on hardware” instead.
- One authoritative place per fact. Rustdoc owns crate contracts. The book owns user journeys and links here; do not copy API listings or limit tables into the book (canonical pages: see docs-style).
- Examples are compiled. A doctest that cannot rot beats a snippet that can.
Crate-level //! structure
Every crate landing page uses these headings, in this order. Omit a section only when it does not apply (a docs-only or generated crate), never reorder.
| # | Heading | Content |
|---|---|---|
| 1 | (first paragraph, no heading) | One-sentence summary shown in search results and on the crate list |
| 2 | # Overview | What the crate provides, when to use it, what it deliberately does not do, no_std / allocation / feature facts |
| 3 | # Quick Example | The smallest meaningful runnable example (a doctest) |
| 4 | # Core Concepts | The main abstractions and how they relate; tables for vocabularies |
| 5 | # Architecture and Integration | How it fits into firmware and the other crates; a text diagram or table; who owns what |
| 6 | # API Navigation | Table of the important modules, traits, types and macros, each an intra-doc link |
| 7 | # Guarantees and Limitations | Errors, resource bounds, cancellation, ABI/wire stability, feature flags, target and platform requirements, what is not verified |
Adapt the emphasis, not the skeleton:
| Crate kind | Emphasis |
|---|---|
Runtime service (rohi-time, rohi-net) | state machine, config section, status issues, cancellation, resource bounds |
Procedural macro (*-derive) | attribute table, generated items, compile-time errors (compile_fail doctest); the macro is used through the runtime crate’s re-export |
Platform adapter (*-esp) | chip features and targets, what is empty without a chip feature, ownership of peripherals, link to firmware |
Generated protocol bindings (*-proto) | the authoritative .proto, public wrappers, limits, compatibility rules; do not list generated items |
Docs-only (rohi-sdk) | crate map, cross-cutting contracts, links to the crate that owns each contract |
Template
//! One-sentence summary, ends with a period.
//!
//! # Overview
//!
//! What `rohi-foo` provides and when to use it. What it does not do. Whether it
//! is `no_std`, allocation free, which Cargo features it has.
//!
//! # Quick Example
//!
//! ```
//! use rohi_foo::Foo;
//!
//! let foo = Foo::new();
//! assert!(foo.is_ready());
//! ```
//!
//! # Core Concepts
//!
//! | Concept | Meaning |
//! |---------|---------|
//! | [`Foo`] | what it is, in one line |
//!
//! # Architecture and Integration
//!
//! ```text
//! firmware task ──► Foo ──► rohi_service::Status
//! ```
//!
//! # API Navigation
//!
//! | Item | Use it to |
//! |------|-----------|
//! | [`foo`] | ... |
//! | [`Foo`] | ... |
//!
//! # Guarantees and Limitations
//!
//! - **Errors:** see [`FooError`].
//! - **Cancellation:** every `async fn` is cancel safe / not cancel safe because ...
//! - **Limits:** at most N entries, sizes are wire ABI ([Resource limits]).
//! - **Targets:** host-tested; hardware verification: not verified ([support matrix]).
//!
//! [Resource limits]: https://docs.rs/rohi-sdk/latest/rohi_sdk/memory/index.html
//! [support matrix]: https://rohi.akagi.dev/support/overview.html
Item-level /// documentation
- First line: one sentence, third person, ends with a period (
Returns ...,Wraps ...). - Then the contract: what the caller must provide, what is guaranteed, what is not.
- Use the standard sections where they apply, in this order:
# Errors,# Panics,# Safety,# Examples.# Errors: every error variant a caller can observe and when it occurs. Link variants with intra-doc links.# Panics: every panic path, includingunwrap/index/overflow in the function body. If it cannot panic, say nothing.# Safety: required for everyunsafe fnandunsafe trait; list the caller obligations, not the implementation.
- Traits: document the contract an implementor must uphold (cancellation safety, blocking, ordering, what the caller guarantees) on the trait and on each required method. Document provided methods separately.
- Trait implementations: do not repeat the trait docs; document only what is specific to the implementation.
- Enums: document each variant, and for error enums say who produces it and how the control plane or caller reacts.
- Macros (
macro_rules!, derives): table of attributes (key, required?, meaning), the generated items, and a doctest; add acompile_faildoctest for each important rejection. - Feature-gated or target-gated items: state the gate in prose (
Available with the esp32c3 or esp32c6 feature). Do not link with intra-doc links to items that do not exist in every documented configuration (see Validation); use plain code font instead. - Constants and limits: state the value only if it is the single source of truth (the constant itself); otherwise link to Resource limits.
- Persistent and wire formats: state what is ABI (ids, field numbers, section versions) and link Persistent ABI.
- Public vs internal:
pub(crate)and private items need comments only when they hold an invariant. Do not document internals on public pages; put them in plain//comments next to the code.
Good and bad
Bad: restates the signature, invents a guarantee, no error contract.
/// Creates a new storage.
///
/// This is very fast and never fails on all supported flash chips.
pub fn new(flash: F, region: FlashRegion) -> Result<Self, EspStorageError>
Good (from rohi-config-esp): states the precondition, every error and the compile-time constraint.
/// Wraps `flash`, restricted to `region`.
///
/// The region must be non-empty, erase-sector aligned and inside the
/// flash capacity.
///
/// # Errors
///
/// [`EspStorageError::InvalidRegion`] if the region is empty, its offset
/// or length is not a multiple of `F::ERASE_SIZE`, its end exceeds the
/// flash capacity, or its end does not fit in `u32`.
pub fn new(flash: F, region: FlashRegion) -> Result<Self, EspStorageError>
Bad (hardware claim without evidence): “Tested on ESP32-C6, takes about 20 ms to erase.”
Good: “Erase duration is not measured; esp-storage runs flash routines in a critical section.” State only what the
support matrix and the validation pages record.
A well-documented derive (from rohi-service-derive): the crate page has Overview, a runnable Quick Example, a table
of generated items, the naming rule, and says that the id is wire ABI. Use it as the model for macros:
/// ```
/// use rohi_service::Service;
///
/// #[derive(Service)]
/// pub struct WifiService;
///
/// assert_eq!(WifiService::NAME, "wifi");
/// assert_eq!(WifiService::ID, rohi_service::service_id("wifi"));
/// ```
Technical accuracy
Before writing a sentence about behaviour:
- Read the implementation of the function or type, not only its signature.
- Read the tests: they show intended edge cases (and sometimes the documented behaviour is wrong).
- Read
Cargo.tomlfor features and dependencies; readbuild.rsand.protofiles for generated code. - Search for callers (
firmwares/altruist-urban,examples/) to see the real integration pattern.
Then classify each statement:
| Kind | Where it belongs |
|---|---|
| Public guarantee (callers may rely on it, changing it is breaking) | item docs, stated as contract |
| Implementation detail (may change) | plain code comments, or label it “currently” |
| Wire/persistent ABI | item docs plus a link to Persistent ABI |
| Unmeasured or unverified | say so explicitly |
Always document, where relevant:
- Ownership: who owns the peripheral, buffer or task; what
&mut self/&selfimplies; what must be'static. - Async and cancellation: whether dropping a future mid-way is safe and what state remains. The canonical rules are in Async and cancellation; link them, do not restate them.
- Resource bounds: capacities of
heaplesscollections, buffer sizes, queue depths, timeouts and what happens at the limit (error, drop, block). - Compatibility: section ids and versions, field numbers, hash algorithms (these are ABI).
- Platform: which chip features and targets compile, what is an empty crate without a feature.
- Experimental or planned: use the words “implemented”, “planned”, “not verified”; never describe a plan as a feature.
- Hardware results: never write one. The only sources are
device-matrix.tomland the validation pages. Distinguish host-tested (unit tests/doctests), target-built (CI builds the ESP target) and hardware-verified (recorded evidence).
Examples and links
- Prefer doctests that run on the host. Portable crates must have at least one in the landing page.
- Use hidden lines (
# use ...;) only for imports and boilerplate that does not hide a requirement the reader needs. - Choose the code-block attribute deliberately:
| Attribute | Use when |
|---|---|
| (none) | the default; the example compiles and runs on the host |
no_run | compiles on the host but needs hardware, a network or never terminates |
compile_fail | demonstrates a deliberate rejection (macro error, borrow rule); keep it specific |
should_panic | demonstrates a documented panic |
text | diagrams, wire layouts, shell output, chip-only snippets that cannot compile on the host |
ignore | almost never; allowed only with a comment saying why it cannot compile anywhere. Never use ignore to bypass a broken example: fix it. |
- Chip-only (
*-esp) examples cannot be doctested on the host. Show a shorttextexcerpt or link the maintained source (firmwares/altruist-urban,examples/src/bin) instead of copying large blocks of implementation. - Intra-doc links for every Rust item:
[`Type`],[`module::function`],[`rohi_config::Value`]. Do not hand-write docs.rs or../rohi_x/index.htmlURLs for dependencies. A relative../rohi_x/index.htmlis allowed only when the target is not a dependency (for example a lower crate pointing at the firmware-facing crate, or the docs-onlyrohi-sdk). - Items that exist only with a chip feature must not be intra-doc linked from pages that are also built without it
(host
cargo docwould fail with-D warnings). Use code font:`EspWifi`. - Links to the book use
https://rohi.akagi.dev/...; links to sources use repository paths in code font. - Tables for vocabularies, limits and error maps;
textdiagrams for structure and data flow. - Name the project “Robonomics Open Hardware Interface (ROHI)”.
Agent workflow
Follow these steps for every crate you touch:
- Inspect the public API (
cargo doc --no-deps -p <crate> --openor readlib.rsexports), the implementation, tests,Cargo.tomlfeatures and callers. - Identify missing, wrong, obsolete and invented documentation. Write the list down.
- Update the crate landing page: fill the seven sections from the template, with concepts and navigation.
- Document the affected public items: contracts,
# Errors,# Panics,# Safety. - Add or repair examples: a Quick Example plus a focused doctest per important trait, macro and integration
pattern. Replace every
ignore. - Run the checks from Validation.
- Inspect the rendered docs (
cargo doc --no-deps -p <crate> --open): headings, tables, links, diagrams. - Report in the PR what was verified (commands, tests) and what could not be validated (hardware, chip-only doctests, external URLs).
Validation
Run through nix develop --command bash -c '<command>' when cargo is not on PATH.
# portable crates: broken links and rustdoc warnings are errors
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps
# doctests and unit tests (host default-members)
cargo test --doc
cargo test
# lints
cargo clippy --all-targets -- -D warnings
cargo fmt --all -- --check
# one crate while you work
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps -p rohi-time
cargo test --doc -p rohi-time
# ESP crates: one chip per invocation, never --all-features
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps -p rohi-hal-esp -p rohi-config-esp -p rohi-net-esp \
--no-default-features --features esp32c3 --target riscv32imc-unknown-none-elf
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps -p rohi-hal-esp -p rohi-config-esp -p rohi-net-esp \
--no-default-features --features esp32c6 --target riscv32imac-unknown-none-elf
# the book (mdBook): build and snippets
mdbook build docs && mdbook test docs
CI (.github/workflows/ci.yml, job docs) runs the same rustdoc commands with -D warnings for the portable crates
and for the ESP crates on both chips; the host job runs cargo test (which includes doctests). A failing doc build
blocks the PR. Targets and features: Targets and features.
Doctests of derive macros live in the macro crate and use the runtime crate (rohi-service, rohi-config) as a
dev-dependency.
Review checklist
Apply to every PR that changes public API or documentation:
- Every claim was verified against code, tests, schema or the support matrix; nothing invented.
- The crate page follows the seven-section template (or states why a section is omitted).
- New or changed public items have a contract,
# Errors,# Panics,# Safetywhere applicable. - Ownership, cancellation, resource bounds and ABI/wire compatibility are stated where relevant.
- Examples are doctests; no
ignorewithout a reason; hardware-only code istextor a link to maintained sources. - Intra-doc links are used; no chip-gated item is linked from a page built without the chip feature.
- Verification wording separates host-tested, target-built and hardware-verified; no unrecorded hardware result.
-
RUSTDOCFLAGS="-D warnings" cargo doc --no-depsand the ESP doc builds pass;cargo test --docpasses. - The book page for the concept only links to the rustdoc (no copied API listings or limit tables).
- The support matrix is updated when a board, driver or hardware result changed.