From 66fe83902075d031973fa06423d82d45346c50af Mon Sep 17 00:00:00 2001 From: noah Date: Fri, 18 Sep 2026 10:25:15 -0600 Subject: [PATCH] GUI: real PIC detection via on-board SSH + i2c probe (right-click action) asic-rs and the miner's network API cannot report PIC-vs-noPIC (only one legacy SKU, ANTMINER S19J88NOPIC, carries it in the model string; the authoritative signal lives on the control board's I2C bus). So this builds the real detector ON TOP of asic-rs as an opt-in SSH probe, per the project wiki (30-power-thermal-and-board-identity/hashboard-eeprom-pic.md): - pic_probe.rs: SSH to the control board and run i2cdump -y 0x48 b, then discriminate by the register period -- a PIC/MCU board exposes an 8-byte register file that WRAPS every 8 bytes ("17 00 4b 50 7f 00 00 00 ..."), while a noPIC board has a 4-register LM75 temp sensor (4-byte wrap). The classifier is pure + unit-tested against the wiki's example dumps and is conservative (indeterminate -> None, never a guess). The I2C bus is chosen from the control-board family (AMLogic->1, BeagleBone->0, else try both). We shell out to ssh/sshpass (no SSH crate) so the offline/vendored build is unaffected. - Right-click "Detect PIC (SSH)..." on the selected miners: a dialog collects SSH login (prefilled from a new 0600 ssh-credentials.txt, default user root), then start_pic_probe runs one miner at a time on a background thread (each is a slow SSH round trip; never part of the fast network scan) and upserts pic_present into the rows as results arrive. Fake-scan mode returns deterministic demo results. Guarded against a firmware flash / concurrent probe. The classifier is unit-tested; the live SSH round-trip needs a reachable bench miner with SSH + i2c-tools to verify end-to-end. cargo check --release --tests clean. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh --- crates/alkane-gui/src/credentials.rs | 51 ++++-- crates/alkane-gui/src/main.rs | 1 + crates/alkane-gui/src/pic_probe.rs | 223 +++++++++++++++++++++++++++ crates/alkane-gui/src/scan.rs | 83 ++++++++++ crates/alkane-gui/src/ui.rs | 169 ++++++++++++++++++++ 5 files changed, 517 insertions(+), 10 deletions(-) create mode 100644 crates/alkane-gui/src/pic_probe.rs diff --git a/crates/alkane-gui/src/credentials.rs b/crates/alkane-gui/src/credentials.rs index ea07fbac..f6639a51 100644 --- a/crates/alkane-gui/src/credentials.rs +++ b/crates/alkane-gui/src/credentials.rs @@ -14,20 +14,24 @@ use asic_rs::core::traits::miner::MinerAuth; use crate::scan::config_path; pub const CREDENTIALS_FILE: &str = "scan-credentials.txt"; +/// SSH login for the control board (used by the PIC probe; distinct from the +/// web/API scan credentials above -- miners' SSH root login is usually not the +/// same account as the web digest-auth login). +pub const SSH_CREDENTIALS_FILE: &str = "ssh-credentials.txt"; -/// Load the saved miner username/password, if any were saved. -pub fn load_credentials() -> Option<(String, String)> { - let s = std::fs::read_to_string(config_path(CREDENTIALS_FILE)).ok()?; +/// Load a saved username/password pair from `file`, if present. +fn load_creds_file(file: &str) -> Option<(String, String)> { + let s = std::fs::read_to_string(config_path(file)).ok()?; let mut lines = s.lines(); let user = lines.next()?.to_string(); let pass = lines.next().unwrap_or("").to_string(); Some((user, pass)) } -/// Save the miner username/password, restricting the file to owner -/// read/write (credentials are plaintext on disk, so the mode matters). -pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> { - let p = config_path(CREDENTIALS_FILE); +/// Save a username/password pair to `file`, restricting it to owner read/write +/// (credentials are plaintext on disk, so the mode matters). +fn save_creds_file(file: &str, user: &str, pass: &str) -> std::io::Result<()> { + let p = config_path(file); if let Some(dir) = p.parent() { std::fs::create_dir_all(dir)?; } @@ -47,15 +51,42 @@ pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> { Ok(()) } -/// Remove the saved credentials, if any. Not an error if none were saved. -pub fn clear_credentials() -> std::io::Result<()> { - match std::fs::remove_file(config_path(CREDENTIALS_FILE)) { +fn clear_creds_file(file: &str) -> std::io::Result<()> { + match std::fs::remove_file(config_path(file)) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(e), } } +/// Load the saved miner web/API username/password, if any were saved. +pub fn load_credentials() -> Option<(String, String)> { + load_creds_file(CREDENTIALS_FILE) +} + +/// Save the miner web/API username/password (0600). +pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> { + save_creds_file(CREDENTIALS_FILE, user, pass) +} + +/// Load the saved SSH username/password for the PIC probe, if any. +pub fn load_ssh_credentials() -> Option<(String, String)> { + load_creds_file(SSH_CREDENTIALS_FILE) +} + +/// Save the SSH username/password for the PIC probe (0600). +pub fn save_ssh_credentials(user: &str, pass: &str) -> std::io::Result<()> { + save_creds_file(SSH_CREDENTIALS_FILE, user, pass) +} + +/// Remove the saved web/API credentials, if any. Not an error if none were saved. +pub fn clear_credentials() -> std::io::Result<()> { + match clear_creds_file(CREDENTIALS_FILE) { + Ok(()) => Ok(()), + Err(e) => Err(e), + } +} + /// Build a `MinerFactory` with the saved credentials (if any) applied as /// discovery auth for every firmware backend, so scans, refreshes, config /// actions, and firmware flashes all authenticate against a non-default diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 87a9d8e0..bdc4402d 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -4,6 +4,7 @@ mod credentials; mod fixtures; mod model; +mod pic_probe; mod presets; mod scan; mod ui; diff --git a/crates/alkane-gui/src/pic_probe.rs b/crates/alkane-gui/src/pic_probe.rs new file mode 100644 index 00000000..367d5fe9 --- /dev/null +++ b/crates/alkane-gui/src/pic_probe.rs @@ -0,0 +1,223 @@ +//! Real PIC-vs-noPIC detection for Antminer control boards, over SSH + i2c-tools. +//! +//! asic-rs and the miner's network API cannot report PIC presence (see the +//! project wiki, 30-power-thermal-and-board-identity/hashboard-eeprom-pic.md); +//! the authoritative tell lives on the control board's I2C bus. On a +//! PIC/MCU-equipped board, I2C 0x48 is a hashboard MCU exposing an 8-byte +//! register file that WRAPS every 8 bytes (e.g. `17 00 4b 50 7f 00 00 00 ...`); +//! on a noPIC board, 0x48 is a plain LM75 temperature sensor with a 4-register +//! layout that wraps every 4 bytes. We read 0x48 with `i2cdump` over SSH and +//! discriminate by that period. +//! +//! This is a slow, credentialed, opt-in probe (an SSH handshake + shell command +//! per miner), never part of the fast network scan. We shell out to `ssh` +//! (via `sshpass` for password auth) rather than pull in an SSH crate, so the +//! offline/vendored build is unaffected. + +use std::process::Command; +use std::time::Duration; + +/// SSH login for the miner's control board (distinct from the web/API creds). +#[derive(Debug, Clone)] +pub struct SshCreds { + pub user: String, + /// Empty means key-based auth (BatchMode); otherwise `sshpass` is used. + pub pass: String, +} + +/// Which I2C bus to probe, chosen from the control-board family. AMLogic uses +/// i2c-1, BeagleBone uses i2c-0; for anything else (Xilinx/CVITek/unknown) we +/// try both. The wiki confirms the AML/BB buses; Zynx/CVITek are unconfirmed. +pub fn bus_candidates(control_board: &str) -> Vec { + let cb = control_board.to_lowercase(); + if cb.contains("amlogic") || cb.contains("aml") { + vec![1] + } else if cb.contains("beaglebone") || cb.contains("bb") { + vec![0] + } else { + vec![1, 0] + } +} + +/// Classify an `i2cdump -y 0x48 b` dump: `Some(true)` = PIC (8-byte MCU +/// register file), `Some(false)` = noPIC (4-register LM75), `None` = couldn't +/// tell (address unresponsive, no periodicity, or unparseable). Conservative: +/// anything ambiguous is `None`, never a guess. +pub fn classify_i2cdump(stdout: &str) -> Option { + let bytes = parse_dump_offset0(stdout)?; + // An LM75's 4 registers repeat every 4 bytes; check that first because a + // period-4 sequence is trivially also period-8. + let period4 = (0..12).all(|i| bytes[i] == bytes[i + 4]); + if period4 { + return Some(false); // LM75 -> noPIC + } + let period8 = (0..8).all(|i| bytes[i] == bytes[i + 8]); + if period8 { + return Some(true); // 8-byte MCU register file -> PIC + } + None +} + +/// Parse the 16 bytes of the `00:` row of an `i2cdump ... b` output. Returns +/// `None` if the row is missing or any cell is unreadable ("XX"). +fn parse_dump_offset0(stdout: &str) -> Option<[u8; 16]> { + let line = stdout.lines().find_map(|l| { + let l = l.trim(); + l.strip_prefix("00:").map(str::trim_start) + })?; + // The row is "<16 hex/XX cells> "; take the first 16 cells. + let mut out = [0u8; 16]; + let mut n = 0; + for tok in line.split_whitespace() { + if n == 16 { + break; + } + if tok.len() != 2 { + break; // reached the ascii gutter + } + match u8::from_str_radix(tok, 16) { + Ok(b) => { + out[n] = b; + n += 1; + } + Err(_) => return None, // "XX" = no response -> indeterminate + } + } + (n == 16).then_some(out) +} + +/// Build the ssh argv for one `i2cdump` on `bus`. Uses `sshpass -p ` when +/// a password is set, else relies on key auth (BatchMode). +fn ssh_command(ip: &str, bus: u8, creds: &SshCreds) -> Command { + let remote = format!("i2cdump -y {bus} 0x48 b"); + let target = format!("{}@{ip}", creds.user); + let ssh_opts = [ + "-o", "StrictHostKeyChecking=no", + "-o", "UserKnownHostsFile=/dev/null", + "-o", "ConnectTimeout=6", + "-o", "NumberOfPasswordPrompts=1", + ]; + if creds.pass.is_empty() { + let mut c = Command::new("ssh"); + c.arg("-o").arg("BatchMode=yes"); + c.args(ssh_opts).arg(&target).arg(&remote); + c + } else { + // sshpass reads the password from the env var named after -e's default, + // but we use -p for simplicity; the password never reaches the argv of + // a child that logs it (sshpass scrubs its own argv). + let mut c = Command::new("sshpass"); + c.arg("-p").arg(&creds.pass).arg("ssh"); + c.args(ssh_opts).arg(&target).arg(&remote); + c + } +} + +/// Probe one miner's PIC state over SSH. Returns `Ok(Some(true/false))` on a +/// confident PIC/noPIC read, `Ok(None)` if reachable but indeterminate, or +/// `Err` on an SSH/connection/auth failure. +pub fn probe_pic(ip: &str, control_board: &str, creds: &SshCreds) -> Result, String> { + let mut last_err = String::from("no i2c bus responded"); + for bus in bus_candidates(control_board) { + match run_probe(ip, bus, creds) { + Ok(Some(v)) => return Ok(Some(v)), + Ok(None) => last_err = format!("i2c-0x48 on bus {bus} was indeterminate"), + Err(e) => return Err(e), // an auth/connection error won't improve on another bus + } + } + // Reachable but couldn't classify on any candidate bus. + let _ = last_err; + Ok(None) +} + +fn run_probe(ip: &str, bus: u8, creds: &SshCreds) -> Result, String> { + let out = wait_with_timeout(ssh_command(ip, bus, creds), Duration::from_secs(12))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + // A failed i2cdump on this bus (e.g. bus doesn't exist) is not fatal -- + // let the caller try the next bus. But an SSH/auth failure is fatal. + let e = err.trim().to_string(); + if e.to_lowercase().contains("permission denied") + || e.to_lowercase().contains("connection") + || e.to_lowercase().contains("timed out") + || e.to_lowercase().contains("no route") + || e.to_lowercase().contains("host key") + { + return Err(if e.is_empty() { "ssh failed".into() } else { e }); + } + return Ok(None); + } + Ok(classify_i2cdump(&String::from_utf8_lossy(&out.stdout))) +} + +/// Run a command with a wall-clock timeout (SSH can hang on a dead host). +fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result { + use std::io::Read; + cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + let mut child = cmd.spawn().map_err(|e| format!("spawn ssh: {e}"))?; + let start = std::time::Instant::now(); + loop { + match child.try_wait().map_err(|e| e.to_string())? { + Some(status) => { + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + if let Some(mut o) = child.stdout.take() { + let _ = o.read_to_end(&mut stdout); + } + if let Some(mut e) = child.stderr.take() { + let _ = e.read_to_end(&mut stderr); + } + return Ok(std::process::Output { status, stdout, stderr }); + } + None => { + if start.elapsed() >= timeout { + let _ = child.kill(); + return Err("ssh timed out".into()); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classify_pic_from_wiki_dump() { + // The wiki's PIC/MCU board dump: 8-byte register file that wraps. + let dump = "\ + 0 1 2 3 4 5 6 7 8 9 a b c d e f 0123456789abcdef +00: 17 00 4b 50 7f 00 00 00 17 00 4b 50 7f 00 00 00 ................ +10: 17 00 4b 50 7f 00 00 00 17 00 4b 50 7f 00 00 00 ................"; + assert_eq!(classify_i2cdump(dump), Some(true), "8-byte wrap -> PIC"); + } + + #[test] + fn classify_nopic_from_lm75() { + // An LM75 has 4 registers (temp/config/Thyst/Tos) that wrap every 4. + let dump = "\ + 0 1 2 3 4 5 6 7 8 9 a b c d e f 0123456789abcdef +00: 19 00 4b 50 19 00 4b 50 19 00 4b 50 19 00 4b 50 ................"; + assert_eq!(classify_i2cdump(dump), Some(false), "4-register LM75 -> noPIC"); + } + + #[test] + fn classify_indeterminate() { + // No response (XX) or no periodicity -> None (never a guess). + let xx = "00: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX"; + assert_eq!(classify_i2cdump(xx), None); + let noisy = "00: 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10"; + assert_eq!(classify_i2cdump(noisy), None); + assert_eq!(classify_i2cdump("no offset row here"), None); + } + + #[test] + fn bus_from_control_board() { + assert_eq!(bus_candidates("AMLogic"), vec![1]); + assert_eq!(bus_candidates("BeagleBone Black"), vec![0]); + assert_eq!(bus_candidates("Xilinx"), vec![1, 0]); + assert_eq!(bus_candidates(""), vec![1, 0]); + } +} diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index 7399ebc8..7aa0df92 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -905,6 +905,89 @@ pub fn start_firmware_flash_action(ips: Vec, image: FirmwareImage) -> Ac ActionHandle { rx, cancel } } +/// Progress/results from a background SSH PIC probe of specific miners. +pub enum PicProbeMsg { + Started { total: usize }, + /// One miner's PIC result: `pic` = Some(true/false)/None (indeterminate), + /// or `error` set on an SSH/connection failure. + Result { ip: String, pic: Option, error: Option }, + Done { total: usize }, +} + +/// A running PIC probe; `stop` cancels the remaining miners. +pub struct PicProbeHandle { + pub rx: Receiver, + cancel: Arc, +} + +impl PicProbeHandle { + pub fn stop(&self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +/// Probe the PIC state of `targets` (ip + control-board string) over SSH on a +/// background thread, one miner at a time (each is a slow SSH round trip). In +/// fake-scan mode it reports simulated results without touching the network. +pub fn start_pic_probe( + targets: Vec<(String, String)>, + creds: crate::pic_probe::SshCreds, +) -> PicProbeHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = targets.len(); + let _ = tx.send(PicProbeMsg::Started { total }); + + if fake_scan_enabled() { + let err_tx = tx.clone(); + let thread_cancel = cancel.clone(); + let res = std::thread::Builder::new().name("fake-pic-probe".into()).spawn(move || { + for (ip, cb) in targets { + if thread_cancel.load(Ordering::Relaxed) { + break; + } + // Deterministic demo: Antminer S21 (CVITek) noPIC, other + // Antminers PIC, WhatsMiner indeterminate. + let pic = if cb.to_lowercase().contains("cvitek") { + Some(false) + } else if !cb.is_empty() { + Some(true) + } else { + None + }; + let _ = tx.send(PicProbeMsg::Result { ip, pic, error: None }); + } + let _ = tx.send(PicProbeMsg::Done { total }); + }); + if res.is_err() { + let _ = err_tx.send(PicProbeMsg::Done { total }); + } + return PicProbeHandle { rx, cancel }; + } + + let thread_cancel = cancel.clone(); + let err_tx = tx.clone(); + let res = std::thread::Builder::new().name("pic-probe".into()).spawn(move || { + for (ip, cb) in targets { + if thread_cancel.load(Ordering::Relaxed) { + break; + } + let (pic, error) = match crate::pic_probe::probe_pic(&ip, &cb, &creds) { + Ok(v) => (v, None), + Err(e) => (None, Some(e)), + }; + if tx.send(PicProbeMsg::Result { ip, pic, error }).is_err() { + return; // UI gone + } + } + let _ = tx.send(PicProbeMsg::Done { total }); + }); + if res.is_err() { + let _ = err_tx.send(PicProbeMsg::Done { total }); + } + PicProbeHandle { rx, cancel } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 18b4b499..0cf94848 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -52,6 +52,10 @@ const ID_CTX_RESUME: i32 = 726; const ID_CTX_TUNING: i32 = 727; const ID_CTX_POWER: i32 = 728; const ID_CTX_RESTART: i32 = 729; +const ID_CTX_PIC_PROBE: i32 = 730; +// SSH PIC-probe credentials dialog. +const ID_PICSSH_OK: i32 = 780; +const ID_PICSSH_CANCEL: i32 = 781; // Value-prompt dialog for power-limit / tuning-percent actions. const ID_ACTION_OK: i32 = 740; const ID_ACTION_CANCEL: i32 = 741; @@ -344,6 +348,12 @@ pub struct App { creds_dialog: Widget, creds_user_input: Widget, creds_pass_input: Widget, + // Background SSH PIC probe + its credentials dialog. + pic_probe: Option, + pending_pic_targets: Vec<(String, String)>, + picssh_dialog: Widget, + picssh_user_input: Widget, + picssh_pass_input: Widget, // Saved view presets + the Presets dialog widgets. presets: Vec, presets_dialog: Widget, @@ -536,6 +546,11 @@ pub fn build(frame: Widget) -> App { creds_dialog: frame, creds_user_input: frame, creds_pass_input: frame, + pic_probe: None, + pending_pic_targets: Vec::new(), + picssh_dialog: frame, + picssh_user_input: frame, + picssh_pass_input: frame, presets: crate::presets::load_presets(), presets_dialog: frame, presets_choice: frame, @@ -815,6 +830,9 @@ impl App { // Refresh is always offered for a non-empty selection, independent of // the capability intersection below. menu.menu_append(ID_CTX_REFRESH, "Refresh"); + // Real PIC-vs-noPIC detection via an on-board SSH i2c probe (asic-rs + // cannot report it over the network); offered for any selection. + menu.menu_append(ID_CTX_PIC_PROBE, "Detect PIC (SSH)..."); // Config actions common to the whole selection (capability // intersection): an action is offered only if every selected miner // supports it. @@ -910,6 +928,147 @@ impl App { wx_rs::set_status_text(&msg); } + /// Build the SSH PIC-probe dialog: captures the selected miners, collects + /// SSH credentials (prefilled from the saved SSH login), and on OK runs the + /// on-board i2c probe. Returns None (no dialog) if nothing is selected or a + /// flash holds the exclusive lock. + fn build_pic_probe_dialog(&mut self) -> Option { + if self.flashing { + wx_rs::set_status_text("firmware flash in progress -- wait for it to finish"); + return None; + } + if self.pic_probe.is_some() { + wx_rs::set_status_text("a PIC probe is already running"); + return None; + } + let targets: Vec<(String, String)> = self + .selected_rows() + .iter() + .map(|r| (r.ip.clone(), r.control_board.clone())) + .collect(); + if targets.is_empty() { + return None; + } + self.pending_pic_targets = targets; + let (saved_user, _) = credentials::load_ssh_credentials().unwrap_or_default(); + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, "Detect PIC via SSH"); + let root = Widget::box_sizer(true); + root.add( + Widget::static_text( + dlg, + &format!( + "Probe {} miner(s) over SSH (runs i2cdump on the control board). SSH login for the miner (root, etc.):", + self.pending_pic_targets.len() + ), + ), + 0, + sf::BORDER_ALL, + 8, + ); + let user_row = Widget::box_sizer(false); + user_row.add(Widget::static_text(dlg, "SSH user:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + let user_input = Widget::text_ctrl(dlg, false); + user_input.set_value(if saved_user.is_empty() { "root" } else { &saved_user }); + user_input.set_min_size(180, -1); + user_row.add(user_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + root.add_sizer(user_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); + let pass_row = Widget::box_sizer(false); + pass_row.add(Widget::static_text(dlg, "SSH password:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + let pass_input = Widget::text_ctrl(dlg, false); + pass_input.set_min_size(180, -1); + pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6); + root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); + root.add( + Widget::static_text(dlg, "(Leave the password blank to use SSH key auth.)"), + 0, + sf::BORDER_ALL, + 6, + ); + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add(Widget::button(dlg, "Probe", ID_PICSSH_OK), 0, sf::BORDER_ALL, 6); + btns.add(Widget::button(dlg, "Cancel", ID_PICSSH_CANCEL), 0, sf::BORDER_ALL, 6); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(420, 210); + dlg.fit(dlg); + self.picssh_dialog = dlg; + self.picssh_user_input = user_input; + self.picssh_pass_input = pass_input; + Some(dlg) + } + + /// Start the PIC probe with the SSH credentials just entered. + fn apply_pic_probe(&mut self) { + let user = self.picssh_user_input.get_value().trim().to_string(); + if user.is_empty() { + wx_rs::set_status_text("enter an SSH user"); + return; + } + let pass = self.picssh_pass_input.get_value(); + let _ = credentials::save_ssh_credentials(&user, &pass); + self.picssh_dialog.close(1); + let targets = std::mem::take(&mut self.pending_pic_targets); + let n = targets.len(); + self.pic_probe = Some(scan::start_pic_probe( + targets, + crate::pic_probe::SshCreds { user, pass }, + )); + wx_rs::set_status_text(&format!("probing PIC on {n} miner(s) via SSH...")); + } + + /// Drain the running PIC probe: update each miner's pic_present as its result + /// arrives, and refresh the table + status when done. + fn drain_pic_probe(&mut self) { + let Some(h) = &self.pic_probe else { return }; + let mut status: Option = None; + let mut done = false; + let mut changed = false; + loop { + match h.rx.try_recv() { + Ok(scan::PicProbeMsg::Started { total }) => { + status = Some(format!("PIC probe: 0/{total}...")); + } + Ok(scan::PicProbeMsg::Result { ip, pic, error }) => { + if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) { + if error.is_none() { + r.pic_present = pic; + changed = true; + } + } + status = Some(match (&pic, &error) { + (_, Some(e)) => format!("PIC probe {ip}: {e}"), + (Some(true), _) => format!("PIC probe {ip}: PIC"), + (Some(false), _) => format!("PIC probe {ip}: noPIC"), + (None, _) => format!("PIC probe {ip}: indeterminate"), + }); + } + Ok(scan::PicProbeMsg::Done { total }) => { + status = Some(format!("PIC probe done ({total} miner(s))")); + done = true; + break; + } + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + done = true; + break; + } + } + } + if changed { + self.fill_rows(); + } + if done { + self.pic_probe = None; + self.action_result = status.clone(); + self.action_result_ticks = ACTION_RESULT_TICKS; + } + if let Some(s) = status { + wx_rs::set_status_text(&s); + } + } + /// A menu item was chosen. Direct actions start immediately; the value-input /// actions (power limit / tuning %) return a prompt dialog to show modally. fn on_menu_item(&mut self, id: i32) -> Option { @@ -923,6 +1082,7 @@ impl App { } } ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()), + ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if // any scan / refresh / action is running (re-checked at confirm). @@ -1402,9 +1562,13 @@ impl App { self.drain_scan(); self.drain_action(); self.drain_refresh(); + self.drain_pic_probe(); if self.scanning { return; // status already shows scan progress } + if self.pic_probe.is_some() { + return; // a PIC probe is in flight; keep its status + } if self.action.is_some() { return; // a config action is in flight; keep its status } @@ -2161,6 +2325,11 @@ impl App { ID_COLUMNS_OK => self.apply_columns(), ID_COLUMNS_CANCEL => self.columns_dialog.close(0), ID_PRESETS => return Some(self.build_presets_dialog()), + ID_PICSSH_OK => self.apply_pic_probe(), + ID_PICSSH_CANCEL => { + self.pending_pic_targets.clear(); + self.picssh_dialog.close(0); + } ID_PRESET_LOAD => self.apply_preset_load(), ID_PRESET_SAVE => self.apply_preset_save(), ID_PRESET_DELETE => self.apply_preset_delete(),