nanoflash 0.1.0

Lay out the flash of ESP32 and Arduino boards and write firmware to them through their bootloaders, natively or in the browser over Web Serial.
Documentation
//! What every flashing backend offers: connect, erase, write, verify and reset, with progress.

use alloc::string::String;
use alloc::vec::Vec;
use core::convert::Infallible;
use core::marker::PhantomData;

use serde::Serialize;

#[cfg(feature = "avr")]
use crate::avr::{AvrBackend, AvrOptions};
use crate::error::Error;
#[cfg(feature = "espressif")]
use crate::espressif::{EspressifBackend, EspressifOptions};
use crate::manifest::{Protocol, ResetSequence};
#[cfg(feature = "samba")]
use crate::samba::{SambaBackend, SambaOptions};
use crate::transport::{DeviceFilter, PortProvider, UsbIdentity};

/// One image to write: its name for messages, where it goes and its bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Segment<'a> {
    /// The name of the image, for messages and progress.
    pub label: &'a str,
    /// The flash offset of its first byte.
    pub offset: u64,
    /// Its bytes.
    pub data: &'a [u8],
}

/// A range of flash.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Region {
    /// The flash offset of the first byte.
    pub offset: u64,
    /// The number of bytes.
    pub size: u64,
}

/// What a backend is doing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Stage {
    /// Resetting into the bootloader and detecting the chip.
    Connecting,
    /// Erasing flash.
    Erasing,
    /// Writing images.
    Writing,
    /// Checking what was written.
    Verifying,
    /// Resetting into the application.
    Resetting,
}

/// How far a stage has gone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ProgressEvent {
    /// The stage.
    pub stage: Stage,
    /// The flash offset the stage works on.
    pub offset: u64,
    /// The bytes done so far.
    pub done: u64,
    /// The bytes the stage handles in all.
    pub total: u64,
}

/// Receives progress events and messages from a backend.
pub trait Progress {
    /// A stage moved on.
    fn report(&mut self, event: ProgressEvent);

    /// Something the user may want to know, such as a setting the backend could not apply.
    fn message(&mut self, text: &str) {
        let _ = text;
    }
}

impl Progress for () {
    fn report(&mut self, _event: ProgressEvent) {}
}

impl<F: FnMut(ProgressEvent)> Progress for F {
    fn report(&mut self, event: ProgressEvent) {
        self(event);
    }
}

/// What `connect` found out about the board.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ChipInformation {
    /// The protocol the backend speaks.
    pub protocol: Protocol,
    /// The chip, such as `esp32-s3`.
    pub chip: String,
    /// The size of the flash in bytes, when the backend could read it.
    pub flash_size: Option<u64>,
    /// Whether the chip only accepts the commands of the secure download mode.
    pub secure_download_mode: bool,
    /// The USB identity of the port, when it has one.
    pub usb: Option<UsbIdentity>,
    /// The lowest flash offset the bootloader writes, when it protects the flash below it
    /// (SAM-BA bootloaders protect themselves); `None` when the whole flash is writable.
    pub writable_from: Option<u64>,
    /// The end of the flash the bootloader writes, when it sits at the top of the flash (AVR
    /// bootloaders); `None` when the flash up to `flash_size` is writable.
    pub writable_to: Option<u64>,
    /// Whether the bootloader erases from an offset to the end of flash, never a region alone
    /// (the SAMD21's SAM-BA bootloader): every erase must then end at the end of flash.
    pub erases_to_end: bool,
}

/// A flashing backend.
// Futures are not Send: browser APIs are single-threaded
// (docs/src/explanation/design-decisions.md, Constraints).
#[allow(async_fn_in_trait)]
pub trait Backend {
    /// Resets the board into its bootloader and detects the chip.
    async fn connect(&mut self) -> Result<ChipInformation, Error>;

    /// Erases `region`, reporting through `progress` how far it went when the backend can tell.
    async fn erase(&mut self, region: Region, progress: &mut dyn Progress) -> Result<(), Error>;

