Skip to main content

waterui_cli/esp32/
platform.rs

1//! ESP32 platform build, flash, emulation, and package utilities.
2//!
3//! The generated harness crate pins its own `esp` Rust toolchain via
4//! `rust-toolchain.toml` and selects the Xtensa target via `.cargo/config.toml`,
5//! so builds simply run `cargo build` inside the harness directory with the
6//! Xtensa GCC and clang library paths exported.
7
8use std::ffi::OsString;
9use std::path::{Path, PathBuf};
10use std::process::Stdio;
11
12use eyre::{Context as _, bail, eyre};
13use smol::fs;
14#[cfg(feature = "esp32")]
15use smol::unblock;
16use tracing::info;
17
18use crate::{
19    build::{BuildOptions, BuildProgress, BuiltTarget},
20    device::Artifact,
21    esp32::{backend::Esp32Backend, chip::Esp32Chip},
22    platform::{PackageOptions, TargetPlatform},
23    project::Project,
24    utils::{command, run_command_os, which},
25};
26
27const ESP32_INIT_HINT: &str = "water run --platform esp32s3";
28
29/// USB vendor IDs commonly found on ESP32 development boards.
30///
31/// `0x303a` is Espressif's native USB (USB-Serial-JTAG); the others are the
32/// `CP210x`, `CH34x`, and FTDI UART bridges used on classic devkits.
33#[cfg(feature = "esp32")]
34const ESP_USB_VENDOR_IDS: [u16; 4] = [0x303a, 0x10c4, 0x1a86, 0x0403];
35
36/// Check if a platform is supported by the ESP32 backend.
37#[must_use]
38pub const fn is_esp32_platform(platform: TargetPlatform) -> bool {
39    matches!(
40        platform,
41        TargetPlatform::Esp32S3 | TargetPlatform::Esp32C3 | TargetPlatform::Esp32P4
42    )
43}
44
45/// Summary of a host serial port for device listing and board auto-detection.
46#[cfg(feature = "esp32")]
47#[derive(Debug, Clone)]
48pub struct SerialPortSummary {
49    /// Host path of the serial port (e.g. `/dev/cu.usbmodem101`).
50    pub port_name: String,
51    /// USB vendor/product identifiers when the port is a USB device.
52    pub usb_vid_pid: Option<(u16, u16)>,
53    /// USB product string when reported by the device.
54    pub product: Option<String>,
55    /// Whether the USB vendor matches a known ESP32 board or UART bridge.
56    pub likely_esp: bool,
57}
58
59/// List host serial ports, marking ports that look like ESP32 boards.
60///
61/// # Errors
62/// Returns an error when the host serial subsystem cannot be enumerated.
63#[cfg(feature = "esp32")]
64pub async fn scan_serial_ports() -> eyre::Result<Vec<SerialPortSummary>> {
65    let ports = unblock(serialport::available_ports)
66        .await
67        .wrap_err("Failed to enumerate serial ports")?;
68
69    Ok(ports
70        .into_iter()
71        .map(|port| {
72            let (usb_vid_pid, product) = match port.port_type {
73                serialport::SerialPortType::UsbPort(usb) => (Some((usb.vid, usb.pid)), usb.product),
74                _ => (None, None),
75            };
76            let likely_esp = usb_vid_pid.is_some_and(|(vid, _)| ESP_USB_VENDOR_IDS.contains(&vid));
77            SerialPortSummary {
78                port_name: port.port_name,
79                usb_vid_pid,
80                product,
81                likely_esp,
82            }
83        })
84        .collect())
85}
86
87/// Pick the serial port of a connected ESP32 board, if any.
88///
89/// Espressif's native USB vendor ID and the usual UART bridges are
90/// considered; on hosts exposing both `tty` and `cu` nodes the callout
91/// (`cu`) node is preferred.
92///
93/// # Errors
94/// Returns an error when the host serial subsystem cannot be enumerated.
95#[cfg(feature = "esp32")]
96pub async fn detect_esp_serial_port() -> eyre::Result<Option<String>> {
97    let mut candidates: Vec<SerialPortSummary> = scan_serial_ports()
98        .await?
99        .into_iter()
100        .filter(|port| port.likely_esp)
101        .collect();
102    candidates.sort_by_key(|port| {
103        let is_callout = port.port_name.contains("/cu.");
104        (!is_callout, port.port_name.clone())
105    });
106    Ok(candidates.into_iter().next().map(|port| port.port_name))
107}
108
109fn home_dir() -> eyre::Result<PathBuf> {
110    dirs::home_dir().ok_or_else(|| eyre!("Failed to resolve the user home directory"))
111}
112
113/// Find the newest versioned subdirectory of `base` containing `relative`.
114pub(crate) fn newest_toolchain_subpath(base: &Path, relative: &Path) -> Option<PathBuf> {
115    let mut versions: Vec<PathBuf> = std::fs::read_dir(base)
116        .ok()?
117        .filter_map(Result::ok)
118        .map(|entry| entry.path())
119        .filter(|path| path.join(relative).is_dir())
120        .collect();
121    versions.sort();
122    versions.pop().map(|path| path.join(relative))
123}
124
125fn espup_component_dir(component: &str, relative: &Path, what: &str) -> eyre::Result<PathBuf> {
126    let base = home_dir()?.join(".rustup/toolchains/esp").join(component);
127    newest_toolchain_subpath(&base, relative).ok_or_else(|| {
128        eyre!(
129            "{what} not found under {}. Install the Espressif Rust toolchain with `espup install`.",
130            base.display()
131        )
132    })
133}
134
135/// Locate the GCC `bin` directory for `chip`'s architecture.
136///
137/// Xtensa GCC ships inside the espup `esp` toolchain
138/// (`~/.rustup/toolchains/esp/xtensa-esp-elf/...`); the RISC-V GCC is installed
139/// by ESP-IDF under `~/.espressif/tools/riscv32-esp-elf/...`. Both are
140/// version-discovered rather than pinned.
141fn gcc_bin_dir(chip: Esp32Chip) -> eyre::Result<PathBuf> {
142    let component = chip.gcc_component();
143    match chip.arch() {
144        crate::esp32::chip::Esp32Arch::Xtensa => espup_component_dir(
145            component.component,
146            Path::new(component.bin_subpath),
147            component.what,
148        ),
149        crate::esp32::chip::Esp32Arch::RiscV => {
150            let base = home_dir()?
151                .join(".espressif/tools")
152                .join(component.component);
153            newest_toolchain_subpath(&base, Path::new(component.bin_subpath)).ok_or_else(|| {
154                eyre!(
155                    "{} not found under {}. Install it with ESP-IDF tools (`idf_tools.py install`) \
156                     or by building an esp-idf-svc project once.",
157                    component.what,
158                    base.display()
159                )
160            })
161        }
162    }
163}
164
165/// Environment variables required to drive the Espressif Rust toolchain for
166/// `chip`.
167///
168/// Prepends the chip architecture's GCC `bin` directory to `PATH` and points
169/// `LIBCLANG_PATH` at the Espressif clang libraries (shared across
170/// architectures), discovered under the espup `esp` toolchain without assuming
171/// a toolchain version.
172///
173/// # Errors
174/// Returns an error when the Espressif toolchain components are not installed.
175pub fn esp_toolchain_envs(chip: Esp32Chip) -> eyre::Result<Vec<(String, OsString)>> {
176    let gcc_bin = gcc_bin_dir(chip)?;
177    let libclang = espup_component_dir(
178        "xtensa-esp32-elf-clang",
179        Path::new("esp-clang/lib"),
180        "Espressif clang libraries",
181    )?;
182
183    let mut paths = vec![gcc_bin];
184    if let Some(current) = std::env::var_os("PATH") {
185        paths.extend(std::env::split_paths(&current));
186    }
187    let path_value =
188        std::env::join_paths(paths).wrap_err("Failed to compose PATH for the ESP toolchain")?;
189
190    Ok(vec![
191        ("PATH".to_string(), path_value),
192        ("LIBCLANG_PATH".to_string(), libclang.into_os_string()),
193    ])
194}
195
196/// Resolve the configured chip for `project`'s ESP32 backend.
197fn esp32_chip(project: &Project) -> eyre::Result<Esp32Chip> {
198    project
199        .esp32_backend()
200        .cloned()
201        .unwrap_or_default()
202        .resolved_chip()
203}
204
205async fn espflash_path() -> eyre::Result<PathBuf> {
206    which("espflash")
207        .await
208        .map_err(|_| eyre!("espflash not found. Install it with `cargo install espflash`."))
209}
210
211fn command_failure_details(output: &std::process::Output) -> String {
212    let stderr = String::from_utf8_lossy(&output.stderr);
213    let stdout = String::from_utf8_lossy(&output.stdout);
214    if stderr.trim().is_empty() {
215        stdout.to_string()
216    } else {
217        stderr.to_string()
218    }
219}
220
221/// Build the ESP32 firmware ELF for the configured chip.
222///
223/// Runs `cargo build` inside the generated harness directory so its
224/// `rust-toolchain.toml` (channel `esp`) and `.cargo/config.toml` (Xtensa
225/// target, `build-std`, ESP-IDF environment) take effect.
226///
227/// # Errors
228/// Returns an error if the harness is missing, the Espressif toolchain is not
229/// installed, or Cargo fails.
230pub async fn build_esp32(project: &Project, options: BuildOptions) -> eyre::Result<BuiltTarget> {
231    let backend_path = project.backend_path::<Esp32Backend>();
232    let cargo_toml = backend_path.join("Cargo.toml");
233    let backend_target_dir = project.toolchain_target_dir("esp32").await?;
234
235    if !cargo_toml.exists() {
236        bail!(
237            "ESP32 backend not found at {}. Run `{ESP32_INIT_HINT}` to initialize it.",
238            backend_path.display(),
239        );
240    }
241
242    let chip = esp32_chip(project)?;
243
244    let mut cargo = smol::process::Command::new("cargo");
245    cargo.current_dir(&backend_path);
246    cargo.arg("build");
247    cargo.arg("--message-format=json-render-diagnostics");
248    cargo.arg("--target-dir").arg(&backend_target_dir);
249    crate::build::configure_generated_crate_compilation(&mut cargo);
250    if let Some(sccache_path) = options.sccache_path() {
251        crate::toolchain::sccache::configure_compilation_cache(&mut cargo, sccache_path)?;
252    }
253    for (key, value) in esp_toolchain_envs(chip)? {
254        cargo.env(key, value);
255    }
256    if options.is_release() {
257        cargo.arg("--release");
258    }
259    // Piped stdio strips rustc diagnostics of their colors; restore cargo's
260    // coloring while the terminal renders the output.
261    if crate::utils::std_output_enabled() && std::env::var_os("CARGO_TERM_COLOR").is_none() {
262        cargo.env("CARGO_TERM_COLOR", "always");
263    }
264
265    let output =
266        crate::build::command_output_with_progress(&mut cargo, options.progress().cloned()).await?;
267    if !output.status.success() {
268        let details = command_failure_details(&output);
269        // A live-rendered stream is tailed rather than re-dumped in full.
270        let details = if options
271            .progress()
272            .is_some_and(BuildProgress::shows_all_lines)
273        {
274            crate::build::output_tail(&details)
275        } else {
276            details
277        };
278        bail!(
279            "Failed to build ESP32 firmware with cargo (status {}):\n{}",
280            output.status,
281            details
282        );
283    }
284
285    // The ELF path comes from cargo's own artifact report — the shared
286    // toolchain target directory hosts other projects' builds, so a bare
287    // `<profile>/<name>` lookup is not evidence the file is this project's.
288    let crate_name = project.esp32_backend_crate_name();
289    let artifact = crate::build::reported_artifact(
290        &output.stdout,
291        &backend_path,
292        crate::build::CargoTarget::Binary(crate_name.as_str()),
293        None,
294    )
295    .map_err(|error| eyre!("failed to resolve the built ESP32 firmware: {error}"))?;
296    let profile_dir = artifact.parent().ok_or_else(|| {
297        eyre!(
298            "ESP32 firmware artifact has no profile directory: {}",
299            artifact.display()
300        )
301    })?;
302    Ok(BuiltTarget {
303        profile_dir: profile_dir.to_path_buf(),
304        artifact,
305        shared_runtime: None,
306    })
307}
308
309/// Build, then flash and monitor the firmware on a board, or emulate it.
310///
311/// `device` selects the run target: `Some("qemu")` forces the QEMU emulator,
312/// `Some(port)` flashes the given serial port, and `None` flashes the first
313/// connected ESP32 board, falling back to QEMU when no board is connected but
314/// the chip's QEMU emulator is installed.
315///
316/// # Errors
317/// Returns an error when building, flashing, or emulation fails, or when
318/// neither a board nor QEMU is available.
319pub async fn run_esp32(
320    project: &Project,
321    options: BuildOptions,
322    device: Option<&str>,
323) -> eyre::Result<()> {
324    let chip = esp32_chip(project)?;
325    let elf = build_esp32(project, options).await?;
326
327    match device {
328        Some("qemu") => qemu_esp32(project, chip, &elf.artifact).await,
329        Some(port) => flash_and_monitor(project, &elf.artifact, Some(port)).await,
330        None => {
331            #[cfg(feature = "esp32")]
332            {
333                if let Some(port) = detect_esp_serial_port().await? {
334                    info!("Flashing ESP32 board on {port}");
335                    return flash_and_monitor(project, &elf.artifact, Some(&port)).await;
336                }
337            }
338            if locate_qemu(chip).await.is_some() {
339                info!("No ESP32 board connected; running under QEMU");
340                return qemu_esp32(project, chip, &elf.artifact).await;
341            }
342            bail!(
343                "No ESP32 board connected and no QEMU for {chip_id} installed.\n\
344                 Connect a board (see `water devices --platform esp32`), pass --device <port>,\n\
345                 or install Espressif's QEMU fork ({qemu} with the {machine} machine).",
346                chip_id = chip.id(),
347                qemu = chip.qemu_binary(),
348                machine = chip.qemu_machine(),
349            );
350        }
351    }
352}
353
354async fn flash_and_monitor(project: &Project, elf: &Path, port: Option<&str>) -> eyre::Result<()> {
355    let backend_path = project.backend_path::<Esp32Backend>();
356    let espflash = espflash_path().await?;
357
358    let mut espflash_cmd = smol::process::Command::new(espflash);
359    espflash_cmd
360        .current_dir(&backend_path)
361        .arg("flash")
362        .arg("--partition-table")
363        .arg(backend_path.join("partitions.csv"))
364        .arg("--monitor");
365    if let Some(port) = port {
366        espflash_cmd.arg("--port").arg(port);
367    }
368    espflash_cmd
369        .arg(elf)
370        .stdin(Stdio::inherit())
371        .stdout(Stdio::inherit())
372        .stderr(Stdio::inherit())
373        .kill_on_drop(true);
374
375    let status = espflash_cmd.status().await?;
376    if !status.success() {
377        bail!("espflash flash failed with status {status}");
378    }
379    Ok(())
380}
381
382/// Locate the QEMU binary that emulates `chip`'s architecture.
383///
384/// Prefers the Espressif QEMU fork bundled under `~/.local/esp-qemu/qemu/bin`,
385/// falling back to the binary on `PATH`.
386async fn locate_qemu(chip: Esp32Chip) -> Option<PathBuf> {
387    let binary = chip.qemu_binary();
388    if let Ok(home) = home_dir() {
389        let bundled = home.join(".local/esp-qemu/qemu/bin").join(binary);
390        if bundled.exists() {
391            return Some(bundled);
392        }
393    }
394    which(binary).await.ok()
395}
396
397/// eFuse image for QEMU: ADC calibration version 1 (BLK2 word 4 bits 0..3).
398///
399/// Without it Xtensa firmware hangs at startup in hardware ADC
400/// self-calibration, which QEMU does not emulate; version 1 makes startup read
401/// the (zeroed) calibration codes from eFuse instead.
402fn qemu_efuse_image() -> Vec<u8> {
403    let mut data = vec![0u8; 1024];
404    data[64] = 0x01;
405    data
406}
407
408/// Run the built firmware ELF under the chip's QEMU, streaming serial output.
409///
410/// Builds a merged flash image with `espflash save-image` and runs the chip's
411/// QEMU with its machine model. Xtensa chips additionally need an eFuse image
412/// to skip unemulated ADC self-calibration; RISC-V chips boot without it.
413///
414/// # Errors
415/// Returns an error when QEMU or espflash is missing, image generation fails,
416/// or the emulator exits with a failure status.
417pub async fn qemu_esp32(project: &Project, chip: Esp32Chip, elf: &Path) -> eyre::Result<()> {
418    let qemu = locate_qemu(chip).await.ok_or_else(|| {
419        eyre!(
420            "QEMU for {} not found. Expected ~/.local/esp-qemu/qemu/bin/{binary} \
421             or {binary} on PATH (Espressif fork with the {machine} machine).",
422            chip.id(),
423            binary = chip.qemu_binary(),
424            machine = chip.qemu_machine(),
425        )
426    })?;
427    let backend_path = project.backend_path::<Esp32Backend>();
428
429    let staging = tempfile::Builder::new()
430        .prefix("waterui-esp32-qemu")
431        .tempdir()
432        .wrap_err("Failed to create QEMU staging directory")?;
433    let flash_image = staging.path().join("flash.bin");
434
435    save_flash_image(&backend_path, chip, elf, &flash_image).await?;
436
437    let mut qemu_cmd = smol::process::Command::new(qemu);
438    qemu_cmd
439        .arg("-nographic")
440        .arg("-machine")
441        .arg(chip.qemu_machine())
442        .arg("-drive")
443        .arg(format!("file={},if=mtd,format=raw", flash_image.display()));
444
445    let efuse_image = staging.path().join("efuse.bin");
446    if chip.needs_qemu_efuse_workaround() {
447        fs::write(&efuse_image, qemu_efuse_image()).await?;
448        qemu_cmd
449            .arg("-drive")
450            .arg(format!(
451                "file={},if=none,format=raw,id=efuse",
452                efuse_image.display()
453            ))
454            .arg("-global")
455            .arg(format!(
456                "driver=nvram.{}.efuse,property=drive,value=efuse",
457                chip.id()
458            ));
459    }
460
461    qemu_cmd
462        .stdin(Stdio::inherit())
463        .stdout(Stdio::inherit())
464        .stderr(Stdio::inherit())
465        .kill_on_drop(true);
466
467    let status = qemu_cmd.status().await?;
468    if !status.success() {
469        bail!("{} exited with status {status}", chip.qemu_binary());
470    }
471    Ok(())
472}
473
474async fn save_flash_image(
475    backend_path: &Path,
476    chip: Esp32Chip,
477    elf: &Path,
478    image_path: &Path,
479) -> eyre::Result<()> {
480    let espflash = espflash_path().await?;
481    let mut save = smol::process::Command::new(espflash);
482    let save = command(&mut save);
483    save.current_dir(backend_path)
484        .arg("save-image")
485        .arg("--chip")
486        .arg(chip.id())
487        .arg("--merge")
488        .arg("--flash-size")
489        .arg(chip.firmware_params().flash_size_arg())
490        .arg("--partition-table")
491        .arg(backend_path.join("partitions.csv"))
492        .arg(elf)
493        .arg(image_path);
494
495    let output = save.output().await?;
496    if !output.status.success() {
497        bail!(
498            "espflash save-image failed with status {}:\n{}",
499            output.status,
500            command_failure_details(&output)
501        );
502    }
503    Ok(())
504}
505
506/// Package the built firmware as a flashable merged image.
507///
508/// # Errors
509/// Returns an error when the built ELF is missing or image merging fails.
510pub async fn package_esp32(
511    project: &Project,
512    options: PackageOptions,
513    built: &BuiltTarget,
514) -> eyre::Result<Artifact> {
515    let profile = if options.is_debug() {
516        "debug"
517    } else {
518        "release"
519    };
520    let elf = &built.artifact;
521    let backend_path = project.backend_path::<Esp32Backend>();
522    let chip = esp32_chip(project)?;
523
524    let dist_dir = crate::platforming::packaging::dist_dir(&backend_path, "esp32", Some(profile));
525    fs::create_dir_all(&dist_dir).await?;
526    // The image ships under the product name; the tagged crate name is
527    // internal to the shared Cargo target directory.
528    let image_path = dist_dir.join(format!("{}.bin", project.esp32_binary_name()));
529    save_flash_image(&backend_path, chip, elf, &image_path).await?;
530
531    Ok(Artifact::new(project.bundle_identifier(), image_path))
532}
533
534/// Clean Cargo build artifacts and packaged images for the ESP32 harness.
535///
536/// # Errors
537/// Returns an error if `cargo clean` fails or the dist directory cannot be removed.
538pub async fn clean_esp32(project: &Project) -> eyre::Result<()> {
539    let backend_path = project.backend_path::<Esp32Backend>();
540    let cargo_toml = backend_path.join("Cargo.toml");
541    let backend_target_dir = project.toolchain_target_dir("esp32").await?;
542
543    if !cargo_toml.exists() {
544        return Ok(());
545    }
546
547    let args: Vec<OsString> = vec![
548        "clean".into(),
549        "--manifest-path".into(),
550        cargo_toml.as_os_str().to_owned(),
551        "--target-dir".into(),
552        backend_target_dir.as_os_str().to_owned(),
553    ];
554    run_command_os("cargo", args).await?;
555
556    let dist_dir = backend_path.join("dist");
557    if dist_dir.exists() {
558        fs::remove_dir_all(&dist_dir).await?;
559    }
560    Ok(())
561}