From ce7f8aba5595702c5f1a2b14b43ed306ebca7780 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:02:50 -0700 Subject: [PATCH] tools: add the rnodeconf guided installer; all upstream options now work --- README.md | 25 +- crates/rns-tools/src/commands/rnodeconf.rs | 110 ++- .../src/commands/rnodeconf/autoinstall.rs | 624 ++++++++++++++++++ .../rns-tools/src/commands/rnodeconf/plan.rs | 37 -- .../rnodeconf_autoinstall/choices.json | 95 +++ .../rnodeconf_autoinstall/generate.py | 97 +++ 6 files changed, 910 insertions(+), 78 deletions(-) create mode 100644 crates/rns-tools/src/commands/rnodeconf/autoinstall.rs delete mode 100644 crates/rns-tools/src/commands/rnodeconf/plan.rs create mode 100644 crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/choices.json create mode 100644 crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/generate.py diff --git a/README.md b/README.md index fce60dc..f3c2429 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ The `rns-tools` crate builds Rust-namespaced Reticulum utilities: | rnid-rs | Identity generation, inspection, public/private import/export, hashing, signing, verification, encryption, and decryption. | | rnprobe-rs | Destination probe utility with loss and round-trip reporting. | | rncp-rs | File transfer utility with send, listen, and authenticated fetch modes. | -| rnodeconf-rs | RNode inspection, EEPROM backup, and saved TNC/normal startup configuration. | +| rnodeconf-rs | RNode inspection, settings, signing, EEPROM bootstrap, firmware install and update, and the guided installer. | | rnsh-rs | Reticulum shell listener/client. | Common command forms (use each binary’s `--help` for the complete option list): @@ -147,6 +147,8 @@ rncp-rs -f [-s DEST_DIR] rnodeconf-rs [-i] [--config] [--eeprom-backup|--eeprom-dump] [--version] [PORT] rnodeconf-rs -T --freq HZ --bw HZ --txp DBM --sf SF --cr CR PORT rnodeconf-rs -N PORT +rnodeconf-rs -a [PORT] +rnodeconf-rs -u [-U] [--fw-version V] [--fw-url URL] [--nocheck] PORT rnsh-rs -l [-i FILE] [-s NAME] [-b PERIOD] [-a HASH]... [-n] [-A|-C] [-- CMD...] rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] [-- CMD...] ``` @@ -163,11 +165,15 @@ Without `-n`, fetch requests require an identified peer on the allowlist. `-j ` to constrain fetched paths to a directory under trusted local control; it is not an operating-system sandbox. -`rnodeconf-rs` in 1.4.0 and 1.3.0 supports inspection, -EEPROM dump/backup, and saving TNC/normal startup settings. `-T` requires all five -RF values shown above. Firmware installation, signing/trust enrollment and -Bluetooth, Wi-Fi, display and interference-avoidance changes are disabled. -Their options remain in the parser but return an error. +`rnodeconf-rs` covers the upstream `rnodeconf` options: inspection, device +settings, signing and trust, EEPROM bootstrap and wipe, firmware download, +update, flashing and extraction, and the `-a` guided installer. Firmware comes +from the official RNode firmware releases unless `--fw-url` names another +source. Flashing runs the same external tools as upstream (`avrdude`, +`adafruit-nrfutil`, and the firmware's own `esptool.py` through `python3`); +upstream's bundled recovery esptool is not included, so `--extract` needs +`esptool.py` or `esptool` on `PATH`. On nRF52 boards the EEPROM bootstrap +writes more slowly than upstream and reads every byte back before locking. `rnid-rs` tracks the Reticulum 1.4.2 identity utility surface for normal software identities: public/private import and export, destination hashing, @@ -314,10 +320,9 @@ Known gaps and intentional limits: - `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented; of the rngit tools only the `rngcs-rs` commit signer exists. -- `rnodeconf-rs` is partial; safe inspection/configuration and EEPROM - dump/backup are furthest along. Firmware flashing, autoinstall/update, ROM - bootstrap, destructive EEPROM wipe, and full signing-key management are not - implemented. +- `rnodeconf-rs` flashing, EEPROM bootstrap and the guided installer are + checked against upstream on an emulated RNode; real-board coverage depends + on hardware testing. - `rnstatus-rs` covers the practical operator surface, but does not implement every display/API behavior from upstream. - `rnpath-rs` remote mode is read-only for table/rates, including destination diff --git a/crates/rns-tools/src/commands/rnodeconf.rs b/crates/rns-tools/src/commands/rnodeconf.rs index 2925dcf..834391e 100644 --- a/crates/rns-tools/src/commands/rnodeconf.rs +++ b/crates/rns-tools/src/commands/rnodeconf.rs @@ -9,12 +9,15 @@ use std::fs; use std::io::{BufRead, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use clap::{CommandFactory, Parser}; use rns_interface::{rnode, rnode_admin}; use rns_tools::RS_RETICULUM_VERSION; +#[path = "rnodeconf/autoinstall.rs"] +mod autoinstall; #[path = "rnodeconf/bootstrap.rs"] mod bootstrap; #[allow(dead_code)] @@ -31,8 +34,6 @@ mod install; #[allow(dead_code)] #[path = "rnodeconf/model.rs"] mod model; -#[path = "rnodeconf/plan.rs"] -mod plan; #[path = "rnodeconf/session.rs"] mod session; #[path = "rnodeconf/trust.rs"] @@ -289,16 +290,26 @@ pub(crate) fn main() -> ExitCode { if args.extract { return install::extract(&args); } - if let Some(message) = plan::refusal_without_port(&args) { - eprintln!("rnodeconf-rs: {message}"); - return ExitCode::from(2); - } + let auto = if args.autoinstall { + match autoinstall::run(&mut args) { + Ok(plan) => Some(plan), + Err(code) => return code, + } + } else { + None + }; if args.public { show_public_keys(); return ExitCode::SUCCESS; } if args.key { - return generate_keys(); + // Autoinstall makes the keys it needs and carries on to flashing. + if let Err(code) = generate_keys(args.autoinstall) { + return code; + } + if !args.autoinstall { + return ExitCode::SUCCESS; + } } let Some(port_path) = args.port.clone() else { out(""); @@ -308,7 +319,24 @@ pub(crate) fn main() -> ExitCode { return ExitCode::SUCCESS; }; if args.flash { - match install::flash(&args, &port_path) { + let flashed = match auto.as_ref() { + Some(plan) => match rnodeconf_cache_paths() { + Ok(paths) => install::flash_firmware( + &args, + &port_path, + &paths, + plan.choice.platform, + &plan.choice.fw_filename, + &plan.version, + ), + Err(error) => { + eprintln!("rnodeconf-rs: {error}"); + return ExitCode::from(1); + } + }, + None => install::flash(&args, &port_path), + }; + match flashed { Ok(rom) => args.rom = rom, Err(code) => return code, } @@ -325,7 +353,7 @@ pub(crate) fn main() -> ExitCode { }; let mut rnode = RNode::new(port, port_path.clone()); rnode.usb_serial_id = bootstrap::usb_serial_number(&port_path); - match run_device(rnode, &args) { + match run_device(rnode, &args, auto.as_ref()) { Ok(code) => code, Err(e) => { eprintln!("rnodeconf-rs: {e}"); @@ -359,7 +387,11 @@ fn print_donation_block() { /// Upstream `main()` from the device probe on, for the operations this build /// supports. Errors are the cases where upstream raises an exception. -fn run_device(session: RNode, args: &Args) -> Result { +fn run_device( + session: RNode, + args: &Args, + auto: Option<&autoinstall::Plan>, +) -> Result { let mut session = session; let rnode = &mut session; if let Err(e) = rnode.device_probe() { @@ -458,9 +490,14 @@ fn run_device(session: RNode, args: &Args) -> Result { model: args.model.as_deref(), hwrev: args.hwrev, autoinstall: args.autoinstall, - mapped_product: model::PRODUCT_RNODE, - mapped_model: None, - firmware: None, + mapped_product: auto.map_or(model::PRODUCT_RNODE, |plan| plan.choice.product), + mapped_model: auto.map(|plan| plan.choice.model), + firmware: auto + .filter(|plan| plan.provisions_firmware_hash()) + .map(|plan| bootstrap::FirmwareProvision { + fw_filename: plan.choice.fw_filename.clone(), + selected_version: plan.version.clone(), + }), port_path: &rnode.name.clone(), }; let signature_valid = device.as_ref().is_some_and(|d| d.signature.valid); @@ -881,12 +918,13 @@ fn show_public_keys() { /// Upstream `-k`: a device signing identity and an EEPROM signing key, each /// created only when absent. Exits 81 and 82 are upstream's intent; upstream /// never reaches them because `Identity.to_file` and `from_file` swallow errors. -fn generate_keys() -> ExitCode { +/// `Err` ends the run with that code; autoinstall goes on after `Ok`. +fn generate_keys(autoinstall: bool) -> Result<(), ExitCode> { let root = match rnodeconf_root() { Ok(root) => root, Err(error) => { log(error); - return ExitCode::SUCCESS; + return Err(ExitCode::SUCCESS); } }; let firmware_dir = root.join("firmware"); @@ -901,7 +939,7 @@ fn generate_keys() -> ExitCode { )); log(error.to_string()); log("Please ensure filesystem access and try again."); - return ExitCode::from(81); + return Err(ExitCode::from(81)); } log(format!( "Device signing key written to {}", @@ -918,37 +956,41 @@ fn generate_keys() -> ExitCode { )); log(error); log("Please restore or clear the key and try again."); - return ExitCode::from(82); + return Err(ExitCode::from(82)); } } let signing_key = trust::signing_key_path(&root); if signing_key.is_file() { let _ = fs::create_dir_all(&firmware_dir); - log("EEPROM Signing key already exists, not overwriting!"); - log("Manually delete this key to create a new one."); - return ExitCode::SUCCESS; + if !autoinstall { + log("EEPROM Signing key already exists, not overwriting!"); + log("Manually delete this key to create a new one."); + } + return Ok(()); } log("Generating a new EEPROM signing key..."); let (private_bytes, public_bytes) = match trust::generate_signing_key() { Ok(keys) => keys, Err(error) => { log(error); - return ExitCode::SUCCESS; + return Err(ExitCode::SUCCESS); } }; if fs::create_dir_all(&firmware_dir).is_err() || !firmware_dir.is_dir() { log("The firmware directory does not exist, can't write key!"); - return ExitCode::SUCCESS; + return Ok(()); } if let Err(error) = fs::write(&signing_key, &private_bytes) { log(py_os_error(&error, &signing_key)); - return ExitCode::SUCCESS; + return Err(ExitCode::SUCCESS); } - log("Wrote signing key"); - log("Public key:"); - log(hex::encode(public_bytes)); - ExitCode::SUCCESS + if !QUIET_UNVERIFIED.load(Ordering::Relaxed) { + log("Wrote signing key"); + log("Public key:"); + log(hex::encode(public_bytes)); + } + Ok(()) } /// Upstream `graceful_exit`: only Windows tells the device the host left. @@ -1084,11 +1126,13 @@ fn parse_eeprom(bytes: &[u8], port_name: &str) -> ParsedEeprom { log("Device signature validated"); } else { log("Device signature validation failed"); - for line in UNVERIFIED_DEVICE_WARNING { - out(*line); + if !QUIET_UNVERIFIED.load(Ordering::Relaxed) { + for line in UNVERIFIED_DEVICE_WARNING { + out(*line); + } + out(format!(" rnodeconf {port_name} --autoinstall")); + out(""); } - out(format!(" rnodeconf {port_name} --autoinstall")); - out(""); } let image = eeprom::EepromImage::new(bytes.to_vec()).expect("length checked"); let identity = image.identity(); @@ -1106,6 +1150,10 @@ fn parse_eeprom(bytes: &[u8], port_name: &str) -> ParsedEeprom { })) } +/// Upstream global `squashvw`: autoinstall silences the unverified-device warning +/// and the new signing key printout. +static QUIET_UNVERIFIED: AtomicBool = AtomicBool::new(false); + const UNVERIFIED_DEVICE_WARNING: &[&str] = &[ " ", " WARNING! This device is NOT verifiable and should NOT be trusted.", diff --git a/crates/rns-tools/src/commands/rnodeconf/autoinstall.rs b/crates/rns-tools/src/commands/rnodeconf/autoinstall.rs new file mode 100644 index 0000000..0514a5e --- /dev/null +++ b/crates/rns-tools/src/commands/rnodeconf/autoinstall.rs @@ -0,0 +1,624 @@ +//! Upstream `rnodeconf --autoinstall`: the guided installer. It picks the port, +//! board and firmware, then hands over to the key, flash and EEPROM bootstrap +//! flows by setting their options, as upstream does. + +use std::io::{BufRead, IsTerminal, Write}; +use std::process::ExitCode; +use std::sync::atomic::Ordering; + +use super::firmware::{self, Selection, Source}; +use super::session::RNode; +use super::{Args, ParsedEeprom, graceful_exit, log, model, open_serial, out, parse_eeprom}; + +const INTRO: &str = "\nHello!\n\nThis guide will help you install the RNode firmware on supported\nand homebrew devices. Please connect the device you wish to set\nup now. Hit enter when it is connected.\n"; +const SELECTION_HEAD: &str = "\n---------------------------------------------------------------------------\n Device Selection\n"; +const DETECTED: &str = "\nThe device seems to have an RNode firmware installed, but it was not\nprovisioned correctly, or it is corrupt. We are going to reinstall the\ncorrect firmware and provision it.\n"; +const FRESH: &str = "\nIt looks like this is a fresh device with no RNode firmware.\n"; +const DEVICE_MENU: &str = "\nWhat kind of device is this?\n\n | Select this option if you have an RNode of a specific\n \\ / type, built from a recipe or bought from a vendor.\n '\n[1] A specific kind of RNode\n\n | Select this option if you have put together an RNode\n \\ / of your own design, or if you are prototyping one.\n '\n[2] Homebrew RNode\n\n | Select one of these options if you want to easily turn\n \\ / a supported development board into an RNode.\n '\n[3] LilyGO LoRa32 v2.1 (aka T3 v1.6 / T3 v1.6.1)\n[4] LilyGO LoRa32 v2.0\n[5] LilyGO LoRa32 v1.0\n[6] LilyGO T-Beam\n[7] Heltec LoRa32 v2\n[8] Heltec LoRa32 v3\n[9] Heltec LoRa32 v4\n[10] LilyGO LoRa T3S3\n[11] RAK4631\n[12] LilyGo T-Echo\n[13] LilyGO T-Beam Supreme\n[14] LilyGO T-Deck\n[15] Heltec T114\n[16] Seeed XIAO ESP32S3 Wio-SX1262\n\n---------------------------------------------------------------------------\n\nEnter the number that matches your device type:\n? "; +const ESP32_BOARD_MENU: &str = "\nWhat kind of ESP32 board is this?\n\n[1] Adafruit Feather ESP32 (HUZZAH32)\n[2] Generic ESP32 board\n\n? "; +const NO_FIRMWARE: &str = "\nSorry, no firmware for your board currently exists.\nHelp making it a reality by contributing code or by\ndonating to the project.\n"; + +/// Upstream's device menu entries, by answer (1 to 16): product, whether it is +/// the T3S3 variant of the RNode product, and the notice shown before the band menu. +const DEVICES: [(u8, bool, Option<&str>); 16] = [ + (model::PRODUCT_RNODE, false, None), + ( + model::PRODUCT_HMBRW, + false, + Some( + "\n---------------------------------------------------------------------------\n Homebrew RNode Installer\n\nThis option allows you to install and provision the RNode firmware on a\ncustom board design, or a custom device created by coupling a generic\ndevelopment board with a supported transceiver module.\n\nImportant! Using RNode firmware on homebrew devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_T32_21, + false, + Some( + "\n---------------------------------------------------------------------------\n LilyGO LoRa32 v2.1 RNode Installer\n\nImportant! Using RNode firmware on LoRa32 devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_T32_20, + false, + Some( + "\n---------------------------------------------------------------------------\n LilyGO LoRa32 v2.0 RNode Installer\n\nImportant! Using RNode firmware on LoRa32 devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_T32_10, + false, + Some( + "\n---------------------------------------------------------------------------\n LilyGO LoRa32 v1.0 RNode Installer\n\nImportant! Using RNode firmware on LoRa32 devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it.\n\nPlease Note! This device is known to have a faulty battery charging circuit,\nwhich can result in overcharging and damaging batteries. If at all possible,\nit is recommended to avoid this device.\n\nHit enter if you're sure you wish to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_TBEAM, + false, + Some( + "\n---------------------------------------------------------------------------\n T-Beam RNode Installer\n\nThe RNode firmware can currently be installed on T-Beam devices using the\nSX1276, SX1278, SX1262 and SX1268 transceiver chips.\n\nImportant! Using RNode firmware on T-Beam devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_H32_V2, + false, + Some( + "\n---------------------------------------------------------------------------\n Heltec LoRa32 v2.0 RNode Installer\n\nImportant! Using RNode firmware on Heltec devices should currently be\nconsidered experimental. It is not intended for production or critical use.\n\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_H32_V3, + false, + Some( + "\n---------------------------------------------------------------------------\n Heltec LoRa32 v3.0 RNode Installer\n\nImportant! Using RNode firmware on Heltec devices should currently be\nconsidered experimental. It is not intended for production or critical use.\n\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_H32_V4, + false, + Some( + "\n---------------------------------------------------------------------------\n Heltec LoRa32 v4 RNode Installer\n\nImportant! Using RNode firmware on Heltec devices should currently be\nconsidered experimental. It is not intended for production or critical use.\n\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_RNODE, + true, + Some( + "\n---------------------------------------------------------------------------\n LilyGO LoRa32 T3S3 RNode Installer\n\nImportant! Using RNode firmware on T3S3 devices should currently be\nconsidered experimental. It is not intended for production or critical use.\n\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_RAK4631, + false, + Some( + "\n---------------------------------------------------------------------------\n RAK4631 RNode Installer\n\nImportant! Using RNode firmware on RAKwireless devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_TECHO, + false, + Some( + "\n---------------------------------------------------------------------------\n LilyGo T-Echo RNode Installer\n\nImportant! Using RNode firmware on LilyGo T-Echo devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_TBEAM_S_V1, + false, + Some( + "\n---------------------------------------------------------------------------\n T-Beam Supreme RNode Installer\n\nThe RNode firmware can currently be installed on T-Beam Supreme devices\nusing the SX1262 and SX1268 transceiver chips.\n\nImportant! Using RNode firmware on T-Beam devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_TDECK, + false, + Some( + "\n---------------------------------------------------------------------------\n T-Deck RNode Installer\n\nThe RNode firmware can currently be installed on T-Deck devices using the\nSX1262 and SX1268 transceiver chips.\n\nImportant! Using RNode firmware on T-Beam devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_HELTEC_T114, + false, + Some( + "\n---------------------------------------------------------------------------\n Heltec T114 RNode Installer\n\nImportant! Using RNode firmware on Heltec T114 devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), + ( + model::PRODUCT_XIAO_S3, + false, + Some( + "\n---------------------------------------------------------------------------\n SeeedStudio XIAO esp32s3 wio RNode Installer\n\nImportant! Using RNode firmware on SeeedStudio XIAO/wio devices should currently be\nconsidered experimental. It is not intended for production or critical use.\nThe currently supplied firmware is provided AS-IS as a courtesy to those\nwho would like to experiment with it. Hit enter to continue.\n---------------------------------------------------------------------------\n", + ), + ), +]; + +const MENU_HMBRW_0: (&str, &str) = ( + "\nWhat kind of microcontroller is your board based on?\n\n[1] AVR ATmega1284P\n[2] AVR ATmega2560\n[3] Espressif Systems ESP32\n\n? ", + "That MCU type does not exist, exiting now.\n", +); +const MENU_HMBRW_1: (&str, &str) = ( + "\nWhat transceiver module does your board use?\n\n[1] SX1276/SX1278 with antenna port on PA_BOOST pin\n[2] SX1276/SX1278 with antenna port on RFO pin\n\n? ", + "That transceiver type does not exist, exiting now.\n", +); +const MENU_RNODE_0: (&str, &str) = ( + "\nWhat model is this RNode?\n\n[1] Handheld v2.1 RNode, 410 - 525 MHz\n[2] Handheld v2.1 RNode, 820 - 1020 MHz\n\n[3] Original v1.x RNode, 410 - 525 MHz\n[4] Original v1.x RNode, 820 - 1020 MHz\n\n[5] Prototype v2.2 RNode, 410 - 525 MHz\n[6] Prototype v2.2 RNode, 820 - 1020 MHz\n\n? ", + "That model does not exist, exiting now.\n", +); +const MENU_RNODE_1: (&str, &str) = ( + "\nWhat band is this T3S3 for?\n\n[1] 433 MHz (with SX1278 chip)\n[2] 868/915/923 MHz (with SX1276 chip)\n\n[3] 433 MHz (with SX1268 chip)\n[4] 868/915/923 MHz (with SX1262 chip)\n\n[5] 2.4 GHz (with SX1280 chip and PA)\n\n? ", + "That model does not exist, exiting now.\n", +); +const MENU_TBEAM_0: (&str, &str) = ( + "\nWhat band is this T-Beam for?\n\n[1] 433 MHz (with SX1278 chip)\n[2] 868/915/923 MHz (with SX1276 chip)\n\n[3] 433 MHz (with SX1268 chip)\n[4] 868/915/923 MHz (with SX1262 chip)\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_TBEAM_S_V1_0: (&str, &str) = ( + "\nWhat band is this T-Beam Supreme for?\n\n[1] 433 MHz (with SX1268 chip)\n[2] 868/915/923 MHz (with SX1262 chip)\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_TDECK_0: (&str, &str) = ( + "\nWhat band is this T-Deck for?\n\n[1] 433 MHz (with SX1268 chip)\n[2] 868/915/923 MHz (with SX1262 chip)\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_T32_10_0: (&str, &str) = ( + "\nWhat band is this LoRa32 for?\n\n[1] 433 MHz\n[2] 868 MHz\n[3] 915 MHz\n[4] 923 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_T32_20_0: (&str, &str) = ( + "\nWhat band is this LoRa32 for?\n\n[1] 433 MHz\n[2] 868 MHz\n[3] 915 MHz\n[4] 923 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_T32_21_0: (&str, &str) = ( + "\nWhat band is this LoRa32 for?\n\n[1] 433 MHz\n[2] 868/915/923 MHz\n[3] 433 MHz, with TCXO\n[4] 868/915/923 MHz, with TCXO\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_H32_V2_0: (&str, &str) = ( + "\nWhat band is this Heltec LoRa32 V2 for?\n\n[1] 433 MHz\n[2] 868 MHz\n[3] 915 MHz\n[4] 923 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_H32_V3_0: (&str, &str) = ( + "\nWhat band is this Heltec LoRa32 V3 for?\n\n[1] 433 MHz\n[2] 868 MHz\n[3] 915 MHz\n[4] 923 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_H32_V4_0: (&str, &str) = ( + "\nWhat band is this Heltec LoRa32 V4 for?\n\n[1] 868 MHz (28 dBm output)\n[2] 915 MHz (28 dBm output)\n[3] 923 MHz (28 dBm output)\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_HELTEC_T114_0: (&str, &str) = ( + "\nWhat band is this Heltec T114 for?\n\n[1] 433 MHz\n[2] 868 MHz\n[3] 915 MHz\n[4] 923 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_XIAO_S3_0: (&str, &str) = ( + "\nWhat band is this XIAO esp32s3 wio module for?\n\n[1] 433 MHz\n[2] 868 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_RAK4631_0: (&str, &str) = ( + "\nWhat band is this RAK4631 for?\n\n[1] 433 MHz\n[2] 868 MHz\n[3] 915 MHz\n[4] 923 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); +const MENU_TECHO_0: (&str, &str) = ( + "\nWhat band is this T-Echo for?\n\n[1] 433 MHz\n[2] 868 MHz\n[3] 915 MHz\n[4] 923 MHz\n\n? ", + "That band does not exist, exiting now.\n", +); + +/// Upstream's selected product, model, platform, MCU and firmware file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Choice { + pub product: u8, + pub model: u8, + pub platform: u8, + pub mcu: u8, + pub fw_filename: String, +} + +/// What the installer shows before reading a line. +pub enum Prompt<'a> { + /// A notice that waits for Enter. + Notice(&'a str), + /// A numbered menu ending in its "? " prompt. + Menu(&'a str), +} + +/// How the installer ends before the confirmation. +#[derive(Debug, PartialEq, Eq)] +pub enum Stop { + /// Upstream prints this line and exits 0. + Message(&'static str), + /// No firmware exists for the selection. + NoFirmware, +} + +/// Python `int()` on an input line. +fn int(line: Option) -> Option { + let line = line?; + let text = line.trim(); + let digits = text.strip_prefix('+').unwrap_or(text); + if digits.starts_with('_') || digits.ends_with('_') || digits.contains("__") { + return None; + } + text.replace('_', "").parse().ok() +} + +/// Upstream's menus from the device type to the firmware file. `ask` shows a +/// prompt and returns the line read, `None` at end of input. +pub fn choose( + detected: bool, + ask: &mut dyn FnMut(Prompt) -> Option, +) -> Result { + let menu = format!( + "{SELECTION_HEAD}{}{DEVICE_MENU}", + if detected { DETECTED } else { FRESH } + ); + let no_device = Stop::Message("That device type does not exist, exiting now."); + let c_dev = int(ask(Prompt::Menu(&menu))).filter(|c| (1..=16).contains(c)); + let Some(c_dev) = c_dev else { + return Err(no_device); + }; + let (product, t3s3, notice) = DEVICES[c_dev as usize - 1]; + if let Some(notice) = notice + && ask(Prompt::Notice(notice)).is_none() + { + return Err(no_device); + } + + // (menu, last valid answer, answer -> (model, platform, mcu)) + let pick = |menu: (&'static str, &'static str), + top: i64, + ask: &mut dyn FnMut(Prompt) -> Option| { + int(ask(Prompt::Menu(menu.0))) + .filter(|c| (1..=top).contains(c)) + .ok_or(Stop::Message(menu.1.trim_end())) + }; + use model::{MCU_1284P as P1284, MCU_2560 as M2560, MCU_ESP32 as ESP, MCU_NRF52 as NRF}; + use model::{PLATFORM_AVR as AVR, PLATFORM_ESP32 as PESP, PLATFORM_NRF52 as PNRF}; + let (model, platform, mcu) = match product { + model::PRODUCT_HMBRW => { + let (mcu, platform) = match pick(MENU_HMBRW_0, 3, ask)? { + 1 => (P1284, AVR), + 2 => (M2560, AVR), + _ => (ESP, PESP), + }; + // Upstream accepts a third transceiver answer that changes nothing. + let model = match pick(MENU_HMBRW_1, 3, ask)? { + 1 => 0xFE, + _ => 0xFF, + }; + (model, platform, mcu) + } + model::PRODUCT_RNODE if !t3s3 => match pick(MENU_RNODE_0, 6, ask)? { + 1 => (0xA2, PESP, ESP), + 2 => (0xA7, PESP, ESP), + 3 => (0xA4, AVR, P1284), + 4 => (0xA9, AVR, P1284), + 5 => (0xA1, PESP, ESP), + _ => (0xA6, PESP, ESP), + }, + model::PRODUCT_RNODE => { + let model = [0xA5, 0xAA, 0xA1, 0xA6, 0xAC][pick(MENU_RNODE_1, 5, ask)? as usize - 1]; + (model, PESP, ESP) + } + _ => { + let (menu, top, platform, mcu, models): (_, _, _, _, &[u8]) = match product { + model::PRODUCT_TBEAM => (MENU_TBEAM_0, 4, PESP, ESP, &[0xE4, 0xE9, 0xE3, 0xE8]), + model::PRODUCT_TBEAM_S_V1 => (MENU_TBEAM_S_V1_0, 2, PESP, ESP, &[0xDB, 0xDC]), + model::PRODUCT_TDECK => (MENU_TDECK_0, 2, PESP, ESP, &[0xD4, 0xD9]), + model::PRODUCT_T32_10 => (MENU_T32_10_0, 4, PESP, ESP, &[0xBA, 0xBB, 0xBB, 0xBB]), + model::PRODUCT_T32_20 => (MENU_T32_20_0, 4, PESP, ESP, &[0xB3, 0xB8, 0xB8, 0xB8]), + model::PRODUCT_T32_21 => ( + MENU_T32_21_0, + 4, + PESP, + ESP, + &[0xB4, 0xB9, model::MODEL_B4_TCXO, model::MODEL_B9_TCXO], + ), + model::PRODUCT_H32_V2 => (MENU_H32_V2_0, 4, PESP, ESP, &[0xC4, 0xC9, 0xC9, 0xC9]), + model::PRODUCT_H32_V3 => (MENU_H32_V3_0, 4, PESP, ESP, &[0xC5, 0xCA, 0xCA, 0xCA]), + model::PRODUCT_H32_V4 => (MENU_H32_V4_0, 3, PESP, ESP, &[0xC8, 0xC8, 0xC8]), + model::PRODUCT_HELTEC_T114 => { + (MENU_HELTEC_T114_0, 4, PNRF, NRF, &[0xC6, 0xC7, 0xC7, 0xC7]) + } + model::PRODUCT_XIAO_S3 => (MENU_XIAO_S3_0, 2, PESP, ESP, &[0xDE, 0xDD]), + model::PRODUCT_RAK4631 => (MENU_RAK4631_0, 4, PNRF, NRF, &[0x11, 0x12, 0x12, 0x12]), + _ => (MENU_TECHO_0, 4, PNRF, NRF, &[0x16, 0x17, 0x17, 0x17]), + }; + (models[pick(menu, top, ask)? as usize - 1], platform, mcu) + } + }; + + let fw_filename = if model != 0xFF && model != 0xFE { + model::model_info(model).and_then(|info| info.firmware_filename) + } else if platform == AVR { + Some(if mcu == P1284 { + "rnode_firmware.hex" + } else { + "rnode_firmware_m2560.hex" + }) + } else { + match int(ask(Prompt::Menu(ESP32_BOARD_MENU))) { + Some(1) => Some("rnode_firmware_featheresp32.zip"), + Some(2) => Some("rnode_firmware_esp32_generic.zip"), + _ => { + return Err(Stop::Message( + "That ESP32 board does not exist, exiting now.", + )); + } + } + }; + let fw_filename = fw_filename.ok_or(Stop::NoFirmware)?; + Ok(Choice { + product, + model, + platform, + mcu, + fw_filename: fw_filename.to_string(), + }) +} + +/// What the installer decided, for the flash and bootstrap steps after it. +pub struct Plan { + pub choice: Choice, + pub version: String, +} + +impl Plan { + /// Upstream's `wants_fw_provision` after a successful flash. + pub fn provisions_firmware_hash(&self) -> bool { + let extracted = self.choice.fw_filename == firmware::EXTRACTED_FIRMWARE; + self.choice.platform == model::PLATFORM_ESP32 + || (self.choice.platform == model::PLATFORM_NRF52 && !extracted) + } +} + +/// Upstream `clear()`: `os.system('clear')`, which only draws on a terminal. +fn clear() { + let mut stdout = std::io::stdout().lock(); + if stdout.is_terminal() { + let _ = write!(stdout, "\x1b[H\x1b[2J\x1b[3J"); + let _ = stdout.flush(); + } +} + +fn show(text: &str) { + let mut stdout = std::io::stdout().lock(); + let _ = write!(stdout, "{text}"); + let _ = stdout.flush(); +} + +/// One `input()` line without its newline; `None` at end of input. +fn read_line() -> Option { + let mut line = String::new(); + match std::io::stdin().lock().read_line(&mut line) { + Ok(0) | Err(_) => None, + Ok(_) => Some(line.trim_end_matches(['\n', '\r']).to_string()), + } +} + +fn describe(port: &serialport::SerialPortInfo) -> (String, String) { + match &port.port_type { + serialport::SerialPortType::UsbPort(info) => ( + info.product.clone().unwrap_or_else(|| "None".to_string()), + info.serial_number + .clone() + .unwrap_or_else(|| "None".to_string()), + ), + _ => ("None".to_string(), "None".to_string()), + } +} + +/// Upstream's `args.autoinstall` block. On success the options are set for +/// the key, flash and bootstrap steps; `Err` is upstream's exit. +pub fn run(args: &mut Args) -> Result { + clear(); + if args.port.is_none() { + show(INTRO); + if read_line().is_none() { + eprintln!("rnodeconf-rs: EOF when reading a line"); + return Err(ExitCode::from(1)); + } + } + super::QUIET_UNVERIFIED.store(true, Ordering::Relaxed); + + let ports = serialport::available_ports().unwrap_or_default(); + let (port_path, serial) = match args.port.clone() { + None => { + let listed: Vec<_> = ports.iter().rev().collect(); + out("Detected serial ports:"); + for (i, port) in listed.iter().enumerate() { + let (product, serial) = describe(port); + out(format!( + " [{}] {} ({product}, {serial})", + i + 1, + port.port_name + )); + } + show("\nEnter the number of the serial port your device is connected to:\n? "); + let chosen = int(read_line()) + .filter(|c| *c >= 1 && *c as usize <= listed.len()) + .map(|c| listed[c as usize - 1]); + let Some(port) = chosen else { + out("That port does not exist, exiting now."); + return Err(ExitCode::SUCCESS); + }; + let (product, serial) = describe(port); + clear(); + out(format!( + "\nOk, using device on {} ({product}, {serial})", + port.port_name + )); + (port.port_name.clone(), (serial != "None").then_some(serial)) + } + Some(path) => { + let Some(port) = ports.iter().find(|port| port.port_name == path) else { + out(format!("Could not find specified port {path}, exiting now")); + return Err(ExitCode::SUCCESS); + }; + let (_, serial) = describe(port); + out(format!("\nUsing device on {path}")); + (path, (serial != "None").then_some(serial)) + } + }; + + out("\nProbing device..."); + let port = match open_serial(&port_path) { + Ok(port) => port, + Err(error) => { + log("Could not open the specified serial port. The contained exception was:"); + log(error.to_string()); + return Err(ExitCode::SUCCESS); + } + }; + let mut rnode = RNode::new(port, port_path.clone()); + rnode.usb_serial_id = serial; + if rnode.device_probe().is_err() { + log("No answer from device"); + } + let detected = rnode.detected == Some(true); + if detected { + log("Trying to read EEPROM..."); + if rnode.download_eeprom().is_err() { + return Err(graceful_exit(&mut rnode, 1)); + } + } + let provisioned_and_signed = rnode.eeprom.as_deref().is_some_and(|image| { + matches!(parse_eeprom(image, &rnode.name), ParsedEeprom::Device(Some(device)) if device.signature.valid) + }); + if provisioned_and_signed { + out("\nThis device is already installed and provisioned. No further action will"); + out("be taken. If you wish to completely reinstall this device, you must first"); + out("wipe the current EEPROM. See the help for more info.\n\nExiting now."); + return Err(graceful_exit(&mut rnode, 0)); + } + + let mut ask = |prompt: Prompt| { + match prompt { + Prompt::Notice(text) => { + clear(); + show(text); + } + Prompt::Menu(text) => show(text), + } + read_line() + }; + let mut choice = match choose(detected, &mut ask) { + Ok(choice) => choice, + Err(Stop::Message(line)) => { + out(line); + return Err(graceful_exit(&mut rnode, 0)); + } + Err(Stop::NoFirmware) => { + show(NO_FIRMWARE); + out(""); + super::print_donation_block(); + out(""); + return Err(graceful_exit(&mut rnode, 0)); + } + }; + if args.use_extracted { + choice.fw_filename = firmware::EXTRACTED_FIRMWARE.to_string(); + } + + clear(); + let band = model::model_info(choice.model).map_or("", |info| info.band); + out(""); + out("------------------------------------------------------------------------------"); + out(" Installer Ready"); + out(""); + out("Ok, that should be all the information we need. Please confirm the following"); + out("summary before proceeding. In the next step, the device will be flashed and"); + out("provisioned, so make sure that you are satisfied with your choices.\n"); + out(format!("Serial port : {port_path}")); + out(format!( + "Device type : {} {band}", + model::product_name(choice.product).unwrap_or_default() + )); + out(format!( + "Platform : {}", + model::platform_name(choice.platform).unwrap_or_default() + )); + out(format!( + "Device MCU : {}", + model::mcu_name(choice.mcu).unwrap_or_default() + )); + out(format!("Firmware file : {}", choice.fw_filename)); + out(""); + out("------------------------------------------------------------------------------"); + show("\nIs the above correct? [y/N] "); + if read_line().map(|line| line.to_lowercase()).as_deref() != Some("y") { + out("OK, aborting now."); + return Err(graceful_exit(&mut rnode, 0)); + } + + args.key = true; + args.port = Some(port_path); + args.hwrev = Some(1); + args.update = false; + args.flash = true; + + log("Checking firmware file availability..."); + let paths = match super::rnodeconf_cache_paths() { + Ok(paths) => paths, + Err(error) => { + log("Could not obain firmware package for your board"); + log(format!("The contained exception was: {error}")); + return Err(graceful_exit(&mut rnode, 0)); + } + }; + let mut selection = Selection { + version: args.fw_version.clone(), + hash: None, + }; + let source = Source { + fw_url: args.fw_url.as_deref(), + nocheck: args.nocheck, + }; + if let Err(code) = + firmware::ensure_firmware_file(&paths, &choice.fw_filename, &mut selection, source) + { + return Err(graceful_exit(&mut rnode, code)); + } + rnode.close(); + Ok(Plan { + choice, + version: selection.version.unwrap_or_default(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every menu path upstream's own installer takes (fixture made by its + /// generator from rnodeconf 2.5.0) selects the same board and firmware here. + #[test] + fn menu_answers_select_what_upstream_selects() { + let golden: serde_json::Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/rnodeconf_autoinstall/choices.json" + )) + .unwrap(); + for case in golden["cases"].as_array().unwrap() { + let mut answers = case["answers"] + .as_array() + .unwrap() + .iter() + .map(|a| a.as_str().unwrap().to_string()) + .collect::>() + .into_iter(); + let result = choose(false, &mut |_| answers.next()); + let label = &case["answers"]; + match case["stop"].as_str() { + Some(line) => match result { + Err(Stop::Message(got)) => assert_eq!(got, line, "{label}"), + other => panic!("{label}: expected exit {line:?}, got {other:?}"), + }, + None => { + let choice = result.unwrap_or_else(|stop| panic!("{label}: {stop:?}")); + let expected = Choice { + product: case["product"].as_u64().unwrap() as u8, + model: case["model"].as_u64().unwrap() as u8, + platform: case["platform"].as_u64().unwrap() as u8, + mcu: case["mcu"].as_u64().unwrap() as u8, + fw_filename: case["fw_filename"].as_str().unwrap().to_string(), + }; + assert_eq!(choice, expected, "{label}"); + } + } + } + } +} diff --git a/crates/rns-tools/src/commands/rnodeconf/plan.rs b/crates/rns-tools/src/commands/rnodeconf/plan.rs deleted file mode 100644 index 99577df..0000000 --- a/crates/rns-tools/src/commands/rnodeconf/plan.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! Operations this build refuses, checked where upstream `rnodeconf` would -//! start them. - -use super::Args; - -/// Flows upstream runs without a serial port. -pub fn refusal_without_port(args: &Args) -> Option { - if args.autoinstall { - return Some("firmware autoinstall is not implemented yet".to_string()); - } - None -} - -#[cfg(test)] -mod tests { - use clap::Parser; - - use super::*; - - fn args(list: &[&str]) -> Args { - Args::parse_from(std::iter::once("rnodeconf").chain(list.iter().copied())) - } - - #[test] - fn only_autoinstall_is_refused() { - assert!(refusal_without_port(&args(&["-a"])).is_some()); - for list in [ - &["--flash", "p"][..], - &["--update", "p"][..], - &["--rom", "p"][..], - &["--eeprom-wipe", "p"][..], - &["-e", "p"][..], - ] { - assert!(refusal_without_port(&args(list)).is_none(), "{list:?}"); - } - } -} diff --git a/crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/choices.json b/crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/choices.json new file mode 100644 index 0000000..cc80acb --- /dev/null +++ b/crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/choices.json @@ -0,0 +1,95 @@ +{"provenance": {"generator": "crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/generate.py", "rns_version": "1.6.0"}, +"cases": [ +{"answers":["1","1","n"],"product":3,"model":162,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_ng21.zip"}, +{"answers":["1","2","n"],"product":3,"model":167,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_ng21.zip"}, +{"answers":["1","3","n"],"product":3,"model":164,"platform":144,"mcu":145,"fw_filename":"rnode_firmware.hex"}, +{"answers":["1","4","n"],"product":3,"model":169,"platform":144,"mcu":145,"fw_filename":"rnode_firmware.hex"}, +{"answers":["1","5","n"],"product":3,"model":161,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_t3s3.zip"}, +{"answers":["1","6","n"],"product":3,"model":166,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_t3s3.zip"}, +{"answers":["1","7","n"],"stop":"That model does not exist, exiting now."}, +{"answers":["2","","1","1","n"],"product":240,"model":254,"platform":144,"mcu":145,"fw_filename":"rnode_firmware.hex"}, +{"answers":["2","","1","2","n"],"product":240,"model":255,"platform":144,"mcu":145,"fw_filename":"rnode_firmware.hex"}, +{"answers":["2","","1","3","n"],"product":240,"model":255,"platform":144,"mcu":145,"fw_filename":"rnode_firmware.hex"}, +{"answers":["2","","2","1","n"],"product":240,"model":254,"platform":144,"mcu":146,"fw_filename":"rnode_firmware_m2560.hex"}, +{"answers":["2","","2","2","n"],"product":240,"model":255,"platform":144,"mcu":146,"fw_filename":"rnode_firmware_m2560.hex"}, +{"answers":["2","","2","3","n"],"product":240,"model":255,"platform":144,"mcu":146,"fw_filename":"rnode_firmware_m2560.hex"}, +{"answers":["2","","3","1","1","n"],"product":240,"model":254,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_featheresp32.zip"}, +{"answers":["2","","3","2","1","n"],"product":240,"model":255,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_featheresp32.zip"}, +{"answers":["2","","3","3","1","n"],"product":240,"model":255,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_featheresp32.zip"}, +{"answers":["2","","3","1","2","n"],"product":240,"model":254,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_esp32_generic.zip"}, +{"answers":["2","","3","1","3","n"],"stop":"That ESP32 board does not exist, exiting now."}, +{"answers":["2","","4","n"],"stop":"That MCU type does not exist, exiting now."}, +{"answers":["2","","1","4","n"],"stop":"That transceiver type does not exist, exiting now."}, +{"answers":["3","","1","n"],"product":177,"model":180,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v21.zip"}, +{"answers":["3","","2","n"],"product":177,"model":185,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v21.zip"}, +{"answers":["3","","3","n"],"product":177,"model":4,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v21_tcxo.zip"}, +{"answers":["3","","4","n"],"product":177,"model":9,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v21_tcxo.zip"}, +{"answers":["3","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["4","","1","n"],"product":176,"model":179,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v20.zip"}, +{"answers":["4","","2","n"],"product":176,"model":184,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v20.zip"}, +{"answers":["4","","3","n"],"product":176,"model":184,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v20.zip"}, +{"answers":["4","","4","n"],"product":176,"model":184,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v20.zip"}, +{"answers":["4","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["5","","1","n"],"product":178,"model":186,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v10.zip"}, +{"answers":["5","","2","n"],"product":178,"model":187,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v10.zip"}, +{"answers":["5","","3","n"],"product":178,"model":187,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v10.zip"}, +{"answers":["5","","4","n"],"product":178,"model":187,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_lora32v10.zip"}, +{"answers":["5","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["6","","1","n"],"product":224,"model":228,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tbeam.zip"}, +{"answers":["6","","2","n"],"product":224,"model":233,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tbeam.zip"}, +{"answers":["6","","3","n"],"product":224,"model":227,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tbeam_sx1262.zip"}, +{"answers":["6","","4","n"],"product":224,"model":232,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tbeam_sx1262.zip"}, +{"answers":["6","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["7","","1","n"],"product":192,"model":196,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v2.zip"}, +{"answers":["7","","2","n"],"product":192,"model":201,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v2.zip"}, +{"answers":["7","","3","n"],"product":192,"model":201,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v2.zip"}, +{"answers":["7","","4","n"],"product":192,"model":201,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v2.zip"}, +{"answers":["7","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["8","","1","n"],"product":193,"model":197,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v3.zip"}, +{"answers":["8","","2","n"],"product":193,"model":202,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v3.zip"}, +{"answers":["8","","3","n"],"product":193,"model":202,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v3.zip"}, +{"answers":["8","","4","n"],"product":193,"model":202,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v3.zip"}, +{"answers":["8","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["9","","1","n"],"product":195,"model":200,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v4pa.zip"}, +{"answers":["9","","2","n"],"product":195,"model":200,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v4pa.zip"}, +{"answers":["9","","3","n"],"product":195,"model":200,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v4pa.zip"}, +{"answers":["9","","4","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["10","","1","n"],"product":3,"model":165,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_t3s3_sx127x.zip"}, +{"answers":["10","","2","n"],"product":3,"model":170,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_t3s3_sx127x.zip"}, +{"answers":["10","","3","n"],"product":3,"model":161,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_t3s3.zip"}, +{"answers":["10","","4","n"],"product":3,"model":166,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_t3s3.zip"}, +{"answers":["10","","5","n"],"product":3,"model":172,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_t3s3_sx1280_pa.zip"}, +{"answers":["10","","6","n"],"stop":"That model does not exist, exiting now."}, +{"answers":["11","","1","n"],"product":16,"model":17,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_rak4631.zip"}, +{"answers":["11","","2","n"],"product":16,"model":18,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_rak4631.zip"}, +{"answers":["11","","3","n"],"product":16,"model":18,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_rak4631.zip"}, +{"answers":["11","","4","n"],"product":16,"model":18,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_rak4631.zip"}, +{"answers":["11","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["12","","1","n"],"product":21,"model":22,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_techo.zip"}, +{"answers":["12","","2","n"],"product":21,"model":23,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_techo.zip"}, +{"answers":["12","","3","n"],"product":21,"model":23,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_techo.zip"}, +{"answers":["12","","4","n"],"product":21,"model":23,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_techo.zip"}, +{"answers":["12","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["13","","1","n"],"product":234,"model":219,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tbeam_supreme.zip"}, +{"answers":["13","","2","n"],"product":234,"model":220,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tbeam_supreme.zip"}, +{"answers":["13","","3","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["14","","1","n"],"product":208,"model":212,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tdeck.zip"}, +{"answers":["14","","2","n"],"product":208,"model":217,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_tdeck.zip"}, +{"answers":["14","","3","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["15","","1","n"],"product":194,"model":198,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_heltec_t114.zip"}, +{"answers":["15","","2","n"],"product":194,"model":199,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_heltec_t114.zip"}, +{"answers":["15","","3","n"],"product":194,"model":199,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_heltec_t114.zip"}, +{"answers":["15","","4","n"],"product":194,"model":199,"platform":112,"mcu":113,"fw_filename":"rnode_firmware_heltec_t114.zip"}, +{"answers":["15","","5","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["16","","1","n"],"product":235,"model":222,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_xiao_esp32s3.zip"}, +{"answers":["16","","2","n"],"product":235,"model":221,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_xiao_esp32s3.zip"}, +{"answers":["16","","3","n"],"stop":"That band does not exist, exiting now."}, +{"answers":["0"],"stop":"That device type does not exist, exiting now."}, +{"answers":["17"],"stop":"That device type does not exist, exiting now."}, +{"answers":["x"],"stop":"That device type does not exist, exiting now."}, +{"answers":["2"],"stop":"That device type does not exist, exiting now."}, +{"answers":["","n"],"stop":"That device type does not exist, exiting now."}, +{"answers":["3","","x"],"stop":"That band does not exist, exiting now."}, +{"answers":["8","","2","n"],"product":193,"model":202,"platform":128,"mcu":129,"fw_filename":"rnode_firmware_heltec32v3.zip"}, +{"answers":["2",""," 1 ","1","n"],"product":240,"model":254,"platform":144,"mcu":145,"fw_filename":"rnode_firmware.hex"} +]} diff --git a/crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/generate.py b/crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/generate.py new file mode 100644 index 0000000..d2d42c9 --- /dev/null +++ b/crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/generate.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Autoinstall menu choices for rnodeconf-rs, from upstream rnodeconf --autoinstall. + +The `if args.autoinstall:` block of rnodeconf.main() is lifted with ast and run +with a stand-in port list and RNode (nothing is opened or flashed). Each case +feeds menu answers through input() and stops at the confirmation, then records +the product, model, platform, MCU and firmware file upstream selected, or the +message it exited with. + +Usage: generate.py [OUT] (default: choices.json beside this file) +""" +import ast, io, json, os, sys, tempfile +from contextlib import redirect_stdout + +HERE = os.path.dirname(os.path.abspath(__file__)) +WORKSPACE = os.path.abspath(os.path.join(HERE, "..", "..", "..", "..", "..", "..")) +RNS_DIR = os.environ.get("RATSPEAK_UPSTREAM_RETICULUM_DIR") or os.path.join(WORKSPACE, "upstream", "Reticulum") +sys.path.insert(0, RNS_DIR) +os.environ["HOME"] = tempfile.mkdtemp(prefix="rnodeconf-home-") +import RNS +assert RNS.__version__ == "1.6.0", RNS.__version__ +assert os.path.realpath(RNS.__file__).startswith(os.path.realpath(RNS_DIR) + os.sep), RNS.__file__ +from RNS.Utilities import rnodeconf as rc +OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "choices.json") + +src = open(rc.__file__).read() +main = next(n for n in ast.walk(ast.parse(src)) if isinstance(n, ast.FunctionDef) and n.name == "main") +block = next(n for n in ast.walk(main) if isinstance(n, ast.If) and ast.unparse(n.test) == "args.autoinstall") +code = compile(ast.Module(body=[block], type_ignores=[]), rc.__file__, "exec") + + +class Port: + device, product, serial_number = "/dev/stand-in", "stand-in", "0001" + + +class Device: + detected = provisioned = signature_valid = False + def __init__(self, serial): pass + def readLoop(self): pass + def device_probe(self): pass + def download_eeprom(self): pass + def disconnect(self): pass + + +class Args: + autoinstall, port, use_extracted = True, Port.device, False + + +class Stop(Exception): + pass + + +def run(answers): + feed = list(answers) + def ask(*_): + if not feed: + raise EOFError("EOF when reading a line") + return feed.pop(0) + def stop(code=0): + raise Stop(code) + ns = dict(vars(rc)) + ns.update(args=Args(), input=ask, clear=lambda: None, graceful_exit=stop, exit=stop, RNode=Device, + rnode_open_serial=lambda path: None) + ns["list_ports"] = type("lp", (), {"comports": staticmethod(lambda: [Port()])}) + buf = io.StringIO() + with redirect_stdout(buf): + try: + exec(code, ns) + except Stop: + pass + text = buf.getvalue().rstrip("\n").splitlines() + if "Is the above correct? [y/N] OK, aborting now." in (text[-1] if text else ""): + return {"product": ns["selected_product"], "model": ns["selected_model"], "platform": ns["selected_platform"], + "mcu": ns["selected_mcu"], "fw_filename": ns["fw_filename"]} + return {"stop": text[-1].removeprefix("? ") if text else ""} # the prompt shares the line + + +# Answers per device: (device answer, needs an Enter for its notice, list of answer tails). +NOTICE = {n for n in range(2, 17)} +TAILS = {1: [["1"], ["2"], ["3"], ["4"], ["5"], ["6"], ["7"]], + 2: [[m, t] + (["1"] if m == "3" else []) for m in ("1", "2", "3") for t in ("1", "2", "3")] + [["3", "1", "2"], ["3", "1", "3"], ["4"], ["1", "4"]], + 10: [[c] for c in ("1", "2", "3", "4", "5", "6")]} +for n, top in {3: 4, 4: 4, 5: 4, 6: 4, 7: 4, 8: 4, 9: 3, 11: 4, 12: 4, 13: 2, 14: 2, 15: 4, 16: 2}.items(): + TAILS[n] = [[str(c)] for c in range(1, top + 2)] +cases = [] +for n in range(1, 17): + for tail in TAILS[n]: + answers = [str(n)] + ([""] if n in NOTICE else []) + tail + ["n"] + cases.append({"answers": answers, **run(answers)}) +for answers in (["0"], ["17"], ["x"], ["2"], ["", "n"], ["3", "", "x"], ["8", "", "2", "n"], ["2", "", " 1 ", "1", "n"]): + cases.append({"answers": answers, **run(answers)}) +with open(OUT, "w") as f: + f.write('{"provenance": ' + json.dumps({"generator": "crates/rns-tools/tests/fixtures/rnodeconf_autoinstall/generate.py", + "rns_version": RNS.__version__}) + ',\n"cases": [\n') + f.write(",\n".join(json.dumps(c, separators=(",", ":")) for c in cases)) + f.write("\n]}\n") +print(len(cases), "cases")