OTA Guide

Overview

ameba_ota downloads a new application image over a caller-supplied byte stream and programs it into the inactive A/B slot. It covers only this download-and-program loop: slot selection, signature verification, and boot-time selection between OTA1/OTA2 remain the bootloader’s job. This crate never touches boot.bin — it writes an image and leaves the manifest Pattern field unset until the write is verified, so the bootloader keeps booting the current image until a commit actually lands.

Note

Before using OTA, see Flash Layout for how the OTA1/OTA2 slots are partitioned, and OTA Guide for the bootloader-side selection and signature-verification mechanism this crate relies on.

Scope and Limitations

ameba_ota deliberately keeps a narrow scope:

  • Application image only. The sub-header’s ImgID is checked against the application image ID, and a bootloader image is rejected with OtaError::UnsupportedImageId rather than programmed.

  • One image per file. A file declaring more than one image is rejected up front with OtaError::MultiImageUnsupported — this project’s images are built and shipped one at a time.

  • NOR flash only. OtaWriter erases and writes at sector granularity, and it has no NAND page-buffering or bad-block handling.

  • No image authenticity check in this crate. Only a plain wrapping-sum checksum against the sub-header’s Checksum field is verified before commit. Tamper resistance comes entirely from the bootloader’s own ECC signature check on the next boot — a corrupted or malicious image still passes this crate’s checksum if the checksum was recomputed to match, but fails to boot.

Architecture

Transport (trait)          byte source: HTTP, filesystem, or a caller-driven feed
     │
     ▼
OtaSession::run()          core.rs   — parses file/sub headers, streams the body
     │
     ▼
OtaWriter                  storage.rs — NOR erase/write, checksum verify, manifest commit
     │
     ▼
FlashStorage (ameba-storage)

slot determines which of OTA1/OTA2 is currently running (by reading the bootloader’s boot-time remap snapshot) and targets the other one, layout holds the four slots’ fixed flash addresses and sizes, and manifest parses the file/sub-header/manifest byte layouts that precede an image’s body.

Flash Storage (ameba-storage)

ameba-storage exposes two API tiers on top of the same FlashStorage handle; ameba_ota::OtaWriter uses only the strict tier, since it already buffers a full sector before every write:

  • Strict, alignment-checked ( read_nor / write_nor / erase ). Offset/length must be 4-byte aligned for read/write and 4 KiB aligned for erase, and the target region must already be erased before write_nor. This tier implements embedded_storage::nor_flash::NorFlash / ReadNorFlash.

  • Arbitrary alignment, Read-Modify-Write ( read / write ). Accepts any offset/length by transparently reading the containing sector, patching it in a stack buffer, erasing, and writing it back — convenient for application code that does not manage its own sector buffering, at the cost of an implicit erase on every call. ameba_ota does not use this path.

Flash::steal() (used in the Quick Start below) is unsafe because exactly one Flash token must exist for the process lifetime — it is the caller’s responsibility not to construct a second one. A lower-level, unchecked ll module also exists (raw spiflash_read/spiflash_write/erase functions, no alignment or bounds checks, no locking) for bootloader- or OTA-writer-style code that manages its own preconditions; ameba_ota does not use it either, since the sector-buffered strict tier above already covers its needs.

Quick Start

use ameba_ota::core::{OTA_BUF_SIZE, OtaSession};
use ameba_ota::storage::OtaWriteBuf;
use ameba_storage::{Flash, FlashStorage};
...
static OTA_BUF: StaticCell<[u8; OTA_BUF_SIZE]> = StaticCell::new();
static WRITE_BUF: StaticCell<OtaWriteBuf> = StaticCell::new();
...
let ota_buf = OTA_BUF.init([0u8; OTA_BUF_SIZE]);
let write_buf = WRITE_BUF.init([0u8; ameba_ota::storage::CHUNK_LEN]);
...
let mut flash = FlashStorage::new(unsafe { Flash::steal() });
let session = OtaSession::new(transport);

