Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b5d811b1e | ||
|
|
77399bdd06 | ||
|
|
408b7d12b4 | ||
|
|
50cd463bee | ||
|
|
d73299166e |
@@ -0,0 +1,115 @@
|
||||
//! Real access / lock-state detection: whether this miner accepts privileged
|
||||
//! (credentialed) command writes, or is view-only.
|
||||
//!
|
||||
//! asic-rs has no lock-state signal (a wrong-password miner just silently
|
||||
//! returns fewer fields, because the collector drops the 401). We build the real
|
||||
//! check ON TOP of asic-rs: a NON-mutating, digest-authenticated GET to a
|
||||
//! privileged endpoint. On Antminer every `/cgi-bin/*.cgi` requires digest auth,
|
||||
//! so the HTTP status is decisive -- 200 means our credentials authenticate
|
||||
//! (we can write -> unlocked), 401/403 means they are rejected (view-only ->
|
||||
//! locked). We probe `get_miner_conf.cgi`, which is read-only (never the
|
||||
//! mutating `set_miner_conf.cgi`).
|
||||
//!
|
||||
//! We shell out to `curl --digest` (already present, supports digest auth)
|
||||
//! rather than add an HTTP+digest crate, so the offline/vendored build is
|
||||
//! unaffected. `Some(true)` = locked, `Some(false)` = unlocked, `None` =
|
||||
//! indeterminate (unreachable, or an endpoint/vendor this probe doesn't cover).
|
||||
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Classify a miner's access state from an HTTP status code string (curl's
|
||||
/// `%{http_code}` output). Conservative: anything other than a clear
|
||||
/// authenticated/unauthorized answer is `None`.
|
||||
pub fn classify_http_code(code: &str) -> Option<bool> {
|
||||
match code.trim() {
|
||||
"200" | "204" => Some(false), // authenticated -> unlocked/writable
|
||||
"401" | "403" => Some(true), // rejected -> locked/view-only
|
||||
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// The privileged, read-only endpoint we probe per firmware family. Antminer
|
||||
/// stock/aftermarket all gate `get_miner_conf.cgi` behind digest auth.
|
||||
fn endpoint(_firmware: &str) -> &'static str {
|
||||
"/cgi-bin/get_miner_conf.cgi"
|
||||
}
|
||||
|
||||
/// Probe one miner's access state over its web API with the given credentials.
|
||||
/// Returns `Ok(Some(true/false))` on a decisive lock/unlock answer, `Ok(None)`
|
||||
/// if reachable-but-indeterminate or a vendor this probe doesn't cover, or
|
||||
/// `Err` only on a failure to run curl at all.
|
||||
pub fn probe_access(ip: &str, firmware: &str, user: &str, pass: &str) -> Result<Option<bool>, String> {
|
||||
let url = format!("http://{ip}{}", endpoint(firmware));
|
||||
let userpass = format!("{user}:{pass}");
|
||||
let mut cmd = Command::new("curl");
|
||||
cmd.args([
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"--digest",
|
||||
"-u",
|
||||
&userpass,
|
||||
"--connect-timeout",
|
||||
"5",
|
||||
"--max-time",
|
||||
"9",
|
||||
&url,
|
||||
]);
|
||||
let out = wait_with_timeout(cmd, Duration::from_secs(12))?;
|
||||
// curl prints the status code to stdout regardless of exit status (000 on a
|
||||
// connection failure), so classify the code rather than the exit status.
|
||||
let code = String::from_utf8_lossy(&out.stdout);
|
||||
Ok(classify_http_code(&code))
|
||||
}
|
||||
|
||||
/// Run a command with a wall-clock timeout (curl can hang past --max-time on a
|
||||
/// black-holed host).
|
||||
fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process::Output, String> {
|
||||
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 curl: {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("curl timed out".into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn classify_codes() {
|
||||
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
|
||||
assert_eq!(classify_http_code("204"), Some(false));
|
||||
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
|
||||
assert_eq!(classify_http_code("403"), Some(true));
|
||||
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
|
||||
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
|
||||
assert_eq!(classify_http_code("500"), None);
|
||||
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
|
||||
assert_eq!(classify_http_code(""), None);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -106,8 +106,9 @@ impl Board {
|
||||
tuning: self.mining,
|
||||
firmware_flash,
|
||||
},
|
||||
// Demo values for the round-8 columns (synthetic, so the columns
|
||||
// Demo values for the round-8/9 columns (synthetic, so the columns
|
||||
// show variety offline).
|
||||
algorithm: "SHA256".to_string(),
|
||||
control_board: if self.model.contains("S17") {
|
||||
"Xilinx".to_string()
|
||||
} else if self.model.contains("S19j") || self.model.contains("S19k") {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
|
||||
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
|
||||
|
||||
mod access_probe;
|
||||
mod credentials;
|
||||
mod fixtures;
|
||||
mod model;
|
||||
mod pic_probe;
|
||||
mod presets;
|
||||
mod scan;
|
||||
mod ui;
|
||||
|
||||
@@ -243,6 +243,8 @@ pub struct MinerRow {
|
||||
pub firmware: String,
|
||||
pub api_version: String,
|
||||
pub control_board: String,
|
||||
/// Mining algorithm (e.g. "SHA256", "Scrypt", "Equihash"), from asic-rs.
|
||||
pub algorithm: String,
|
||||
/// Whether the hashboards carry a PIC MCU. asic-rs does not report this over
|
||||
/// the network, so it is a best-effort inference (model-string heuristic):
|
||||
/// `None` = unknown, `Some(true)` = PIC, `Some(false)` = noPIC. True
|
||||
@@ -369,6 +371,7 @@ pub enum Column {
|
||||
Serial,
|
||||
ApiVersion,
|
||||
ControlBoard,
|
||||
Algorithm,
|
||||
Pic,
|
||||
Locked,
|
||||
Error,
|
||||
@@ -389,7 +392,7 @@ pub enum Column {
|
||||
|
||||
/// Every column, in registry order. Ip first, then the default-visible set
|
||||
/// (UI-SPEC order), then all remaining metrics.
|
||||
pub const ALL_COLUMNS: [Column; 38] = [
|
||||
pub const ALL_COLUMNS: [Column; 39] = [
|
||||
Column::Ip,
|
||||
Column::Hashrate,
|
||||
Column::Power,
|
||||
@@ -412,6 +415,7 @@ pub const ALL_COLUMNS: [Column; 38] = [
|
||||
Column::Serial,
|
||||
Column::ApiVersion,
|
||||
Column::ControlBoard,
|
||||
Column::Algorithm,
|
||||
Column::Pic,
|
||||
Column::Locked,
|
||||
Column::Error,
|
||||
@@ -467,6 +471,7 @@ impl Column {
|
||||
Column::Serial => "Serial",
|
||||
Column::ApiVersion => "API ver",
|
||||
Column::ControlBoard => "Control board",
|
||||
Column::Algorithm => "Algorithm",
|
||||
Column::Pic => "PIC",
|
||||
Column::Locked => "Access",
|
||||
Column::Error => "Errors",
|
||||
@@ -503,6 +508,7 @@ impl Column {
|
||||
Column::Mac | Column::Hostname | Column::Serial => 150,
|
||||
Column::ApiVersion | Column::Light => 90,
|
||||
Column::ControlBoard => 130,
|
||||
Column::Algorithm => 100,
|
||||
Column::Pic => 70,
|
||||
Column::Locked => 90,
|
||||
Column::Error => 160,
|
||||
@@ -644,6 +650,7 @@ impl Column {
|
||||
Column::Serial => r.serial.clone(),
|
||||
Column::ApiVersion => r.api_version.clone(),
|
||||
Column::ControlBoard => r.control_board.clone(),
|
||||
Column::Algorithm => r.algorithm.clone(),
|
||||
Column::Pic => match r.pic_present {
|
||||
Some(true) => "PIC".to_string(),
|
||||
Some(false) => "noPIC".to_string(),
|
||||
@@ -783,6 +790,16 @@ impl ViewState {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every column available to filter on, independent of visibility: a filter
|
||||
/// matches a row by that column's cell text whether or not the column is
|
||||
/// shown, so (e.g.) Algorithm can be filtered without first un-hiding it.
|
||||
/// Ip first, then the registry order.
|
||||
pub fn filter_columns(&self) -> Vec<Column> {
|
||||
let mut v = vec![Column::Ip];
|
||||
v.extend(self.order.iter().copied().filter(|c| *c != Column::Ip));
|
||||
v
|
||||
}
|
||||
|
||||
pub fn is_fixed(&self, c: Column) -> bool {
|
||||
c == Column::Ip
|
||||
}
|
||||
@@ -852,6 +869,11 @@ pub struct Kpis {
|
||||
pub paused: usize,
|
||||
pub total_hashrate_ths: f64,
|
||||
pub total_power_w: f64,
|
||||
/// Per-algorithm hashrate totals (algorithm name, total TH/s), only for
|
||||
/// algorithms actually producing hashrate, ordered by total descending then
|
||||
/// name. The hashrate KPI card cycles through these when more than one
|
||||
/// algorithm is running in the fleet.
|
||||
pub hashrate_by_algo: Vec<(String, f64)>,
|
||||
}
|
||||
|
||||
pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
|
||||
@@ -863,7 +885,11 @@ pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
|
||||
paused: 0,
|
||||
total_hashrate_ths: 0.0,
|
||||
total_power_w: 0.0,
|
||||
hashrate_by_algo: Vec::new(),
|
||||
};
|
||||
// Accumulate per-algorithm totals in an insertion-ordered list (fleets have
|
||||
// a handful of algorithms at most, so a linear scan is cheaper than a map).
|
||||
let mut by_algo: Vec<(String, f64)> = Vec::new();
|
||||
for &i in view_idx {
|
||||
let r = &rows[i];
|
||||
// Bucket by the same precedence status() uses, so the KPI header can
|
||||
@@ -876,7 +902,19 @@ pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
|
||||
}
|
||||
k.total_hashrate_ths += r.hashrate_ths;
|
||||
k.total_power_w += r.power_w;
|
||||
if r.hashrate_ths > 0.0 {
|
||||
// Fall back to "SHA256" when a miner didn't report its algorithm, so
|
||||
// a producing miner is never dropped from the per-algorithm cycle.
|
||||
let algo = if r.algorithm.is_empty() { "SHA256" } else { r.algorithm.as_str() };
|
||||
match by_algo.iter_mut().find(|(a, _)| a == algo) {
|
||||
Some((_, t)) => *t += r.hashrate_ths,
|
||||
None => by_algo.push((algo.to_string(), r.hashrate_ths)),
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stable order: largest total first, ties broken alphabetically.
|
||||
by_algo.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));
|
||||
k.hashrate_by_algo = by_algo;
|
||||
k
|
||||
}
|
||||
|
||||
|
||||
@@ -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<u8> {
|
||||
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 <bus> 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<bool> {
|
||||
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> <ascii gutter>"; 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 <pass>` 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<Option<bool>, 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<Option<bool>, 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<std::process::Output, String> {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -498,6 +498,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
|
||||
.iter()
|
||||
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
|
||||
.fold(0.0f64, f64::max);
|
||||
let algorithm = data.hashrate.as_ref().map(|h| h.algo.to_string()).unwrap_or_default();
|
||||
let is_mining = data.is_mining;
|
||||
let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths);
|
||||
let operating_state = data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default();
|
||||
@@ -525,6 +526,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
|
||||
ip: data.ip.to_string(),
|
||||
selected: false,
|
||||
caps,
|
||||
algorithm,
|
||||
pic_present,
|
||||
write_locked,
|
||||
errors,
|
||||
@@ -905,6 +907,167 @@ pub fn start_firmware_flash_action(ips: Vec<String>, 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<bool>, error: Option<String> },
|
||||
Done { total: usize },
|
||||
}
|
||||
|
||||
/// A running PIC probe; `stop` cancels the remaining miners.
|
||||
pub struct PicProbeHandle {
|
||||
pub rx: Receiver<PicProbeMsg>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
/// Progress/results from a background access (lock-state) probe.
|
||||
pub enum AccessProbeMsg {
|
||||
Started { total: usize },
|
||||
/// `locked` = Some(true) locked/view-only, Some(false) unlocked/writable,
|
||||
/// None indeterminate; `error` set only when the probe couldn't run.
|
||||
Result { ip: String, locked: Option<bool>, error: Option<String> },
|
||||
Done { total: usize },
|
||||
}
|
||||
|
||||
/// A running access probe; `stop` cancels the remaining miners.
|
||||
pub struct AccessProbeHandle {
|
||||
pub rx: Receiver<AccessProbeMsg>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AccessProbeHandle {
|
||||
pub fn stop(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Probe the access/lock state of `targets` (ip + firmware string) over the web
|
||||
/// API with `creds` (user, pass), on a background thread. A digest-auth GET is
|
||||
/// fast, but we still run one miner at a time with cancel-between. Fake-scan mode
|
||||
/// returns deterministic demo results.
|
||||
pub fn start_access_probe(
|
||||
targets: Vec<(String, String)>,
|
||||
creds: (String, String),
|
||||
) -> AccessProbeHandle {
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let total = targets.len();
|
||||
let _ = tx.send(AccessProbeMsg::Started { total });
|
||||
let (user, pass) = creds;
|
||||
|
||||
if fake_scan_enabled() {
|
||||
let err_tx = tx.clone();
|
||||
let thread_cancel = cancel.clone();
|
||||
let res = std::thread::Builder::new().name("fake-access-probe".into()).spawn(move || {
|
||||
for (ip, _fw) in targets {
|
||||
if thread_cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
// Demo: the WardenOS-dev unit (.115) is locked, others unlocked.
|
||||
let locked = Some(ip.ends_with(".115"));
|
||||
let _ = tx.send(AccessProbeMsg::Result { ip, locked, error: None });
|
||||
}
|
||||
let _ = tx.send(AccessProbeMsg::Done { total });
|
||||
});
|
||||
if res.is_err() {
|
||||
let _ = err_tx.send(AccessProbeMsg::Done { total });
|
||||
}
|
||||
return AccessProbeHandle { rx, cancel };
|
||||
}
|
||||
|
||||
let thread_cancel = cancel.clone();
|
||||
let err_tx = tx.clone();
|
||||
let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || {
|
||||
for (ip, fw) in targets {
|
||||
if thread_cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) {
|
||||
Ok(v) => (v, None),
|
||||
Err(e) => (None, Some(e)),
|
||||
};
|
||||
if tx.send(AccessProbeMsg::Result { ip, locked, error }).is_err() {
|
||||
return; // UI gone
|
||||
}
|
||||
}
|
||||
let _ = tx.send(AccessProbeMsg::Done { total });
|
||||
});
|
||||
if res.is_err() {
|
||||
let _ = err_tx.send(AccessProbeMsg::Done { total });
|
||||
}
|
||||
AccessProbeHandle { rx, cancel }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+419
-26
@@ -40,6 +40,8 @@ const ID_KPI_HASHING: i32 = 150;
|
||||
const ID_KPI_SLOW: i32 = 151;
|
||||
const ID_KPI_NOT: i32 = 152;
|
||||
const ID_KPI_PAUSED: i32 = 153;
|
||||
// Click the hashrate KPI card to cycle through per-algorithm hashrate totals.
|
||||
const ID_KPI_HASHRATE: i32 = 154;
|
||||
// Right-click context-menu item ids.
|
||||
const ID_CTX_OPEN: i32 = 720;
|
||||
const ID_CTX_REFRESH: i32 = 732;
|
||||
@@ -52,6 +54,11 @@ 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;
|
||||
const ID_CTX_ACCESS_PROBE: i32 = 731;
|
||||
// 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;
|
||||
@@ -103,6 +110,15 @@ fn luminance(c: (u8, u8, u8)) -> f32 {
|
||||
0.299 * c.0 as f32 + 0.587 * c.1 as f32 + 0.114 * c.2 as f32
|
||||
}
|
||||
|
||||
/// Human-facing algorithm name for the hashrate KPI label. asic-rs renders the
|
||||
/// SHA-256 variant as "SHA256"; everything else already reads well as-is.
|
||||
fn pretty_algo(algo: &str) -> String {
|
||||
match algo {
|
||||
"SHA256" => "SHA-256".to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn nudge(c: (u8, u8, u8), d: i32) -> (u8, u8, u8) {
|
||||
let f = |v: u8| (v as i32 + d).clamp(0, 255) as u8;
|
||||
(f(c.0), f(c.1), f(c.2))
|
||||
@@ -281,6 +297,13 @@ pub struct App {
|
||||
kpi_not: Widget,
|
||||
kpi_paused: Widget,
|
||||
kpi_hashrate: Widget,
|
||||
// The hashrate card's caption label, retitled to "<Algo> Hashrate" as the
|
||||
// per-algorithm cycle advances (the card itself is re-laid-out with the rest
|
||||
// in refresh_kpis).
|
||||
kpi_hashrate_lbl: Widget,
|
||||
// Which per-algorithm total the hashrate card is currently showing; clicking
|
||||
// the card advances it, wrapping around the fleet's running algorithms.
|
||||
hashrate_algo_idx: usize,
|
||||
kpi_power: Widget,
|
||||
progress: Widget,
|
||||
pub table: Option<Widget>,
|
||||
@@ -305,10 +328,11 @@ pub struct App {
|
||||
pal: Palette,
|
||||
kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)>,
|
||||
// The 4 status KPI cards that double as quick-filters: (status text, its
|
||||
// ButtonClicked id, its card panel -- for binding the click and for
|
||||
// tinting the active one). `active_kpi_filter` is set iff view.filters
|
||||
// holds exactly that single-value Status filter.
|
||||
kpi_filter_cards: [(&'static str, i32, Widget); 4],
|
||||
// ButtonClicked id, card panel, value text, label text). The three widgets
|
||||
// are all painted for the active-filter highlight (so the whole box tints,
|
||||
// not just the panel behind the text). `active_kpi_filter` is set iff
|
||||
// view.filters holds exactly that single-value Status filter.
|
||||
kpi_filter_cards: [(&'static str, i32, Widget, Widget, Widget); 4],
|
||||
active_kpi_filter: Option<&'static str>,
|
||||
// A context menu built on right-click, popped up outside the App borrow.
|
||||
pending_popup: Option<(Widget, Widget)>,
|
||||
@@ -322,6 +346,9 @@ pub struct App {
|
||||
action_is_power: bool,
|
||||
action_total: usize,
|
||||
action_done: usize,
|
||||
// IPs the current config action targets, re-probed after it completes so the
|
||||
// table reflects the change (e.g. the identify light toggling).
|
||||
action_targets: Vec<String>,
|
||||
// A confirmation dialog for disruptive actions, plus its pending target.
|
||||
confirm_dialog: Widget,
|
||||
pending_confirm: Option<(Vec<String>, scan::ConfigAction)>,
|
||||
@@ -344,6 +371,14 @@ pub struct App {
|
||||
creds_dialog: Widget,
|
||||
creds_user_input: Widget,
|
||||
creds_pass_input: Widget,
|
||||
// Background access (lock-state) probe.
|
||||
access_probe: Option<scan::AccessProbeHandle>,
|
||||
// Background SSH PIC probe + its credentials dialog.
|
||||
pic_probe: Option<scan::PicProbeHandle>,
|
||||
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<crate::presets::Preset>,
|
||||
presets_dialog: Widget,
|
||||
@@ -382,17 +417,18 @@ pub fn build(frame: Widget) -> App {
|
||||
// KPI header: a row of equal-width cards, each a big value over a small
|
||||
// label. Health KPIs are colour-coded (green/amber/red); hashrate uses the
|
||||
// accent colour so totals stand apart from counts.
|
||||
// wrap_sizer (not box_sizer): at phone-ish widths the cards reflow onto a
|
||||
// second line instead of squeezing/clipping.
|
||||
let kpi_row = Widget::wrap_sizer(false);
|
||||
// Horizontal box sizer with every card at proportion 1 + EXPAND, so the
|
||||
// cards are always equal width AND grow to span the full window; a per-card
|
||||
// min size floors them at their largest content's width.
|
||||
let kpi_row = Widget::box_sizer(false);
|
||||
let mut kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)> = Vec::new();
|
||||
let mut mk_card = |label: &str, kind: ColorKind| -> (Widget, Widget) {
|
||||
let vc = kind_color(&pal, kind);
|
||||
let card = Widget::panel(panel);
|
||||
card.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
|
||||
// Uniform size so every KPI box is identical regardless of its content
|
||||
// (wide enough for the largest value, e.g. "685 TH/s" / "21.3 kW").
|
||||
card.set_min_size(150, 62);
|
||||
// Min-content floor (the widest label/value); cards grow equally past
|
||||
// this to fill the window (proportion 1 + EXPAND on add).
|
||||
card.set_min_size(116, 62);
|
||||
let cs = Widget::box_sizer(true);
|
||||
let value = Widget::static_text(card, "0");
|
||||
value.set_font_size(19);
|
||||
@@ -417,7 +453,7 @@ pub fn build(frame: Widget) -> App {
|
||||
cs.add_sizer(centre(lbl), 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_BOTTOM | sf::BORDER_RIGHT, 8);
|
||||
cs.add_stretch(1);
|
||||
cs.set_sizer_on(card);
|
||||
kpi_row.add(card, 0, sf::BORDER_ALL, 4);
|
||||
kpi_row.add(card, 1, sf::EXPAND | sf::BORDER_ALL, 4);
|
||||
kpi_cards.push((card, value, lbl, kind));
|
||||
(card, value)
|
||||
};
|
||||
@@ -426,19 +462,37 @@ pub fn build(frame: Widget) -> App {
|
||||
let (card_slow, kpi_slow) = mk_card("Slow", ColorKind::Amber);
|
||||
let (card_not, kpi_not) = mk_card("Not hashing", ColorKind::Red);
|
||||
let (card_paused, kpi_paused) = mk_card("Paused", ColorKind::Blue);
|
||||
let (_card_hashrate, kpi_hashrate) = mk_card("Hashrate", ColorKind::Accent);
|
||||
let (card_hashrate, kpi_hashrate) = mk_card("SHA-256 Hashrate", ColorKind::Accent);
|
||||
let (_card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral);
|
||||
drop(mk_card);
|
||||
// The 4 status cards double as quick-filters: clicking one narrows the
|
||||
// table to that status (see `toggle_kpi_filter`).
|
||||
let kpi_filter_cards: [(&'static str, i32, Widget); 4] = [
|
||||
("hashing", ID_KPI_HASHING, card_hashing),
|
||||
("slow", ID_KPI_SLOW, card_slow),
|
||||
("not hashing", ID_KPI_NOT, card_not),
|
||||
("paused", ID_KPI_PAUSED, card_paused),
|
||||
let _ = (card_hashing, card_slow, card_not, card_paused);
|
||||
// The hashrate card is kpi_cards[5] in build order (Total, Hashing, Slow,
|
||||
// Not, Paused, Hashrate, Power); its caption is retitled per algorithm.
|
||||
let kpi_hashrate_lbl = kpi_cards[5].2;
|
||||
// The hashrate card cycles per-algorithm totals on click; bind the card and
|
||||
// both its texts (so a click on the number or the label registers too).
|
||||
card_hashrate.bind_click(ID_KPI_HASHRATE);
|
||||
kpi_hashrate.bind_click(ID_KPI_HASHRATE);
|
||||
kpi_hashrate_lbl.bind_click(ID_KPI_HASHRATE);
|
||||
// The 4 status cards double as quick-filters: clicking one narrows the table
|
||||
// to that status (see `toggle_kpi_filter`). They are kpi_cards[1..=4] in this
|
||||
// order. Bind the click on the card AND its value/label texts (a click on the
|
||||
// text must register too), and keep all three widgets so the highlight can
|
||||
// fill the whole box, not just the panel behind the text.
|
||||
let filter_ids = [
|
||||
("hashing", ID_KPI_HASHING),
|
||||
("slow", ID_KPI_SLOW),
|
||||
("not hashing", ID_KPI_NOT),
|
||||
("paused", ID_KPI_PAUSED),
|
||||
];
|
||||
for &(_, id, card) in &kpi_filter_cards {
|
||||
let mut kpi_filter_cards: [(&'static str, i32, Widget, Widget, Widget); 4] =
|
||||
[("", 0, panel, panel, panel); 4];
|
||||
for (i, &(status, id)) in filter_ids.iter().enumerate() {
|
||||
let (card, value, lbl, _) = kpi_cards[i + 1];
|
||||
card.bind_click(id);
|
||||
value.bind_click(id);
|
||||
lbl.bind_click(id);
|
||||
kpi_filter_cards[i] = (status, id, card, value, lbl);
|
||||
}
|
||||
root.add_sizer(kpi_row, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
|
||||
@@ -482,8 +536,11 @@ pub fn build(frame: Widget) -> App {
|
||||
frame_sizer.set_sizer_on(frame);
|
||||
frame.set_min_size(640, 480);
|
||||
|
||||
// A status bar carries scan state (was an inline label).
|
||||
// A status bar carries scan state (was an inline label). A second,
|
||||
// colour-tinted field pinned to the bottom-right corner carries scan/apply
|
||||
// errors (red) and warnings (amber) so they don't overwrite the scan state.
|
||||
wx_rs::create_status_bar();
|
||||
wx_rs::status_indicator_init(frame);
|
||||
wx_rs::set_status_text("starting scan...");
|
||||
|
||||
// Repaint custom-coloured widgets when the OS switches light/dark.
|
||||
@@ -500,6 +557,8 @@ pub fn build(frame: Widget) -> App {
|
||||
kpi_not,
|
||||
kpi_paused,
|
||||
kpi_hashrate,
|
||||
kpi_hashrate_lbl,
|
||||
hashrate_algo_idx: 0,
|
||||
kpi_power,
|
||||
progress,
|
||||
table: None,
|
||||
@@ -526,6 +585,7 @@ pub fn build(frame: Widget) -> App {
|
||||
action_is_power: false,
|
||||
action_total: 0,
|
||||
action_done: 0,
|
||||
action_targets: Vec::new(),
|
||||
confirm_dialog: frame,
|
||||
pending_confirm: None,
|
||||
flash_confirm_dialog: frame,
|
||||
@@ -536,6 +596,12 @@ pub fn build(frame: Widget) -> App {
|
||||
creds_dialog: frame,
|
||||
creds_user_input: frame,
|
||||
creds_pass_input: frame,
|
||||
access_probe: None,
|
||||
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,
|
||||
@@ -724,8 +790,44 @@ impl App {
|
||||
self.kpi_slow.set_label(&k.slow.to_string());
|
||||
self.kpi_not.set_label(&k.not_hashing.to_string());
|
||||
self.kpi_paused.set_label(&k.paused.to_string());
|
||||
self.kpi_hashrate.set_label(&format_si(k.total_hashrate_ths * 1e12, "H/s"));
|
||||
// Hashrate KPI: no "/s" suffix (per UI request) -> "685 TH", "1.2 PH".
|
||||
// With a single algorithm running (the common case) the card shows that
|
||||
// algorithm's total under a "<Algo> Hashrate" caption; when several are
|
||||
// running, clicking the card cycles `hashrate_algo_idx` through them.
|
||||
let (algo_label, algo_ths) = if k.hashrate_by_algo.is_empty() {
|
||||
("SHA-256".to_string(), 0.0)
|
||||
} else {
|
||||
let i = self.hashrate_algo_idx % k.hashrate_by_algo.len();
|
||||
let (a, t) = &k.hashrate_by_algo[i];
|
||||
(pretty_algo(a), *t)
|
||||
};
|
||||
self.kpi_hashrate.set_label(&format_si(algo_ths * 1e12, "H"));
|
||||
self.kpi_hashrate_lbl.set_label(&format!("{algo_label} Hashrate"));
|
||||
self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
|
||||
// set_label resizes the static text; re-run each card's sizer so the
|
||||
// centring spacers recompute around the new width (otherwise the value
|
||||
// drifts off-centre when a filter changes a count's digit width).
|
||||
for (card, _, _, _) in &self.kpi_cards {
|
||||
card.layout();
|
||||
}
|
||||
}
|
||||
|
||||
/// Show a scan/apply error (red) in the bottom-right status indicator,
|
||||
/// separate from the left-hand scan-status text.
|
||||
fn set_error_indicator(&self, msg: &str) {
|
||||
let c = self.pal.red;
|
||||
wx_rs::status_indicator_set(msg, c.0, c.1, c.2);
|
||||
}
|
||||
|
||||
/// Show a scan/apply warning (amber) in the bottom-right status indicator.
|
||||
fn set_warning_indicator(&self, msg: &str) {
|
||||
let c = self.pal.amber;
|
||||
wx_rs::status_indicator_set(msg, c.0, c.1, c.2);
|
||||
}
|
||||
|
||||
/// Clear the bottom-right status indicator.
|
||||
fn clear_indicator(&self) {
|
||||
wx_rs::status_indicator_set("", 0, 0, 0);
|
||||
}
|
||||
|
||||
/// Re-apply the theme palette to the KPI cards and table rows after the OS
|
||||
@@ -752,13 +854,29 @@ impl App {
|
||||
/// so the active quick-filter is visible at a glance; every other status
|
||||
/// card resets to the normal card background.
|
||||
fn highlight_kpi_filter(&self) {
|
||||
for &(status, _, card) in &self.kpi_filter_cards {
|
||||
for &(status, _, card, value, lbl) in &self.kpi_filter_cards {
|
||||
let bg = if Some(status) == self.active_kpi_filter {
|
||||
tint_toward(self.pal.card_bg, status_kind_color(&self.pal, status), 0.35)
|
||||
} else {
|
||||
self.pal.card_bg
|
||||
};
|
||||
// Paint the panel and both static texts so the whole box tints; a
|
||||
// static_text keeps its own background, so tinting only the card
|
||||
// would leave an untinted rectangle behind the number and label.
|
||||
card.set_bg(bg.0, bg.1, bg.2);
|
||||
value.set_bg(bg.0, bg.1, bg.2);
|
||||
lbl.set_bg(bg.0, bg.1, bg.2);
|
||||
}
|
||||
}
|
||||
|
||||
/// Click on the hashrate KPI card: advance to the next running algorithm's
|
||||
/// total (wrapping around). A no-op when fewer than two algorithms are
|
||||
/// running, since there is nothing to cycle to.
|
||||
fn cycle_hashrate_algo(&mut self) {
|
||||
let n = compute_kpis(&self.rows, &self.view_idx).hashrate_by_algo.len();
|
||||
if n > 1 {
|
||||
self.hashrate_algo_idx = (self.hashrate_algo_idx + 1) % n;
|
||||
self.refresh_kpis();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -784,7 +902,7 @@ impl App {
|
||||
self.active_kpi_filter = match self.view.filters.get(&Column::Status) {
|
||||
Some(ColFilter::Values(set)) if set.len() == 1 => {
|
||||
let v = set.iter().next().map(String::as_str);
|
||||
self.kpi_filter_cards.iter().map(|&(s, _, _)| s).find(|&s| Some(s) == v)
|
||||
self.kpi_filter_cards.iter().map(|&(s, _, _, _, _)| s).find(|&s| Some(s) == v)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
@@ -815,6 +933,12 @@ 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)...");
|
||||
// Real access/lock-state check (credentialed digest GET; uses the saved
|
||||
// scan credentials).
|
||||
menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)");
|
||||
// Config actions common to the whole selection (capability
|
||||
// intersection): an action is offered only if every selected miner
|
||||
// supports it.
|
||||
@@ -887,7 +1011,11 @@ impl App {
|
||||
old.stop();
|
||||
}
|
||||
let msg = format!("applying {} to {} miner(s)...", action.label(), ips.len());
|
||||
self.action_targets = ips.clone();
|
||||
self.action = Some(scan::start_config_action(ips, action));
|
||||
// Clear any stale error/warning from a previous operation; the new
|
||||
// outcome repopulates the indicator when this action finishes.
|
||||
self.clear_indicator();
|
||||
wx_rs::set_status_text(&msg);
|
||||
}
|
||||
|
||||
@@ -910,6 +1038,223 @@ 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<Widget> {
|
||||
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..."));
|
||||
}
|
||||
|
||||
/// Start the access (lock-state) probe on the selected miners, using the
|
||||
/// saved scan (web) credentials (defaulting to root/root if none are set).
|
||||
fn start_access_probe(&mut self) {
|
||||
if self.flashing {
|
||||
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
|
||||
return;
|
||||
}
|
||||
if self.access_probe.is_some() {
|
||||
wx_rs::set_status_text("an access check is already running");
|
||||
return;
|
||||
}
|
||||
let targets: Vec<(String, String)> = self
|
||||
.selected_rows()
|
||||
.iter()
|
||||
.map(|r| (r.ip.clone(), r.firmware.clone()))
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return;
|
||||
}
|
||||
let creds = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
|
||||
let n = targets.len();
|
||||
self.access_probe = Some(scan::start_access_probe(targets, creds));
|
||||
wx_rs::set_status_text(&format!("checking access on {n} miner(s)..."));
|
||||
}
|
||||
|
||||
/// Drain the running access probe: update each miner's write_locked as its
|
||||
/// result arrives, and refresh the table + status when done.
|
||||
fn drain_access_probe(&mut self) {
|
||||
let Some(h) = &self.access_probe else { return };
|
||||
let mut status: Option<String> = None;
|
||||
let mut done = false;
|
||||
let mut changed = false;
|
||||
loop {
|
||||
match h.rx.try_recv() {
|
||||
Ok(scan::AccessProbeMsg::Started { total }) => {
|
||||
status = Some(format!("access check: 0/{total}..."));
|
||||
}
|
||||
Ok(scan::AccessProbeMsg::Result { ip, locked, error }) => {
|
||||
if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) {
|
||||
if error.is_none() {
|
||||
r.write_locked = locked;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
status = Some(match (&locked, &error) {
|
||||
(_, Some(e)) => format!("access {ip}: {e}"),
|
||||
(Some(true), _) => format!("access {ip}: locked"),
|
||||
(Some(false), _) => format!("access {ip}: unlocked"),
|
||||
(None, _) => format!("access {ip}: indeterminate"),
|
||||
});
|
||||
}
|
||||
Ok(scan::AccessProbeMsg::Done { total }) => {
|
||||
status = Some(format!("access check 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.access_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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<String> = 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<Widget> {
|
||||
@@ -923,6 +1268,8 @@ impl App {
|
||||
}
|
||||
}
|
||||
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
|
||||
ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(),
|
||||
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
|
||||
ID_CTX_FLASH => {
|
||||
// A flash needs exclusive hardware access; don't even prompt if
|
||||
// any scan / refresh / action is running (re-checked at confirm).
|
||||
@@ -1226,6 +1573,9 @@ impl App {
|
||||
let Some(h) = &self.action else { return };
|
||||
let mut status: Option<String> = None;
|
||||
let mut finished = false;
|
||||
// Bottom-right indicator to apply after the `h` borrow is released:
|
||||
// None = leave as-is, Some(None) = clear, Some(Some((is_error, msg))).
|
||||
let mut indicator: Option<Option<(bool, String)>> = None;
|
||||
loop {
|
||||
match h.rx.try_recv() {
|
||||
Ok(scan::ActionMsg::Started { total }) => {
|
||||
@@ -1248,6 +1598,15 @@ impl App {
|
||||
} else {
|
||||
format!("applied to {ok}/{total} miner(s), {} failed", total - ok)
|
||||
});
|
||||
// Surface the outcome in the bottom-right indicator: a total
|
||||
// failure is red, a partial failure amber, full success clears.
|
||||
indicator = Some(if total == 0 || ok == total {
|
||||
None
|
||||
} else if ok == 0 {
|
||||
Some((true, format!("apply failed on all {total} miner(s)")))
|
||||
} else {
|
||||
Some((false, format!("apply: {}/{total} miner(s) failed", total - ok)))
|
||||
});
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
@@ -1261,6 +1620,7 @@ impl App {
|
||||
}
|
||||
if finished {
|
||||
self.action = None;
|
||||
let was_flash = self.flashing;
|
||||
// Release the firmware-flash exclusive lock (harmless no-op for a
|
||||
// plain config action, which never set it).
|
||||
self.flashing = false;
|
||||
@@ -1268,6 +1628,21 @@ impl App {
|
||||
// action's outcome (incl. failures) isn't clobbered by the next tick.
|
||||
self.action_result = status.clone();
|
||||
self.action_result_ticks = ACTION_RESULT_TICKS;
|
||||
// Re-probe the miners the action touched so the table reflects the
|
||||
// change (e.g. the identify light). Skip after a flash (the miner is
|
||||
// rebooting and won't answer a refresh yet).
|
||||
let targets = std::mem::take(&mut self.action_targets);
|
||||
if !was_flash && !targets.is_empty() {
|
||||
self.start_refresh(targets);
|
||||
}
|
||||
}
|
||||
// Apply the captured indicator now the `h` borrow is gone.
|
||||
if let Some(ind) = indicator {
|
||||
match ind {
|
||||
None => self.clear_indicator(),
|
||||
Some((true, msg)) => self.set_error_indicator(&msg),
|
||||
Some((false, msg)) => self.set_warning_indicator(&msg),
|
||||
}
|
||||
}
|
||||
if let Some(s) = status {
|
||||
wx_rs::set_status_text(&s);
|
||||
@@ -1342,6 +1717,8 @@ impl App {
|
||||
self.progress.gauge_set_value(0);
|
||||
self.progress.show(true);
|
||||
self.table_parent.layout();
|
||||
// A fresh scan supersedes any prior error/warning.
|
||||
wx_rs::status_indicator_set("", 0, 0, 0);
|
||||
wx_rs::set_status_text(&format!("scanning {total} addresses..."));
|
||||
}
|
||||
Ok(ScanMsg::Progress { done, total, ip }) => {
|
||||
@@ -1373,6 +1750,9 @@ impl App {
|
||||
self.progress.show(false);
|
||||
self.table_parent.layout();
|
||||
wx_rs::set_status_text(&format!("scan failed: {e}"));
|
||||
// Surface the failure in the bottom-right indicator (red).
|
||||
let c = self.pal.red;
|
||||
wx_rs::status_indicator_set(&format!("scan failed: {e}"), c.0, c.1, c.2);
|
||||
self.countdown = if self.playing { self.auto_secs } else { 0 };
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => break,
|
||||
@@ -1402,9 +1782,14 @@ impl App {
|
||||
self.drain_scan();
|
||||
self.drain_action();
|
||||
self.drain_refresh();
|
||||
self.drain_pic_probe();
|
||||
self.drain_access_probe();
|
||||
if self.scanning {
|
||||
return; // status already shows scan progress
|
||||
}
|
||||
if self.pic_probe.is_some() || self.access_probe.is_some() {
|
||||
return; // a probe is in flight; keep its status
|
||||
}
|
||||
if self.action.is_some() {
|
||||
return; // a config action is in flight; keep its status
|
||||
}
|
||||
@@ -1892,7 +2277,9 @@ impl App {
|
||||
let dlg = Widget::dialog(frame, "Filter");
|
||||
let root = Widget::box_sizer(true);
|
||||
|
||||
self.filter_cols = self.view.display_columns();
|
||||
// Offer every column (not just the visible ones) so any metric --
|
||||
// Algorithm included -- can be filtered without first un-hiding it.
|
||||
self.filter_cols = self.view.filter_columns();
|
||||
self.filter_working = self.view.filters.clone();
|
||||
self.filter_cur = 0;
|
||||
|
||||
@@ -2161,6 +2548,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(),
|
||||
@@ -2194,6 +2586,7 @@ impl App {
|
||||
ID_KPI_SLOW => self.toggle_kpi_filter("slow"),
|
||||
ID_KPI_NOT => self.toggle_kpi_filter("not hashing"),
|
||||
ID_KPI_PAUSED => self.toggle_kpi_filter("paused"),
|
||||
ID_KPI_HASHRATE => self.cycle_hashrate_algo(),
|
||||
ID_PLAY => {
|
||||
// Resume/start the scan loop: scan now (unless one is
|
||||
// already running) + auto-rescan on.
|
||||
@@ -2265,7 +2658,7 @@ impl App {
|
||||
(self.kpi_slow, "Slow", "1"),
|
||||
(self.kpi_not, "Not hashing", "1"),
|
||||
(self.kpi_paused, "Paused", "1"),
|
||||
(self.kpi_hashrate, "Hashrate", "685 TH/s"),
|
||||
(self.kpi_hashrate, "SHA-256 Hashrate", "685 TH"),
|
||||
(self.kpi_power, "Est. power", "21.3 kW"),
|
||||
];
|
||||
for (w, name, want) in want_kpis {
|
||||
|
||||
+18
-1
@@ -10,7 +10,7 @@
|
||||
+pub use widgets::*;
|
||||
--- a/src/widgets.rs
|
||||
+++ b/src/widgets.rs
|
||||
@@ -0,0 +1,728 @@
|
||||
@@ -0,0 +1,745 @@
|
||||
+// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge
|
||||
+// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the
|
||||
+// wxWidgets object tree (parents own children; nothing to free in Rust).
|
||||
@@ -116,6 +116,8 @@
|
||||
+ pub fn wxbr_destroy(win: *mut c_void);
|
||||
+ pub fn wxbr_destroy_children(win: *mut c_void);
|
||||
+ pub fn wxbr_call_after(id: c_int);
|
||||
+ pub fn wxbr_status_indicator_init(frame: *mut c_void);
|
||||
+ pub fn wxbr_status_indicator_set(text: *const c_char, r: c_int, g: c_int, b: c_int);
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
@@ -188,6 +190,21 @@
|
||||
+ unsafe { notsafe::wxbr_call_after(id as c_int) }
|
||||
+}
|
||||
+
|
||||
+/// Reconfigure the frame's status bar to two fields and attach a colour-tinted
|
||||
+/// label pinned to the right-hand field (bottom-right corner). Call once after
|
||||
+/// `create_status_bar()`. The main scan status keeps using the left field via
|
||||
+/// the upstream `set_status_text` path.
|
||||
+pub fn status_indicator_init(frame: Widget) {
|
||||
+ unsafe { notsafe::wxbr_status_indicator_init(frame.0) }
|
||||
+}
|
||||
+
|
||||
+/// Set the bottom-right status indicator's text and colour (an empty string
|
||||
+/// clears it). Used for scan/apply errors (red) and warnings (amber).
|
||||
+pub fn status_indicator_set(text: &str, r: u8, g: u8, b: u8) {
|
||||
+ let c = CString::new(text).unwrap_or_default();
|
||||
+ unsafe { notsafe::wxbr_status_indicator_set(c.as_ptr(), r as c_int, g as c_int, b as c_int) }
|
||||
+}
|
||||
+
|
||||
+/// Open a URL in the system default browser. Returns true on success.
|
||||
+pub fn launch_browser(url: &str) -> bool {
|
||||
+ let c = CString::new(url).unwrap_or_default();
|
||||
|
||||
+77
-3
@@ -1,6 +1,6 @@
|
||||
--- a/cpp_src/widgets_bridge.cpp
|
||||
+++ b/cpp_src/widgets_bridge.cpp
|
||||
@@ -0,0 +1,1059 @@
|
||||
@@ -0,0 +1,1133 @@
|
||||
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
|
||||
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
|
||||
+// render-callback bridge (which is kept untouched).
|
||||
@@ -32,6 +32,7 @@
|
||||
+#include <wx/graphics.h>
|
||||
+#include <wx/wrapsizer.h>
|
||||
+#include <wx/filedlg.h>
|
||||
+#include <wx/statusbr.h>
|
||||
+#include <cstring>
|
||||
+#include <cstdio>
|
||||
+#include <map>
|
||||
@@ -701,9 +702,11 @@
|
||||
+}
|
||||
+
|
||||
+// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
|
||||
+// scroll position after a refill). Out-of-range rows are ignored.
|
||||
+// scroll position after a refill). Out-of-range rows are ignored -- GetItem()
|
||||
+// itself asserts on row >= count, so the bound MUST be checked before calling.
|
||||
+void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
|
||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
+ if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
|
||||
+ wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
|
||||
+ if (item.IsOk()) dv->EnsureVisible(item);
|
||||
+}
|
||||
@@ -775,6 +778,25 @@
|
||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
+ unsigned n = dv->GetColumnCount();
|
||||
+ if (pos < 0 || (unsigned)pos >= n) return -1;
|
||||
+#ifdef __WXGTK__
|
||||
+ // wxGTK's GetColumnPosition() does NOT reflect a native GtkTreeView column
|
||||
+ // drag, so after the user reorders columns it reports the creation order and
|
||||
+ // the reorder is silently lost. Read the real display order from the
|
||||
+ // GtkTreeView instead, then map the column back to its wx creation index.
|
||||
+ GtkWidget* tvw = dv->GtkGetTreeView();
|
||||
+ if (tvw) {
|
||||
+ GList* cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(tvw)); // display order
|
||||
+ GtkTreeViewColumn* gcol = (GtkTreeViewColumn*)g_list_nth_data(cols, (guint)pos);
|
||||
+ g_list_free(cols);
|
||||
+ if (gcol) {
|
||||
+ wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
|
||||
+ for (unsigned i = 0; i < n; i++) {
|
||||
+ if (dv->GetColumn(i) == wxcol) return (int)i;
|
||||
+ }
|
||||
+ }
|
||||
+ return -1;
|
||||
+ }
|
||||
+#endif
|
||||
+ for (unsigned i = 0; i < n; i++) {
|
||||
+ wxDataViewColumn* c = dv->GetColumn(i);
|
||||
+ if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
|
||||
@@ -806,9 +828,11 @@
|
||||
+void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
|
||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
+ int count = (int)dvlc_store(win)->GetItemCount();
|
||||
+ dv->UnselectAll();
|
||||
+ for (int i = 0; i < n; i++) {
|
||||
+ if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
|
||||
+ // GetItem() asserts on an out-of-range row, so bound both ends.
|
||||
+ if (rows[i] >= 0 && rows[i] < count) dv->Select(m->GetItem((unsigned)rows[i]));
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
@@ -827,6 +851,7 @@
|
||||
+ if (row < 0) return;
|
||||
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
+ if (row >= (long)dvlc_store(win)->GetItemCount()) return;
|
||||
+ dv->Select(m->GetItem((unsigned)row));
|
||||
+}
|
||||
+
|
||||
@@ -1051,6 +1076,55 @@
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+// ---- status-bar error/warning indicator -------------------------------------
|
||||
+// A colour-tinted static text pinned to the RIGHT-hand field of the frame's
|
||||
+// status bar, so scan/apply errors surface in the bottom-right corner without
|
||||
+// overwriting the main (left) scan-status text. The status bar is reconfigured
|
||||
+// to two fields: field 0 (stretch) carries the scan status set via the upstream
|
||||
+// SetStatusText path; field 1 (fixed) hosts this coloured label, which we
|
||||
+// reposition into that field's rect whenever the bar is resized.
|
||||
+static wxStaticText* g_status_indicator = nullptr;
|
||||
+
|
||||
+static void reposition_status_indicator() {
|
||||
+ if (!g_status_indicator) return;
|
||||
+ wxStatusBar* sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar);
|
||||
+ if (!sb) return;
|
||||
+ wxRect r;
|
||||
+ if (!sb->GetFieldRect(1, r)) return;
|
||||
+ wxSize best = g_status_indicator->GetBestSize();
|
||||
+ int h = best.GetHeight();
|
||||
+ int y = r.y + (r.height - h) / 2;
|
||||
+ g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h);
|
||||
+}
|
||||
+
|
||||
+void wxbr_status_indicator_init(void* frame_ptr) {
|
||||
+ wxFrame* frame = (wxFrame*)frame_ptr;
|
||||
+ wxStatusBar* sb = frame->GetStatusBar();
|
||||
+ if (!sb) sb = frame->CreateStatusBar();
|
||||
+ int widths[2] = { -1, 340 };
|
||||
+ sb->SetFieldsCount(2);
|
||||
+ sb->SetStatusWidths(2, widths);
|
||||
+ if (!g_status_indicator) {
|
||||
+ g_status_indicator = new wxStaticText(sb, wxID_ANY, wxEmptyString,
|
||||
+ wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxST_NO_AUTORESIZE);
|
||||
+ sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) {
|
||||
+ reposition_status_indicator();
|
||||
+ ev.Skip();
|
||||
+ });
|
||||
+ }
|
||||
+ reposition_status_indicator();
|
||||
+}
|
||||
+
|
||||
+// Set the bottom-right indicator text and its colour. An empty string clears it.
|
||||
+void wxbr_status_indicator_set(const char* text, int r, int g, int b) {
|
||||
+ if (!g_status_indicator) return;
|
||||
+ g_status_indicator->SetLabel(wxString::FromUTF8(text ? text : ""));
|
||||
+ g_status_indicator->SetForegroundColour(
|
||||
+ wxColour((unsigned char)r, (unsigned char)g, (unsigned char)b));
|
||||
+ reposition_status_indicator();
|
||||
+ g_status_indicator->Refresh();
|
||||
+}
|
||||
+
|
||||
+// ---- deferred destroy (safe from event handlers) ----------------------------
|
||||
+
|
||||
+void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); }
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
#include <wx/graphics.h>
|
||||
#include <wx/wrapsizer.h>
|
||||
#include <wx/filedlg.h>
|
||||
#include <wx/statusbr.h>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
@@ -698,9 +699,11 @@ int wxbr_dvlc_get_top_row(void* win) {
|
||||
}
|
||||
|
||||
// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
|
||||
// scroll position after a refill). Out-of-range rows are ignored.
|
||||
// scroll position after a refill). Out-of-range rows are ignored -- GetItem()
|
||||
// itself asserts on row >= count, so the bound MUST be checked before calling.
|
||||
void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
|
||||
wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
|
||||
if (item.IsOk()) dv->EnsureVisible(item);
|
||||
}
|
||||
@@ -772,6 +775,25 @@ int wxbr_dvlc_col_at_pos(void* win, int pos) {
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
unsigned n = dv->GetColumnCount();
|
||||
if (pos < 0 || (unsigned)pos >= n) return -1;
|
||||
#ifdef __WXGTK__
|
||||
// wxGTK's GetColumnPosition() does NOT reflect a native GtkTreeView column
|
||||
// drag, so after the user reorders columns it reports the creation order and
|
||||
// the reorder is silently lost. Read the real display order from the
|
||||
// GtkTreeView instead, then map the column back to its wx creation index.
|
||||
GtkWidget* tvw = dv->GtkGetTreeView();
|
||||
if (tvw) {
|
||||
GList* cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(tvw)); // display order
|
||||
GtkTreeViewColumn* gcol = (GtkTreeViewColumn*)g_list_nth_data(cols, (guint)pos);
|
||||
g_list_free(cols);
|
||||
if (gcol) {
|
||||
wxDataViewColumn* wxcol = dv->GTKColumnToWX(gcol);
|
||||
for (unsigned i = 0; i < n; i++) {
|
||||
if (dv->GetColumn(i) == wxcol) return (int)i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
for (unsigned i = 0; i < n; i++) {
|
||||
wxDataViewColumn* c = dv->GetColumn(i);
|
||||
if (c && dv->GetColumnPosition(c) == (unsigned)pos) return (int)i;
|
||||
@@ -803,9 +825,11 @@ int wxbr_dvlc_get_selections(void* win, int* buf, int cap) {
|
||||
void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
int count = (int)dvlc_store(win)->GetItemCount();
|
||||
dv->UnselectAll();
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
|
||||
// GetItem() asserts on an out-of-range row, so bound both ends.
|
||||
if (rows[i] >= 0 && rows[i] < count) dv->Select(m->GetItem((unsigned)rows[i]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -824,6 +848,7 @@ void wxbr_dvlc_select_row(void* win, long row) {
|
||||
if (row < 0) return;
|
||||
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
|
||||
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
|
||||
if (row >= (long)dvlc_store(win)->GetItemCount()) return;
|
||||
dv->Select(m->GetItem((unsigned)row));
|
||||
}
|
||||
|
||||
@@ -1048,6 +1073,55 @@ void wxbr_call_after(int id) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- status-bar error/warning indicator -------------------------------------
|
||||
// A colour-tinted static text pinned to the RIGHT-hand field of the frame's
|
||||
// status bar, so scan/apply errors surface in the bottom-right corner without
|
||||
// overwriting the main (left) scan-status text. The status bar is reconfigured
|
||||
// to two fields: field 0 (stretch) carries the scan status set via the upstream
|
||||
// SetStatusText path; field 1 (fixed) hosts this coloured label, which we
|
||||
// reposition into that field's rect whenever the bar is resized.
|
||||
static wxStaticText* g_status_indicator = nullptr;
|
||||
|
||||
static void reposition_status_indicator() {
|
||||
if (!g_status_indicator) return;
|
||||
wxStatusBar* sb = wxDynamicCast(g_status_indicator->GetParent(), wxStatusBar);
|
||||
if (!sb) return;
|
||||
wxRect r;
|
||||
if (!sb->GetFieldRect(1, r)) return;
|
||||
wxSize best = g_status_indicator->GetBestSize();
|
||||
int h = best.GetHeight();
|
||||
int y = r.y + (r.height - h) / 2;
|
||||
g_status_indicator->SetSize(r.x + 4, y, r.width - 8, h);
|
||||
}
|
||||
|
||||
void wxbr_status_indicator_init(void* frame_ptr) {
|
||||
wxFrame* frame = (wxFrame*)frame_ptr;
|
||||
wxStatusBar* sb = frame->GetStatusBar();
|
||||
if (!sb) sb = frame->CreateStatusBar();
|
||||
int widths[2] = { -1, 340 };
|
||||
sb->SetFieldsCount(2);
|
||||
sb->SetStatusWidths(2, widths);
|
||||
if (!g_status_indicator) {
|
||||
g_status_indicator = new wxStaticText(sb, wxID_ANY, wxEmptyString,
|
||||
wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxST_NO_AUTORESIZE);
|
||||
sb->Bind(wxEVT_SIZE, [](wxSizeEvent& ev) {
|
||||
reposition_status_indicator();
|
||||
ev.Skip();
|
||||
});
|
||||
}
|
||||
reposition_status_indicator();
|
||||
}
|
||||
|
||||
// Set the bottom-right indicator text and its colour. An empty string clears it.
|
||||
void wxbr_status_indicator_set(const char* text, int r, int g, int b) {
|
||||
if (!g_status_indicator) return;
|
||||
g_status_indicator->SetLabel(wxString::FromUTF8(text ? text : ""));
|
||||
g_status_indicator->SetForegroundColour(
|
||||
wxColour((unsigned char)r, (unsigned char)g, (unsigned char)b));
|
||||
reposition_status_indicator();
|
||||
g_status_indicator->Refresh();
|
||||
}
|
||||
|
||||
// ---- deferred destroy (safe from event handlers) ----------------------------
|
||||
|
||||
void wxbr_destroy(void* win) { ((wxWindow*)win)->Destroy(); }
|
||||
|
||||
@@ -103,6 +103,8 @@ mod notsafe {
|
||||
pub fn wxbr_destroy(win: *mut c_void);
|
||||
pub fn wxbr_destroy_children(win: *mut c_void);
|
||||
pub fn wxbr_call_after(id: c_int);
|
||||
pub fn wxbr_status_indicator_init(frame: *mut c_void);
|
||||
pub fn wxbr_status_indicator_set(text: *const c_char, r: c_int, g: c_int, b: c_int);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +177,21 @@ pub fn call_after(id: i32) {
|
||||
unsafe { notsafe::wxbr_call_after(id as c_int) }
|
||||
}
|
||||
|
||||
/// Reconfigure the frame's status bar to two fields and attach a colour-tinted
|
||||
/// label pinned to the right-hand field (bottom-right corner). Call once after
|
||||
/// `create_status_bar()`. The main scan status keeps using the left field via
|
||||
/// the upstream `set_status_text` path.
|
||||
pub fn status_indicator_init(frame: Widget) {
|
||||
unsafe { notsafe::wxbr_status_indicator_init(frame.0) }
|
||||
}
|
||||
|
||||
/// Set the bottom-right status indicator's text and colour (an empty string
|
||||
/// clears it). Used for scan/apply errors (red) and warnings (amber).
|
||||
pub fn status_indicator_set(text: &str, r: u8, g: u8, b: u8) {
|
||||
let c = CString::new(text).unwrap_or_default();
|
||||
unsafe { notsafe::wxbr_status_indicator_set(c.as_ptr(), r as c_int, g as c_int, b as c_int) }
|
||||
}
|
||||
|
||||
/// Open a URL in the system default browser. Returns true on success.
|
||||
pub fn launch_browser(url: &str) -> bool {
|
||||
let c = CString::new(url).unwrap_or_default();
|
||||
|
||||
Reference in New Issue
Block a user