A NervesHub device agent for ESP-IDF targets, in Rust.
This enables you to add your ESP32-IDF Rust applications to your NervesCloud account or self-hosted NervesHub platform.
This crate orchestrates updates through esp_ota with the
bootloader's rollback protection intact.
Early development
| Layer | State |
|---|---|
| Phoenix v2 frame codec | ✅ |
| Join payload / firmware metadata | ✅ |
| Update payload, decisions, progress throttling | ✅ |
| Checksums | ✅ |
| Install orchestration (download → verify → commit) | ✅ |
Delta updates (esp_delta_ota) |
✅ |
WebSocket transport (esp_websocket_client) |
Run on hardware with shared secrets: over ws:// on the ESP32 bench, and over wss:// to NervesCloud on an ESP32-C6 |
HTTP download (EspHttpConnection) |
✅ |
esp_ota apply, rollback confirmation |
✅ |
| Extensions: health, geo, logging | ✅ |
| Reboot and identify | ✅ |
| Console: a fixed set of commands | ✅ |
| mTLS transport | Run on hardware: a CA-signed client certificate over wss:// to NervesCloud on an ESP32-C6, TLS 1.2, session resumption included |
| Device identity from NVS | Run on hardware: the certificate and key read from the certs partition on an ESP32-C6 |
- ESP-IDF v5.3 or later, via
esp-idf-svc0.53 (std); CI builds against v5.5.5. Theno_stdesp-halstack is not supported: it brings no ESP-IDF, and therefore noesp_ota, noesp_websocket_client, and no mbedTLS. - Two app partitions plus
otadata. Seepartitions.csv. CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y. Seesdkconfig.defaults.- The
espressif/esp_websocket_clientmanaged component. It is not part of core ESP-IDF, andesp_idf_svc::ws::clientis cfg-gated on its presence, so without it the module silently does not exist and you get an unresolved import. See the note below. - The
espressif/esp_delta_otamanaged component, which applies the patches NervesHub generates. Without it, delta updates fail; full images still work.
esp-idf-sys reads [package.metadata.esp-idf-sys] only from the root
package of the build, so none of this is inherited from a library dependency.
An application using this crate must copy into its own Cargo.toml:
[[package.metadata.esp-idf-sys.extra_components]]
remote_component = { name = "espressif/esp_websocket_client", version = "^1.0" }
[[package.metadata.esp-idf-sys.extra_components]]
remote_component = { name = "espressif/esp_delta_ota", version = "^1.1" }
bindings_header = "include/delta_ota_bindings.h"esp_delta_ota needs the bindings_header as well as the component. esp-idf-sys
generates bindings from a curated header list that covers the well-known
components; this is not one of them, so without a header that includes
esp_delta_ota.h the component builds and its symbols never reach Rust. Copy
include/delta_ota_bindings.h from this repo.
and into its own sdkconfig.defaults:
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
The partition table is deliberately not configured in this repo's
sdkconfig.defaults: esp-idf-sys builds ESP-IDF in its own output directory,
where a relative partitions.csv does not exist, so setting it here breaks the
library build. partitions.csv is a working example to copy.
Note also that cargo does not invalidate a build script when package.metadata
changes. After editing the extra_components block you must
cargo clean -p esp-idf-sys or the change is silently ignored.
- Xtensa parts (ESP32, S2, S3) need the
esprustc fork:espup install, then build with+esp. RISC-V parts (C3, C6, H2, P4) build on stable.
There is deliberately no rust-toolchain.toml: pinning the esp channel
would make cargo test fail on any machine without espup installed, and the
protocol layer is meant to be testable anywhere. Select the toolchain per build
instead:
cargo test # host, no ESP toolchain
cargo +esp esp32 # device build
cargo +esp check-esp32 # device type-check, no linkingesp32s3 and check-esp32s3 are there too. The bench runs on a plain ESP32,
so that is the target with hardware behind it.
The device aliases live in .cargo/config.toml. They carry
-Zbuild-std=std,panic_abort, which the esp toolchain needs because it ships no
prebuilt std for the espidf targets. It cannot go in [unstable], because
that would apply to host builds and break cargo test on stable.
Three layers. Start at the top; drop down only when you need to.
fn main() -> Result<(), nerves_hub_link_esp32::Error> {
esp_idf_svc::sys::link_patches();
esp_idf_svc::log::EspLogger::initialize_default();
// ... bring wifi up ...
nerves_hub_link_esp32::esp::run("devices.nervescloud.com")?;
Ok(())
}That reads the client certificate from NVS and the running firmware from
esp_app_desc_t, connects, joins, confirms the running image once NervesHub
accepts it, heartbeats, and installs updates as they arrive, rebooting into
each one. See examples/basic.rs.
Bring the clock up before this, with SNTP. See Authentication for why a device that believes it is 1970 cannot join.
Most devices should not drop what they are doing to install firmware. Implement
[UpdateHandler] and NervesHub is told what you decided, rather than being left
to guess from silence:
struct Policy;
impl UpdateHandler for Policy {
fn update_available(&mut self, _update: &UpdatePayload) -> UpdateDecision {
if mid_measurement() {
// Recorded server-side, and the device is held off for five minutes.
UpdateDecision::Reschedule { delay_minutes: 5, reason: "busy".into() }
} else {
UpdateDecision::Apply
}
}
fn progress(&mut self, stage: Stage, percent: u8) {
log::info!("{} {}%", stage.as_str(), percent);
}
}
let mut config = Config::new("devices.nervescloud.com", identity::load()?);
config.heartbeat_interval_secs = 45;
esp::agent_with(config, Policy)?.run()?;See examples/advanced.rs.
Agent is generic over a [Platform], the trait holding every operation that
touches the world: connect, download, write flash, confirm, reboot, sleep, clock.
EspPlatform is one implementation. Supplying another gets you a different
transport, a different flash target, or a simulated device for testing your own
update policy without hardware.
Below that, the pieces are public and independent: Link (the channel state
machine, generic over Transport), install (download → verify → commit,
generic over HttpStream and ImageSink), message (the wire format).
The loop deliberately lives in the library rather than in an example. Its sequencing has several things that are easy to get wrong and silent when you do: confirming the running image only after the join succeeds, aborting a failed install without rebooting, backing off only when a session never joined. None of that could be tested while it was code users copied.
The download runs on that same loop, and services the connection between chunks: heartbeats and queued log lines go out while an image comes down, and a heartbeat that cannot be sent is how the download learns the connection has gone. Nothing is read during one, and nothing needs to be: frames arriving queue on the transport and are handled when it finishes, so a console command typed mid-update is answered late rather than lost.
A download that can't start is tried again, three more times, 5, 15 and 45 s
apart, or after the server's Retry-After when that is longer (up to two
minutes). That covers a connection that fails, a response that never comes, and
a 408, 429 or 5xx. It doesn't cover a 403, which is an expired pre-signed
URL that asking again only repeats, or a 404. The waits are spent as the
download is, with heartbeats and logs going out. Once any of the image has been
written nothing is retried: the failure goes to NervesHub, whose deployment
offers the update again.
run holds the connection for as long as the device is up, and returns only
to reboot into an update. A battery device can't do that: it wakes, reports,
and sleeps again. run_session is one connection, bounded:
use nerves_hub_link_esp32::{SessionWindow, Stopped};
use std::time::Duration;
let window = SessionWindow {
// Stay at least this long after the join, for an update or a console.
linger: Duration::from_secs(10),
// Leave by this, whatever is still queued. An update that has started
// installing always finishes.
limit: Duration::from_secs(90),
};
match esp::agent_with(config, policy)?.with_health(health).run_session(window) {
Ok(Stopped::Finished) => {} // reported; go back to sleep
Ok(Stopped::Rebooting) => {} // an update, or an operator's reboot
Err(err) => log::warn!("{err}"), // no retry: that's the caller's call
}Inside the window it does everything run does in a session: the running
image is confirmed once the join is accepted, extensions attach, updates
install. It leaves once the join is linger old and nothing is outstanding --
the extensions channel answered, the health check NervesHub sends on attach
answered, the queued log sent -- or at limit. Nothing is retried: a refused
connection, or a session the server ends early, is an Error::Transport,
because only the application knows what another attempt costs its battery.
Over a cellular link, give the connection longer to come up. DNS, TCP, the TLS
handshake and the websocket upgrade must all complete inside
Config::connect_timeout_secs, which defaults to 10. Over LTE-M, on an
ESP32-S3, the TLS handshake alone has been measured at 5.5 to 11.5 seconds:
config.connect_timeout_secs = 30;A device that sleeps on battery may still be on mains or USB some of the time,
and then there is no reason to leave. run_session_until keeps the session
open until the application says otherwise, and gives it a turn between frames
-- at least every half a second or so while the socket is quiet -- to do its
own work there:
use nerves_hub_link_esp32::Control;
config.heartbeat_interval_secs = 120; // under NervesHub's 3-minute socket timeout
let outcome = agent.run_session_until(|| {
if !on_external_power() {
Control::Leave
} else if readings_are_due() {
refresh_readings(); // the health provider reports these
Control::ReportHealth
} else {
Control::Stay
}
});Control::ReportHealth sends a report from the health provider now, rather
than when NervesHub next asks, which it does only hourly unless someone has the
device's page open. As with run_session, nothing is retried.
Most of that handshake is the server's certificates, key exchange and, from NervesCloud, a certificate request listing every CA it trusts: about 15 KB down and three round trips. A resumed session is a ServerHello and a Finished, 143 bytes and one round trip. On an ESP32-S3 over LTE-M that took a report from 31.5 KB and an 11.6 s connect to 11.3 KB and 2.1 s.
Reconnects within a boot resume on their own. Across a deep sleep the session has to be kept somewhere that survives it, which is RTC memory, and handed back:
use nerves_hub_link_esp32::TlsSession;
#[link_section = ".rtc.data"]
static mut SESSION: [u8; 256] = [0; 256];
// ... and its length, beside it
config.tls_session = TlsSession::restore(saved_bytes);
let session = config.tls_session.clone(); // the same slot, not a copy
let outcome = esp::agent_with(config, policy)?.run_session(window);
if let Some(bytes) = session.saved() {
// copy into RTC memory for the next wake
}It needs, in sdkconfig.defaults:
CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS=y
# CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is not set
The first lets esp-tls offer a session at all. The second keeps the server's certificate out of the saved session, which is then about 150 bytes rather than 1.3 KB; nothing reads the certificate after the handshake. The saved bytes hold the session's master secret, so keep them in RTC memory, not flash or a log.
ESP-IDF builds without TLS 1.3, so a device speaks 1.2 to any server. To allow
1.3, in sdkconfig.defaults:
CONFIG_MBEDTLS_SSL_PROTO_TLS1_3=y
CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y
ESP-IDF won't build TLS 1.3 without the second line. That undoes the saving above for TLS 1.2: a saved 1.2 session carries the server's certificate again. A saved 1.3 session never does, since mbedTLS writes only the resumption secret and the server's ticket, so its size depends on that ticket.
Keeping the peer certificate costs memory while connected, too: every open TLS connection holds the certificate chain the server sent, parsed, for as long as it is open. That is a few KiB a connection, and an update has two open, the websocket and the download.
With both lines, a device asks for 1.3 and falls back to 1.2 if the server
doesn't speak it. Config::tls_version can hold it to one version.
TlsVersion::Tls13 on a build without TLS 1.3 refuses to connect, where
esp-tls would quietly use 1.2.
Resumption works the same from the application's side. The difference is inside: the server sends a 1.3 ticket after the handshake rather than in it, so it is saved once the first read on the connection has taken it in. A connection that ends before reading anything leaves the session it was offered.
A 1.3 ticket also has an age, which mbedTLS checks before offering it, against a clock that on ESP-IDF restarts at every boot, deep-sleep wakes included. So a saved session holds the ticket's date on the wall clock, which ESP-IDF keeps through deep sleep, and goes back onto mbedTLS's clock when it is offered. Without that, a session saved before a sleep usually looked as if it came from the future, and mbedTLS dropped it: a full handshake on most reports.
Nothing is lost when the server has forgotten the session -- restarted, evicted it, or is another node behind a load balancer: the handshake is a full one and its session replaces the old.
Five things, none of which this crate can do for you.
1. Cargo.toml: esp-idf-sys reads package.metadata only from the root
package of a build, so this is not inherited from the dependency:
[dependencies]
nerves-hub-link-esp32 = "0.1"
[[package.metadata.esp-idf-sys.extra_components]]
remote_component = { name = "espressif/esp_websocket_client", version = "^1.0" }
[[package.metadata.esp-idf-sys.extra_components]]
remote_component = { name = "espressif/esp_delta_ota", version = "^1.1" }
bindings_header = "include/delta_ota_bindings.h"2. sdkconfig.defaults:
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_ESP_MAIN_TASK_STACK_SIZE=10000
CONFIG_APP_PROJECT_VER_FROM_CONFIG=y
CONFIG_APP_PROJECT_VER="1.0.0"
CONFIG_ESP_WS_CLIENT_ENABLE_DYNAMIC_BUFFER=y
The version is not optional. NervesHub reads it from esp_app_desc_t, at
upload and from the running device, and it has to parse as SemVer. Left unset,
ESP-IDF fills it from git describe, which does not. A device reporting an
unparseable version has no firmware metadata server-side, so it can never match
a deployment while looking perfectly healthy.
CONFIG_ESP_WS_CLIENT_ENABLE_DYNAMIC_BUFFER is a saving rather than a
requirement. Without it the websocket client holds its 4 KiB send and receive
buffers for as long as it is connected; with it they exist only while a
message goes through, which gives back 8 KiB nearly all the time, firmware
downloads included, when the heap is at its tightest.
mbedTLS has a bigger saving of the same kind, not yet tried with this crate.
Each TLS connection holds a 16 KiB receive buffer and a 4 KiB send buffer for
as long as it is open, and an update has two open. CONFIG_MBEDTLS_DYNAMIC_BUFFER=y
allocates them only while a record goes through, which would give back most of
the idle websocket's 20 KiB. The download would pay for it: a buffer the size
of each record it receives, up to 16 KiB and in one piece, allocated and freed
again record by record. Measure before turning it on.
3. partitions.csv: two app slots, otadata, and a certs partition.
Copy the one in this repo. Both app slots must be identical in size and large
enough for the biggest image you will ever ship; an image that outgrows its slot
fails on the device, in the field.
4. The project name in the image: NervesHub matches esp_app_desc_t's
project_name against the product an image is uploaded to. ESP-IDF takes that
field from the CMake project name, which esp-idf-sys hardcodes to
libespidf, so every Rust image claims to be a product called libespidf and
no upload matches anything. There is no setting for it. Patch the ELF after
building and before elf2image:
scripts/set_app_desc.py --project-name MyProduct target/<target>/release/my-appOn the ELF, not the .bin: the image's SHA-256 is computed during
elf2image, so patching afterwards invalidates it and the bootloader refuses
to start the image.
5. A device identity: either scheme works; the device needs one of them.
For shared secrets, nothing is provisioned: the identifier and secret are configuration, and a product-wide secret registers unknown devices on first connection. That is the quickest way to a working bench.
For mTLS, a device certificate in NVS. NervesHub identifies a device by its
client certificate, which it knows by the SHA-1 fingerprint of its DER. A
certificate gets on file in one of two ways, and
nh does the identity half of both.
Signed by a CA registered to your organization, the recommended route. NervesHub checks a certificate it hasn't seen against the organization's CAs, so nothing is uploaded per device, and with Just In Time Provisioning the device itself is created on its first connection. Once per organization, make a CA and register it:
nh ca generate --uploadThat writes the CA's key and certificate to ~/.nh/ca/<org>/, named by the
time it was made (2026-10-21-09-15-02-cert.pem, say), and proves to NervesHub
that you hold the key. Whoever holds that key can add devices to your
organization, so keep it on the machine that provisions them. Then open the CA
on the organization's Certificate Authorities page, turn on Just In Time
Provisioning, and choose the product new devices join, with a description and
tags to copy to each of them (the page requires both for now). nh has no flag
for that.
Then, for each device:
nh device certificates generate my-device-001 --ca 2026-10-21-09-15-02--ca takes the time the CA's files are named by. That generates a secp256r1
key and a client certificate signed by the CA, with the device identifier as
the common name. Nothing is uploaded: on the device's first connection,
NervesHub checks the certificate against the CA, creates the device in the
JITP product and pins the certificate. Without JITP the device has to exist in
NervesHub first; its first connection then registers the certificate.
Self-signed, with no CA to look after. NervesHub has nothing to check a self-signed certificate against, so it has to be uploaded for a device that already exists, before that device connects:
nh device create my-device-001
nh device certificates generate my-device-001 --self-signed --uploadThat generates a secp256r1 key and a self-signed client certificate with the device identifier as the common name, and registers the certificate with the device. NervesHub accepts an uploaded self-signed certificate once it has nerves_hub_web#3184; without that, it refuses a self-signed certificate in the TLS handshake, uploaded or not.
Either way, the key and certificate land in ~/.nh/certificates/<org>/. Write
them into the certs partition and flash. scripts/provision.sh does this, or
by hand:
cat > nvs.csv <<'CSV'
key,type,encoding,value
nerves_hub,namespace,,
device.crt,file,binary,device.crt
device.key,file,binary,device.key
CSV
nvs_partition_gen.py generate nvs.csv certs.bin 0x10000
esptool.py --port /dev/tty.usbmodem write_flash 0x3E0000 certs.binBoth tools ship with ESP-IDF. The 0x3E0000 offset is the certs partition in
partitions.csv. Change it if you change the table.
The NVS partition, namespace and key names are exported from identity
(PARTITION, NAMESPACE, CERTIFICATE_KEY, PRIVATE_KEY_KEY) and are
deliberately visible off-device, so tooling that writes the image can reference
them rather than repeat the strings. A drift there surfaces as a TLS handshake
failure that says nothing about a renamed key.
In production, provision at manufacture and enable NVS encryption: the private key is otherwise readable by anyone who can dump flash.
NervesHub reads either JSON or msgpack from a device, chosen by the socket URL. JSON is the default because every NervesHub has it; msgpack, from July 2026, is smaller:
config.serializer = nerves_hub_link_esp32::Serializer::MsgPack;On frames shaped like a cellular water monitor's it is 13% smaller on the join and 14% on a batch of log lines, but only 3% on a health report, whose floats take eight bytes either way: about 400 bytes a report in all. Worth having on a link billed by the byte; not worth more than one line of configuration.
Both of NervesHub's schemes, as configuration on the same websocket client: a client certificate handed to mbedTLS, or shared-secret headers on the HTTP upgrade. Which one an organization uses is its choice.
Credentials::client_certificate(cert_pem, key_pem)? // mTLS
Credentials::shared_secret(identifier, key, secret) // HMAC headersThe shared-secret path reproduces Plug.Crypto's signed-token format: PBKDF2
with a negotiated digest, iteration count and key length, then
MessageVerifier's encoding, over a multi-line salt that binds the headers.
It is checked byte for byte against vectors generated by the Elixir side, in
shared_secret.rs, because getting it subtly wrong fails in a way that looks
exactly like a wrong secret.
The clock has to be right either way. A signature is only valid inside the server's window, 90 seconds by default, and TLS certificate dates cannot be checked by a device that believes it is 1970. Run SNTP before connecting; a device that does not will fail to join in a way that reads as bad credentials.
Keep certificates in an NVS partition, encrypted in production. Compiling them into the image gives an entire fleet one identity.
ota.rs calls the six esp_ota_* C functions directly rather than using the
esp-ota crate. No published version of esp-ota works with esp-idf-svc
0.53: the newest (0.2.2) requires esp-idf-sys ^0.36, esp-idf-svc 0.53
pulls 0.38, and esp-idf-sys is a links = "esp_idf" crate so only one copy
may exist in the graph. Pinning the whole stack back to keep a thin wrapper was
the worse trade.
ESP-IDF's rollback protocol and NervesHub's firmware_validated work in harmony.
- Write the image to the inactive slot, mark it bootable, reboot.
- The new image comes up in
PENDING_VERIFY. - It must call
esp_ota_mark_app_valid_cancel_rollback(), or the bootloader reverts on the next reset.
This crate confirms only after rejoining NervesHub. Confirming at startup would cancel the rollback for an image that cannot reach the server, the exact failure rollback exists to catch.
The bootloader marks an image that reset before confirming itself ABORTED
and boots its predecessor. That predecessor then says so in its join
(firmware_auto_revert_detected) and logs a warning, for as long as the
failed image is still in the other slot.
NervesHub sends a patch rather than a whole image where it has one. On the firmware this project builds, a patch runs from 1.6% of the image for a version bump to 7.3% for a release's worth of changes.
Nothing to configure on the device. An update says nothing about which it is:
firmware_url looks the same either way and the checksum is of whatever was
sent. So the agent reads the first byte. An application image opens with the
magic the bootloader insists on, and anything else is treated as a patch. A
patch is fed to esp_delta_ota, which reads the running slot and writes the
rebuilt image into the inactive one.
The rebuild is byte for byte, which is what makes this work under Secure Boot: the signature block travels inside the image, so the device verifies the same bytes it would have downloaded. Nothing is re-signed on the device.
A patch that does not rebuild the expected image is caught by esp_ota_end
before the boot partition moves, and reported as a failed update. The device
stays on the firmware it was running.
NervesHub names each attempt at an update with an update_id, sent with the
update. The agent sends it back as update_id on every update_progress and
status_update about that update: completed, failed, and the ignored or
rescheduled an UpdateHandler decides on. NervesHub applies each report to
the attempt it names, and ignores one about an attempt it has moved on from
rather than applying it to the next.
A NervesHub from before update IDs sends none. The reports then go without the key, as they always have, and NervesHub applies them to whatever update is in progress.
While the device is still working on an update, a join also carries it as
current_update_id, next to currently_downloading_uuid, which older servers
read. The agent itself never joins in that window: an update downloads and
installs inside the session that received it, and the device reboots once it
is applied. It matters to an application driving Link across reconnects,
which calls Link::set_update_id when it takes an update, keeps it set until
the device reboots into it (completed included), and clears it once the
update fails.
Off by default, each one asked for individually, and attached only if the product allows it:
use nerves_hub_link_esp32::extensions::Enabled;
use nerves_hub_link_esp32::{health::EspHealth, logging, whenwhere::Whenwhere};
config.extensions = Enabled::none().health().geo().logging();
let logs = logging::install(log::LevelFilter::Info, log::Level::Info);
esp::agent_with(config, AlwaysApply)?
.with_health(EspHealth::new())
.with_location(Whenwhere::new())
.with_logs(logs)
.on_identify(|| blink())
.run()?;- health reports memory, WiFi RSSI and the reason for the last reset. The
memory is internal RAM alone, here and in the console's
heap: PSRAM is not counted, since it is not what a device runs out of. - geo answers with a GeoIP position from the Nerves project's
whenwhereservice, the same onenerves_hub_linkuses. Supply your ownLocationProviderfor a GNSS fix. - logging sends what the
logcrate is given.logging::installreplacesEspLogger::initialize_default()and keeps writing to the console. It does not capture ESP-IDF's own C logging, which never reaches thelogcrate. Where NervesHub has logging 0.1.0 the lines go in batches, a second's worth per message and a sleeping device's whole backlog in the first; elsewhere one line per message, four a second.
The extensions channel is joined when NervesHub sends extensions:get, which
names the versions of each extension it has, and the join declares the newest
of each that both sides speak. A NervesHub that never asks still gets a join,
five seconds after the device's, at the versions every NervesHub has.
on_identify runs when an operator presses Identify in NervesHub. Reboot needs
nothing: the agent answers it and restarts.
NervesHub can attach a terminal to a device. On Nerves the far end is an IEx session, which is why it works there: something is already running that takes text in and gives text back. An ESP32 has nothing equivalent, so this puts a fixed set of commands on the far end instead.
esp32> partitions
running ota_0 at 0x020000 1966080 bytes valid
next ota_1 at 0x200000 1966080 bytes ABORTED, rolled back: never confirmed
esp32> heap
total 338384
free 198224
min free 161136 low-water mark
largest 110592 largest single block
Off unless asked for, because it is a remote command surface:
esp::agent_with(config, AlwaysApply)?
.with_console()
.command("relay", "on|off — drive the relay", move |args, out| {
match args {
["on"] => writeln!(out, "relay on")?,
_ => writeln!(out, "usage: relay on|off")?,
}
Ok(())
})
.run()?;It brings help, info, uptime, reboot, log, and on a device also
heap, wifi, partitions and reset-reason. Each answers from something
the agent already reads, which is the rule for adding one: a command needing
new plumbing is a feature wearing a command's clothes.
Two earn their place beyond convenience. partitions separates "this device is
on old firmware" from "this device tried the new firmware and the bootloader
threw it out", which is otherwise only visible over a serial cable. log debug
raises what is forwarded to NervesHub and log info lowers it again, which is
unaffordable across a fleet and free on one device while someone watches it.
Every command is a Rust function compiled into the image. There is no eval and no way to reach anything the firmware did not ship with. That is the security property, and it is why the vocabulary stays fixed even when a general escape hatch would be convenient. File transfers, which are part of the channel, are declined out loud rather than ignored.
- Resumable downloads: NervesHub sends
partials_checksumsso an interrupted transfer can be resumed and verified chunk-wise. Here one fails and is reported, and NervesHub's next offer starts it from zero. Only a download that never started is retried on the device. - Updating the VM or bootloader: application partition only.
- Support scripts (
scripts/runon thedevicechannel), which ask a device to run supplied code. There is no interpreter here to run it in, and adding one would undo the property that makes the console safe. - Local shell and network identity extensions: health, geo and logging are implemented; these two are not.
src/
agent.rs the run loop (trait: Platform)
link.rs the channel state machine (trait: Transport)
install.rs download -> verify -> commit (traits: HttpStream, ImageSink)
message.rs Phoenix v2 frames, topics, event names
inbound.rs the socket's pieces -> whole messages, for transport.rs
metadata.rs esp_app_desc_t -> join payload
update.rs update payload, decisions, progress throttling
checksum.rs SHA-256 in NervesHub's format
config.rs connection config, credentials, backoff
extensions.rs the extensions channel (traits: LocationProvider, HealthProvider)
logging.rs a log::Log that keeps a copy for NervesHub
shared_secret.rs Plug.Crypto signed tokens, checked against Elixir vectors
esp.rs EspPlatform + the one-call entry point
transport.rs esp_websocket_client (impl Transport)
tls.rs esp-tls under the websocket, with a session the app can keep
tls_session.rs the session, between connections and across sleep
http.rs EspHttpConnection (impl HttpStream)
ota.rs esp_ota + esp_delta_ota (impl ImageSink)
health.rs memory, RSSI, reset reason (impl HealthProvider)
whenwhere.rs GeoIP position (impl LocationProvider)
identity.rs client certificate from NVS
The top group is host-testable; the bottom group is the device. Each seam is a
trait, so the loop runs against a fake platform, link.rs against a fake
socket, and install.rs against a fake network and fake flash. The frames, the
sequencing and the install decisions are the parts most likely to be wrong; the
sockets are not.
That is also why install.rs, not ota.rs, owns checksum verification and
the decision to commit. "Never make a corrupt image bootable" is a rule worth a
test, and it can only have one on the host.
cargo test # host: protocol, install, extensions, logging
cargo +esp check-esp32 # device type-check, no linking
cargo +esp esp32 --example local # device build of the bench exampleThe host tests need no ESP toolchain, which is the point: the frames, the sequencing and the install decisions are the parts most likely to be wrong.
examples/local.rs is the one that has actually been run. It brings WiFi up
itself, authenticates with a shared secret, and enables health, geo and
logging, so there is nothing to provision first. Copy
local_config.rs.template to local_config.rs in the crate root and fill it
in. basic.rs and advanced.rs are the mTLS shapes and have not been run.
docs/esp_idf_support.md in the NervesHub repository, for the server side and
the full list of what is not supported yet.