match session.run(&mut flash, ota_buf, write_buf).await {
    Ok(report) => {
        println!(
            "[ota] programmed: fw_ver={} img_id={} body_len={} bytes",
            report.fw_ver, report.img_id as u32, report.body_len
        );
        println!("[PASS] ota-http: image committed to inactive slot, resetting");
        // Give LOGUART time to flush before the reset cuts it off.
        Timer::after_millis(20).await;
        cortex_m::peripheral::SCB::sys_reset();
    }
    Err(e) => {
        println!("[FAIL] ota-http: {:?}", e);
    }
}

transport is anything implementing ameba_ota::transport::Transport, e.g. the HTTP transport below. On Ok the slot is committed and the reset lets the bootloader pick the new image; on Err the slot is left uncommitted and the running image is untouched.

ota_buf and write_buf are placed in static items rather than as locals: together they are several KB, which would otherwise inflate the calling async task’s future.

Transport

OtaSession never talks to a network stack or filesystem directly — it only pulls bytes from whatever implements the Transport trait:

pub trait Transport {
    /// Transport-specific failure (socket error, HTTP status, short read…).
    type Error;
    ...
    fn read(
        &mut self,
        buf: &mut [u8],
    ) -> impl core::future::Future<Output = Result<usize, Self::Error>>;
}

read returns Ok(0) at end of stream and must not busy-wait — it is the point where an async transport yields to the executor while the next packet arrives. Implement it directly to feed OTA bytes from a filesystem, BLE link, or any caller-driven byte source.

HTTP Transport

Enable the http-reqwless feature to get a ready-made HTTP GET transport built on reqwless:

ameba-ota = { path = "../../ameba-ota", features = ["http-reqwless"] }
use ameba_ota::http::{self, HEADER_BUF_SIZE, LiteralDns};
...
let tcp_client = embassy_net::tcp::client::TcpClient::new(stack, tcp_state);
let dns = LiteralDns;
let mut client = reqwless::client::HttpClient::new(&tcp_client, &dns);
...
let mut resource =
    match embassy_time::with_timeout(Duration::from_secs(15), client.resource(url.as_str()))
        .await
    {
        Ok(Ok(r)) => r,
        ...
    };

let transport = match embassy_time::with_timeout(
    Duration::from_secs(15),
    http::http_get(&mut resource, OTA_PATH, header_buf),
)
.await
{
    Ok(Ok(t)) => t,
    ...
};

