1use 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#[cfg(feature = "esp32")]
34const ESP_USB_VENDOR_IDS: [u16; 4] = [0x303a, 0x10c4, 0x1a86, 0x0403];
35
36#[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#[cfg(feature = "esp32")]
47#[derive(Debug, Clone)]
48pub struct SerialPortSummary {
49 pub port_name: String,
51 pub usb_vid_pid: Option<(u16, u16)>,
53 pub product: Option<String>,
55 pub likely_esp: bool,
57}
58
59#[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#[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
113pub(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
135fn 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
165pub 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(¤t));
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
196fn 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
221pub 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 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 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 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
309pub 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
382async 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
397fn qemu_efuse_image() -> Vec<u8> {
403 let mut data = vec![0u8; 1024];
404 data[64] = 0x01;
405 data
406}
407
408pub 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
506pub 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 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
534pub 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}