    /// Writes `segments`, in order.
    async fn write(
        &mut self,
        segments: &[Segment<'_>],
        progress: &mut dyn Progress,
    ) -> Result<(), Error>;

    /// Checks that the flash holds `segments`.
    async fn verify(
        &mut self,
        segments: &[Segment<'_>],
        progress: &mut dyn Progress,
    ) -> Result<(), Error>;

    /// Leaves the bootloader and starts the application.
    async fn reset_to_application(&mut self) -> Result<(), Error>;

    /// Checks, after `connect` and before anything is erased or written, a whole flash as
    /// [`flash`](crate::flash::flash) sends it: `erase_all` (`--erase-all`), then `erases` in
    /// order, then `segments` in order, one `write` each. A backend whose bootloader only takes
    /// erases and writes in some order (the Mega 2560's) refuses here a flash it would refuse
    /// part-way; the others accept any, and check each call again.
    fn check_plan(
        &self,
        erase_all: Option<Region>,
        erases: &[Region],
        segments: &[Segment<'_>],
    ) -> Result<(), Error> {
        let _ = (erase_all, erases, segments);
        Ok(())
    }
}

/// How every backend connects.
#[derive(Debug, Clone, Default)]
pub struct BackendOptions {
    /// The baud rate to switch to after connecting; `None` lets the backend choose. The
    /// Espressif backend then uses 460800 through a USB-to-UART bridge, and 115200 on
    /// USB-Serial-JTAG and the ESP32-C2, which keep 115200 whatever is requested. On STK500v1
    /// and STK500v2, the rate of the bootloader (by default 115200, then 57600 on STK500v1);
    /// ignored on AVR109.
    pub baud_rate: Option<u32>,
    /// The USB identities the board shows in its bootloader, for resets that re-enumerate;
    /// `flash` fills it from the manifest when empty.
    pub bootloader_devices: Vec<DeviceFilter>,
}

/// The backends compiled in, chosen by protocol.
pub enum Backends<'p, P: PortProvider> {
    /// The Espressif ROM loader.
    #[cfg(feature = "espressif")]
    Espressif(EspressifBackend<'p, P>),
    /// Arduino's SAM-BA bootloaders.
    #[cfg(feature = "samba")]
    Samba(SambaBackend<'p, P>),
    /// The STK500v1, STK500v2 and AVR109 bootloaders of Arduino's AVR boards.
    #[cfg(feature = "avr")]
    Avr(AvrBackend<'p, P>),
    /// No backend: keeps the type parameters used when every backend is left out.
    #[doc(hidden)]
    Unavailable(Infallible, PhantomData<&'p mut P>),
}

impl<'p, P: PortProvider> Backends<'p, P> {
    /// The backend of `protocol` over `port`, which `provider` can reopen; `reset` is the reset
    /// sequence of the board, or `None` to let the backend choose from the port.
    pub fn new(
        protocol: Protocol,
        port: P::Port,
        provider: &'p mut P,
        reset: Option<ResetSequence>,
        options: &BackendOptions,
    ) -> Result<Self, Error> {
        match protocol {
            #[cfg(feature = "espressif")]
            Protocol::Espressif => {
                let options = EspressifOptions {
                    baud_rate: options.baud_rate,
                    ..EspressifOptions::default()
                };
                EspressifBackend::new(port, provider, reset, options).map(Backends::Espressif)
            }
            #[cfg(feature = "samba")]
            Protocol::Samba => {
                let options = SambaOptions {
                    bootloader_devices: options.bootloader_devices.clone(),
                    baud_rate: options.baud_rate,
                };
                SambaBackend::new(port, provider, reset, options).map(Backends::Samba)
            }
            #[cfg(feature = "avr")]
            Protocol::Stk500v1 | Protocol::Stk500v2 | Protocol::Avr109 => {
                let options = AvrOptions {
                    baud_rate: options.baud_rate,
                    bootloader_devices: options.bootloader_devices.clone(),
                };
                AvrBackend::new(protocol, port, provider, reset, options).map(Backends::Avr)
            }
            // With every backend compiled in, every protocol is matched above and this arm would
            // be unreachable.
            #[cfg(not(all(feature = "espressif", feature = "samba", feature = "avr")))]
            protocol => {
                let _ = (port, provider, reset, options);
                Err(Error::ProtocolNotEnabled { protocol })
            }
        }
    }

    /// Resets the board into its bootloader and detects the chip, reporting through `progress`
    /// the settings the backend could not apply.
    pub async fn connect(&mut self, progress: &mut dyn Progress) -> Result<ChipInformation, Error> {
        match self {
            #[cfg(feature = "espressif")]
            Backends::Espressif(backend) => backend.connect(progress).await,
            #[cfg(feature = "samba")]
            Backends::Samba(backend) => backend.connect(progress).await,
            #[cfg(feature = "avr")]
            Backends::Avr(backend) => backend.connect(progress).await,
            Backends::Unavailable(never, _) => {
                let _ = progress;
                match *never {}
            }
        }
    }

    /// Resets the board into its bootloader and detects the chip, without changing the baud
    /// rate: enough to tell the chip.
    pub async fn identify(
        &mut self,
        progress: &mut dyn Progress,
    ) -> Result<ChipInformation, Error> {
        match self {
            #[cfg(feature = "espressif")]
            Backends::Espressif(backend) => backend.identify(progress).await,
            // SAM-BA changes no baud rate: identifying is connecting.
            #[cfg(feature = "samba")]
            Backends::Samba(backend) => backend.connect(progress).await,
            // The AVR backend keeps the rate its bootloader answered at: identifying is connecting.
            #[cfg(feature = "avr")]
            Backends::Avr(backend) => backend.connect(progress).await,
            Backends::Unavailable(never, _) => {
                let _ = progress;
                match *never {}
            }
        }
    }
}

impl<P: PortProvider> Backend for Backends<'_, P> {
    async fn connect(&mut self) -> Result<ChipInformation, Error> {
        Backends::connect(self, &mut ()).await
    }

    async fn erase(&mut self, region: Region, progress: &mut dyn Progress) -> Result<(), Error> {
        match self {
            #[cfg(feature = "espressif")]
            Backends::Espressif(backend) => backend.erase(region, progress).await,
            #[cfg(feature = "samba")]
            Backends::Samba(backend) => backend.erase(region, progress).await,
            #[cfg(feature = "avr")]
            Backends::Avr(backend) => backend.erase(region, progress).await,
            Backends::Unavailable(never, _) => {
                let _ = (region, progress);
                match *never {}
            }
        }
    }

    async fn write(
        &mut self,
        segments: &[Segment<'_>],
        progress: &mut dyn Progress,
    ) -> Result<(), Error> {
        match self {
            #[cfg(feature = "espressif")]
            Backends::Espressif(backend) => backend.write(segments, progress).await,
            #[cfg(feature = "samba")]
            Backends::Samba(backend) => backend.write(segments, progress).await,
            #[cfg(feature = "avr")]
            Backends::Avr(backend) => backend.write(segments, progress).await,
            Backends::Unavailable(never, _) => {
                let _ = (segments, progress);
                match *never {}
            }
        }
    }

    async fn verify(
        &mut self,
        segments: &[Segment<'_>],
        progress: &mut dyn Progress,
    ) -> Result<(), Error> {
        match self {
            #[cfg(feature = "espressif")]
            Backends::Espressif(backend) => backend.verify(segments, progress).await,
            #[cfg(feature = "samba")]
            Backends::Samba(backend) => backend.verify(segments, progress).await,
            #[cfg(feature = "avr")]
            Backends::Avr(backend) => backend.verify(segments, progress).await,
            Backends::Unavailable(never, _) => {
                let _ = (segments, progress);
                match *never {}
            }
        }
    }

    async fn reset_to_application(&mut self) -> Result<(), Error> {
        match self {
            #[cfg(feature = "espressif")]
            Backends::Espressif(backend) => backend.reset_to_application().await,
            #[cfg(feature = "samba")]
            Backends::Samba(backend) => backend.reset_to_application().await,
            #[cfg(feature = "avr")]
            Backends::Avr(backend) => backend.reset_to_application().await,
            Backends::Unavailable(never, _) => match *never {},
        }
    }

    fn check_plan(
        &self,
        erase_all: Option<Region>,
        erases: &[Region],
        segments: &[Segment<'_>],
    ) -> Result<(), Error> {
        match self {
            #[cfg(feature = "espressif")]
            Backends::Espressif(backend) => backend.check_plan(erase_all, erases, segments),
            #[cfg(feature = "samba")]
            Backends::Samba(backend) => backend.check_plan(erase_all, erases, segments),
            #[cfg(feature = "avr")]
            Backends::Avr(backend) => backend.check_plan(erase_all, erases, segments),
            Backends::Unavailable(never, _) => {
                let _ = (erase_all, erases, segments);
                match *never {}
            }
        }
    }
}