Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Library

The crate nanoflash is the library behind the command and the browser package. It is no_std with alloc, and it builds for thumbv7em-none-eabihf and wasm32-unknown-unknown with every no_std feature. The API documentation is on docs.rs. Add the crate from crates.io:

[dependencies]
nanoflash = { version = "0.1", features = ["toml", "flash", "espressif", "native"] }

Features

No feature is enabled by default. Every feature only adds code.

FeatureEnablesNeeds std
tomlReading layout files and board manifests from TOML.no
jsonReading board manifests from JSON, and esp-web-tools manifests.no
table-espressifThe Espressif partition table writer.no
table-mbrThe MBR writer.no
table-linkerThe linker regions and Rust constants writer.no
flashThe backend interface, its errors and progress events, image preparation and checks, shared by every protocol. Implies toml and table-espressif.no
espressifThe Espressif ROM loader backend. Implies flash.no
sambaThe SAM-BA backend of the Arduino Nano 33 BLE and SAMD21 boards. Implies flash.no
avrThe STK500v1, STK500v2 and AVR109 backends of Arduino’s AVR boards. Implies flash.no
elfReading the loadable segments of ELF images, over the object crate. Implies flash.no
testingTranscript replay and recording transports, and MemorySource.no
nativeThe host serial port over the serialport crate, and port listing.yes
webThe serial port of the browser over Web Serial, through hand-written wasm-bindgen bindings, without web-sys. No web_sys_unstable_apis flag is needed downstream.no
buildConstants and linker regions for the build.rs of a firmware. Implies toml, json, table-linker and cargo.yes
cargoThe board that [package.metadata.nanoflash] of a Cargo.toml names. Implies toml.yes

A function that needs a missing feature refuses with an error instead of failing to compile in two places: Backends::new returns protocol-not-enabled for a protocol whose feature is off, and image preparation returns elf-not-enabled for an ELF image without the elf feature.

Modules

ModuleFeatureRole
layoutLayout files, their resolution and report.
tabletable-*The table writers.
quantitySizes and offsets as integers, hexadecimal or numbers with a binary unit.
manifestBoard manifests (TOML, JSON) and esp-web-tools manifests (json).
transportThe SerialPort and PortProvider traits, DeviceFilter, transport errors.
backend, errorflashThe Backend trait, progress events, the errors and their class.
flashflashBoard selection, image preparation and checks (Intel HEX for every protocol, ELF decoded into flat segments or built into Espressif application images by the image source), the flash and detect orchestration, image_build.
espressifespressifThe ROM loader backend: SLIP, commands, chip table, resets, writes.
touchsamba or avrThe 1200-baud touch that SAM-BA and AVR109 share, and the bootloader device to wait for after it.
sambasambaThe SAM-BA backend of Arduino’s bootloaders: the ASCII commands with Arduino’s X, Y and Z, the chip families, writes and CRC-16 checks.
avravrThe AVR backend: the chip table, the commands of the STK500v1 (Optiboot, ATmegaBOOT), STK500v2 (Mega 2560) and AVR109 (Caterina) bootloaders, page writes and read-back checks, and the erase order of the Mega 2560.
nativenativeThe host serial port over serialport.
webwebThe serial port of the browser over Web Serial, and the provider that finds a device again among the granted ports.
testingtestingTranscript replay and recording, MemorySource.
buildbuildConstants and linker regions for a build.rs, from a layout file or from the board of the package, and a whole memory.x. See Build and cargo features.
cargocargoFinding the package from the Cargo variables or the working directory, reading the metadata, the layout of a board manifest.

Transport traits

#![allow(unused)]
fn main() {
pub trait SerialPort {
    /// Waits up to `timeout`; returns 0 when nothing arrived.
    async fn read(&mut self, buffer: &mut [u8], timeout: Duration) -> Result<usize, TransportError>;
    async fn write(&mut self, data: &[u8]) -> Result<(), TransportError>;
    async fn set_baud_rate(&mut self, baud_rate: u32) -> Result<(), TransportError>;
    async fn set_signals(&mut self, signals: Signals) -> Result<(), TransportError>; // DTR, RTS
    async fn sleep(&mut self, duration: Duration);
    fn identity(&self) -> Option<UsbIdentity>; // vendor, product, serial number
}

/// Finds or opens a port again, for resets that change the USB device (1200-baud touch,
/// USB-Serial-JTAG).
pub trait PortProvider {
    type Port: SerialPort;
    async fn open(&mut self, filter: &DeviceFilter, baud_rate: u32, timeout: Duration) -> Result<Self::Port, TransportError>;
    /// How long to wait for Caterina after a touch; 7 s by default.
    fn caterina_reopen_timeout(&self) -> Duration;
}
}

Public traits with async fn carry #[allow(async_fn_in_trait)] and have no Send bound, because browser APIs are single-threaded.

Backend trait

#![allow(unused)]
fn main() {
pub trait Backend {
    async fn connect(&mut self) -> Result<ChipInformation, Error>; // reset into the bootloader, detect
    async fn erase(&mut self, region: Region, progress: &mut dyn Progress) -> Result<(), Error>;
    async fn write(&mut self, segments: &[Segment<'_>], progress: &mut dyn Progress) -> Result<(), Error>;
    async fn verify(&mut self, segments: &[Segment<'_>], progress: &mut dyn Progress) -> Result<(), Error>;
    async fn reset_to_application(&mut self) -> Result<(), Error>;
    /// The whole flash in the order that `flash` sends it, before the first erase; `Ok` by default.
    fn check_plan(&self, erase_all: Option<Region>, erases: &[Region], segments: &[Segment<'_>]) -> Result<(), Error>;
}
}

ChipInformation, which connect returns, gives the protocol, the chip, the flash size, the secure download mode, the USB identity, writable_from (the lowest offset that the bootloader writes), writable_to (the end of the flash that the bootloader writes) and erases_to_end.

Hooks of the caller

TraitRole
ImageSourceReads the bytes of an image: files natively, fetch in the browser. With the elf feature, application_image builds the Espressif application image of an ELF file; the default refuses (application-image).
ImageVerifierCalled after the SHA-256 check, for signatures or anything else. () accepts every image.
ProgressReceives the progress events: stage, offset, bytes done and total.

Invariants

  • No panic on any input or device answer: checked arithmetic for every offset and size (u64), no indexing that can fail, no unwrap outside tests, fallible allocation for buffers sized by the input.
  • Every loop that waits on a device is bounded: attempt counts, inactivity timeouts passed to SerialPort::read, byte budgets.
  • #![forbid(unsafe_code)] in every crate.
  • The library is #![no_std] with extern crate alloc. Only the build, cargo and native features enable std.
  • Features only add code. default = []. A function that needs a missing feature returns an error (for example ProtocolNotEnabled).