The excerpt is from examples/ota-http, where tcp_state and header_buf come from static StaticCell items, and url holds the server’s base URL (http://<OTA_SERVER_IP>:<OTA_SERVER_PORT>). Both the connect and the GET are wrapped in a 15 s with_timeout: a TCP SYN to an unreachable server retransmits for minutes with no error, so without a bound the update would hang with no verdict.

This transport has three deliberate restrictions:

  • No TLS. reqwless is taken with default-features = false, dropping embedded-tls. Transport confidentiality is not what makes an update safe here — the bootloader’s ECC signature check on next boot is what rejects a tampered image, not the download channel.

  • No redirects. reqwless does not follow 3xx responses, and a redirecting URL surfaces as HttpError::Status instead of being chased silently. Point the updater at a direct URL.

  • No DNS. LiteralDns only accepts an IPv4 literal host — pulling in a real resolver would mean another socket and another failure mode on the update path. A hostname URL fails immediately with HttpError::NotAnIpLiteral.

The response status is checked inside http_get before it returns, so a 404 fails there rather than being programmed into flash as if it were firmware.

Application Examples

The Rust SDK provides one example project at ota-http, which downloads an image from a plain-HTTP server on the LAN and programs it into the inactive slot:

  1. Enable the system watchdog (5 s timeout) and start a task that refreshes it every 500 ms (see Watchdog During OTA below).

  2. Connect to Wi-Fi (WPA2-PSK) and wait for DHCP.

  3. GET the image over HTTP using the http-reqwless transport.

  4. Stream the response body through OtaSession::run into the inactive slot.

  5. On success, commit the slot and reset so the bootloader boots the new image. On failure, the slot is left uncommitted and the board idles — the currently running image is never affected.

Before building, set these constants at the top of src/main.rs:

Constant

Meaning

WIFI_SSID, WIFI_PASSWORD

2.4 GHz WPA2-PSK network to join

OTA_SERVER_IP

HTTP server address, must be an IPv4 literal

OTA_SERVER_PORT

HTTP server port

OTA_PATH

Path of the OTA image on that server

REQUEST_OTA_UPDATE

Whether this boot attempts an update at all

BUILD_MARKER

Printed at startup to tell which image is running

Running an Update

The image to download is the ota_all.bin that cargo xtask build produces next to app.bin. Each image’s version is set by IMG_VER_MAJOR and IMG_VER_MINOR in ameba-flash/src/pack.rs. At every boot the bootloader compares the versions of the two slots and boots the higher one (on a tie it picks the first slot), so the downloaded image needs a higher version than the running one; otherwise the update succeeds but the board keeps booting the old image.

  1. Set the Wi-Fi and server constants, keep REQUEST_OTA_UPDATE = true, then build and flash this image. It is the one that performs the update.

  2. Build the image to download: set REQUEST_OTA_UPDATE = false so it does not start another update on its first boot, change BUILD_MARKER, and raise IMG_VER_MINOR. Copy the resulting build/rtl8721f/ota_all.bin to a directory on the server host. Do not flash this build.

  3. Serve that directory over HTTP, for example:

    $ python3 -m http.server 8000
    

    OTA_SERVER_PORT and OTA_PATH in the image from step 1 must match it (here port 8000 and path /ota_all.bin).

  4. Reset the board. After the download it resets on its own and prints the new BUILD_MARKER.

Expected output of the running image, with an update ([wifi] join_status=... lines omitted):

[build] <build timestamp>
[marker] A (currently running)
[wdg] enabled, timeout=5000ms
[wifi] on: 0
[wifi] connecting to "<ssid>" ...
[wifi] connect returned: 0
[NET] WiFi connected
[NET] MAC: xx:xx:xx:xx:xx:xx
[NET] waiting for DHCP ...
[NET] DHCP: IP=192.168.x.x
[ota] GET http://192.168.x.y:8000/ota_all.bin
[ota] programmed: fw_ver=... img_id=... body_len=... bytes
[PASS] ota-http: image committed to inactive slot, resetting

Expected output of the downloaded image, after the reset:

[build] <build timestamp>
[marker] <your new BUILD_MARKER>
[wdg] enabled, timeout=5000ms
[ota] REQUEST_OTA_UPDATE=false, skipping OTA this boot

fw_ver is the version field of the OTA header and always reads 4294967295 (0xFFFFFFFF); it is not the image version. The version that the bootloader reports as IMG2 BOOT from OTA 2, Version: ... comes from the image itself. The Wi-Fi core and driver also print debug lines such as [api], [blk_api] and [WLAN-A] in between.

If nothing is listening on the server port, the connection is refused:

[FAIL] ota-http: connect failed: Network(ConnectionReset)

If the server host cannot be reached from this network, the connection attempt times out instead:

[FAIL] ota-http: connect to http://192.168.x.y:8000 timed out after 15s (server unreachable from this network?)

In both cases the inactive slot is not committed and the running image stays selected.

Watchdog During OTA

An OTA download is the longest uninterruptible stretch of work this firmware does, and it is worth sizing a watchdog refresh interval around it explicitly rather than by trial and error. Every flash erase/write call takes a cross-core IPC hardware lock and disables interrupts for its duration — buffering a full sector before each write (see ameba_ota::storage::CHUNK_LEN) keeps that stretch to roughly 7 ms worst case on hardware (RTL8721F, 100 MHz flash clock: sector erase 0.9–1.4 ms, sector write 4.8–7.1 ms). A refresh task on a period comfortably above that — the example uses 500 ms against a 5 s watchdog timeout — cannot be starved past its deadline by flash access alone. Programming small chunks instead of a full sector multiplies the lock count without shortening any single stretch, and only makes the starvation risk worse.

The watchdog must also be enabled before any OTA-triggering gate, not after: enabling it is irreversible in software, so an image reached by OTA finds it already running and must start refreshing from its very first boot, whether or not that boot does any OTA work itself. Gating watchdog setup behind a “should I OTA this boot” check instead produces a reboot loop — the freshly downloaded image parks at the gate, never feeds, and is reset by the watchdog it never got the chance to arm.