//! Table data model: rows, columns, sort/filter state (UI-SPEC section "Table"). use std::collections::{HashMap, HashSet}; /// Serialises tests that mutate the process-global `$HOME` (config paths read it), /// so they never race each other under the parallel test harness (round 18 #12). /// Lock it with `.lock().unwrap_or_else(|e| e.into_inner())` to shrug off a poison /// from a panicking sibling test. #[cfg(test)] pub(crate) static HOME_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// A miner counts as "slow" when it is mining but running below this fraction /// of its model's expected hashrate (UI-SPEC "Slow" band). A missing expected /// hashrate (0.0) means the band is unknown, so the miner is never "slow". pub const SLOW_THRESHOLD: f64 = 0.8; /// The single source of truth for the "slow" classification, shared by the /// live scan (`scan::to_row`) and the fixtures/tests, so the expected-vs-actual /// comparison exercises the same rule the app uses. pub fn is_slow(is_mining: bool, hashrate_ths: f64, expected_ths: f64) -> bool { is_mining && expected_ths > 0.0 && hashrate_ths < SLOW_THRESHOLD * expected_ths } /// Choose an SI prefix and a max-3-significant-digit mantissa string for a /// base value, shared by `format_si` and `format_fan_rpm`: the prefix puts /// the mantissa in [1, 1000), shown with 1 decimal below 100 and no decimal /// from 100 up. `None` for a non-finite or non-positive value -- the caller /// renders its own "absent" form ("0 " for `format_si`, "-" for /// `format_fan_rpm`). fn si_mantissa_and_prefix(value_base: f64) -> Option<(String, &'static str)> { if !value_base.is_finite() || value_base <= 0.0 { return None; } const PREFIXES: [&str; 8] = ["", "k", "M", "G", "T", "P", "E", "Z"]; let mut v = value_base; let mut i = 0usize; while v >= 1000.0 && i < PREFIXES.len() - 1 { v /= 1000.0; i += 1; } // Round first, then re-check the prefix. A mantissa that rounds up to 1000 // (e.g. 999.9 -> "1000") must roll over to the next prefix so the number // never shows more than three integer digits; and a mantissa in [99.95,100) // rounds to "100.0" and should drop its decimal (the >=100 branch's rule). let render = |v: f64| { if v >= 100.0 { format!("{v:.0}") } else { format!("{v:.1}") } }; let mut num = render(v); if (num == "1000" || num == "1000.0") && i < PREFIXES.len() - 1 { v /= 1000.0; i += 1; num = render(v); } else if num == "100.0" { num = "100".to_string(); } Some((num, PREFIXES[i])) } /// Format a value in its base unit with an SI prefix chosen so the number stays /// compact: the prefix puts the mantissa in [1, 1000), then it is shown with 1 /// decimal below 100 and no decimal from 100 up (so 21300 W -> "21.3 kW", /// 685e12 H/s -> "685 TH/s", 6.8e12 -> "6.8 TH/s"). Zero renders as "0 ". pub fn format_si(value_base: f64, unit: &str) -> String { match si_mantissa_and_prefix(value_base) { Some((num, prefix)) => format!("{num} {prefix}{unit}"), None => format!("0 {unit}"), } } /// Like `format_si` but for a cooling-fan RPM reading: no unit/space suffix, /// and "-" (rather than "0") for an absent/non-positive reading (see the per-fan /// `Column::Fan1`..`Fan4` columns). pub fn format_fan_rpm(rpm: f64) -> String { match si_mantissa_and_prefix(rpm) { Some((num, prefix)) => format!("{num}{prefix}"), None => "-".to_string(), } } /// A hashrate reading (in TH/s) for the combined Hashrate column: mantissa + SI /// prefix only, no unit and no space (80.5 TH/s -> "80.5T", 102 TH/s -> "102T"), /// or `None` for an absent/non-positive reading. pub fn format_hashrate_ths(ths: f64) -> Option { si_mantissa_and_prefix(ths * 1e12).map(|(num, prefix)| format!("{num}{prefix}")) } /// The current-hashrate reading for the combined Hashrate cell, distinguishing a /// reported zero from an unreadable one: `Some("0.00T")` when the firmware reported /// a hashrate that rounds to zero, `Some("T")` for a positive reading, and /// `None` (renders as the "-" dash) only when the hashrate is unreadable/absent. pub fn format_hashrate_actual(ths: f64, known: bool) -> Option { if !known { return None; } Some(format_hashrate_ths(ths).unwrap_or_else(|| "0.00T".to_string())) } /// A hashrate number (no unit) for a given mining algorithm (round 18 #7). asic-rs /// stores every hashrate normalised to "TH/s", but for Equihash the underlying /// count is Sol/s that it reinterprets through the base H unit, so `ths * 1e12` /// recovers the real Sol/s count. SHA256/Scrypt show the TH/s value directly /// ("33.5"); Equihash shows the Sol/s count with an SI prefix ("167.8K"). Pair /// with [`MinerRow::hashrate_unit`]. `None` for a non-positive reading. pub fn hashrate_num_for(algo: &str, ths: f64) -> Option { if ths <= 0.0 { return None; } if algo.eq_ignore_ascii_case("equihash") { si_mantissa_and_prefix(ths * 1e12).map(|(num, prefix)| format!("{num}{prefix}")) } else { Some(format!("{ths:.1}")) } } /// The actual/expected ratio, or `None` when the expected value is unknown /// (<= 0.0) so a ratio-based color/warning never divides by zero or treats an /// unknown expectation as a 0% shortfall. pub fn actual_expected_ratio(actual: f64, expected: f64) -> Option { if expected > 0.0 { Some(actual / expected) } else { None } } /// Mean of `vals`, or `default` when empty -- a scalar sort key for the /// slash-joined per-board columns (round 19 #10). fn avg_or(vals: &[f64], default: f64) -> f64 { if vals.is_empty() { default } else { vals.iter().sum::() / vals.len() as f64 } } /// Mean of the POSITIVE entries in `vals`, or `default` when none are positive. /// Board voltage/frequency store 0.0 for a board that reports no value (rendered /// "-"), so a plain average would drag the sort/filter key toward zero and /// mis-rank the miner (round 19 review); this skips those placeholders. fn avg_positive(vals: &[f64], default: f64) -> f64 { let (sum, n) = vals .iter() .filter(|&&v| v > 0.0) .fold((0.0, 0usize), |(s, n), &v| (s + v, n + 1)); if n == 0 { default } else { sum / n as f64 } } /// Render a per-board vector as one slash-joined cell (blank when empty), each /// value formatted by `f` -- the shared shape of the Board HR/V/freq columns /// (round 19 #10). fn join_board(vals: &[f64], f: impl Fn(f64) -> String) -> String { if vals.is_empty() { String::new() } else { vals.iter().map(|&v| f(v)).collect::>().join(" / ") } } /// Render the combined Hashrate cell "actual/expected" (no spaces around the /// slash, prefix-only unit): blank when neither is known, the bare actual when /// only it is known, "-/" when only the expected is known, and /// "/" when both are (e.g. "80.5T/95.0T"). fn combined_si(actual_ths: f64, actual_known: bool, expected_ths: f64) -> String { match ( format_hashrate_actual(actual_ths, actual_known), format_hashrate_ths(expected_ths), ) { (None, None) => String::new(), (Some(a), None) => a, (None, Some(e)) => format!("-/{e}"), (Some(a), Some(e)) => format!("{a}/{e}"), } } /// Same combined rendering as `combined_si`, for a plain integer count /// (hashboards, total chips) instead of an SI-formatted rate. fn combined_count(actual: Option, expected: Option) -> String { match (actual, expected) { (None, None) => String::new(), (Some(a), None) => a.to_string(), (None, Some(e)) => format!("- / {e}"), (Some(a), Some(e)) => format!("{a} / {e}"), } } /// An RGB colour (0-255 per channel) for a coloured text segment. pub type Rgb = (u8, u8, u8); /// One coloured text segment: an optional colour plus its text. Cells with /// two-tone / multi-tone content (actual vs expected, per-fan colours) are built /// as a `Vec` and encoded via [`encode_segments`]. pub type Segment = (Option, String); /// Encode colored text segments for a custom-rendered cell (see the wx-rs /// `SegmentRenderer`): segments are joined by U+001F, and within a segment an /// optional uppercase RRGGBB color is separated from its text by U+001E. /// `decode_segments_plain` is the inverse for anything that just wants the /// plain text (filtering, sorting, tests). pub fn encode_segments(segs: &[Segment]) -> String { segs.iter() .map(|(color, text)| { let hex = color .map(|(r, g, b)| format!("{r:02X}{g:02X}{b:02X}")) .unwrap_or_default(); format!("{hex}\u{1e}{text}") }) .collect::>() .join("\u{1f}") } /// Strip the encoding `encode_segments` applies, returning just the /// concatenated text. A plain string with no U+001E in it (i.e. never passed /// through `encode_segments`) round-trips unchanged, so this is safe to call /// on any cell value. pub fn decode_segments_plain(s: &str) -> String { if !s.contains('\u{1e}') { return s.to_string(); } s.split('\u{1f}') .map(|seg| { seg.split_once('\u{1e}') .map(|(_, text)| text) .unwrap_or(seg) }) .collect::() } /// Replace every case-insensitive occurrence of `placeholder` in `s` with /// `value` (round 14 #7 worker templates). Placeholders and the surrounding /// worker name are ASCII, so lowercasing preserves byte offsets; a non-ASCII /// input (offsets would shift) falls back to a case-sensitive replace. fn replace_placeholder_ci(s: &str, placeholder: &str, value: &str) -> String { if !s.is_ascii() { return s.replace(placeholder, value); } let hay = s.to_ascii_lowercase(); let needle = placeholder.to_ascii_lowercase(); let mut out = String::with_capacity(s.len()); let mut last = 0usize; let mut from = 0usize; while let Some(rel) = hay[from..].find(&needle) { let at = from + rel; out.push_str(&s[last..at]); out.push_str(value); last = at + placeholder.len(); from = last; } out.push_str(&s[last..]); out } /// Split a full pool worker "account.worker" into (account, worker). Mining /// pools name a worker "."; split on the first '.'. With no '.', /// the whole string is the account and the worker name is empty. fn split_worker(full: &str) -> (&str, &str) { match full.split_once('.') { Some((account, worker)) => (account, worker), None => (full, ""), } } /// Compact human duration (e.g. "3d 4h", "5h 12m", "42m", "18s"). pub fn format_uptime(secs: u64) -> String { if secs == 0 { return String::new(); } let d = secs / 86_400; let h = (secs % 86_400) / 3600; let m = (secs % 3600) / 60; let s = secs % 60; if d > 0 { format!("{d}d {h}h") } else if h > 0 { format!("{h}h {m}m") } else if m > 0 { format!("{m}m") } else { format!("{s}s") } } /// Pack a dotted-quad IPv4 string into a u32 for numeric ordering, so /// "10.255.1.9" sorts before "10.255.1.10" (a plain string sort gets this /// wrong). Anything unparseable sorts first (0). `pub(crate)` so the headless /// self-test can build the same numeric order it asserts the view against. pub(crate) fn ip_to_u32(s: &str) -> u32 { let mut parts = s.split('.'); let mut acc = 0u32; for _ in 0..4 { let octet: u32 = parts .next() .and_then(|p| p.trim().parse().ok()) .unwrap_or(0); acc = (acc << 8) | (octet & 0xff); } acc } /// What a miner supports being told to do, probed from asic-rs' `supports_*` /// capability methods at scan time. The right-click menu offers an action only /// when every selected miner supports it (the intersection of capabilities). #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct MinerCaps { pub fault_light: bool, pub restart: bool, pub pause: bool, pub resume: bool, pub power_limit: bool, pub tuning: bool, /// Round 17 C: supports setting a structured hashrate target via /// `set_tuning_config` (the firmware actively tunes by hashrate, e.g. ePIC). /// Power targets are covered by `power_limit`. pub hashrate_target: bool, /// Round 18 / roadmap G3: supports selecting a named firmware preset/profile /// via `set_tuning_config(TuningTarget::Preset)` (LuxOS profiles, VNish presets). /// The available presets are read live into `MinerRow::presets` at scan time. pub supports_presets: bool, /// Whether this miner's asic-rs driver supports `upgrade_firmware` /// (probed via `supports_upgrade_firmware()` at scan time). pub firmware_flash: bool, /// Whether this miner's driver supports writing pool configuration (probed /// via `supports_pools_config()` at scan time; round 14 #7). pub pools: bool, /// Round 17 B: supports setting the timezone / changing the web password / /// factory reset (probed via the matching `supports_*()` at scan time). pub timezone: bool, pub change_password: bool, pub factory_reset: bool, } impl MinerCaps { /// The capabilities common to `self` and `other` (logical AND per action). pub fn intersect(self, other: MinerCaps) -> MinerCaps { MinerCaps { fault_light: self.fault_light && other.fault_light, restart: self.restart && other.restart, pause: self.pause && other.pause, resume: self.resume && other.resume, power_limit: self.power_limit && other.power_limit, tuning: self.tuning && other.tuning, hashrate_target: self.hashrate_target && other.hashrate_target, supports_presets: self.supports_presets && other.supports_presets, firmware_flash: self.firmware_flash && other.firmware_flash, pools: self.pools && other.pools, timezone: self.timezone && other.timezone, change_password: self.change_password && other.change_password, factory_reset: self.factory_reset && other.factory_reset, } } /// The capabilities common to every miner in `caps` (all-true identity when /// empty is intentionally avoided: an empty selection has no common caps). pub fn intersect_all(caps: impl IntoIterator) -> MinerCaps { let mut it = caps.into_iter(); match it.next() { Some(first) => it.fold(first, MinerCaps::intersect), None => MinerCaps::default(), } } /// True when no action is supported (nothing to offer in the menu). pub fn is_empty(self) -> bool { self == MinerCaps::default() } /// Whether the miner exposes any writable control action at all. Used to /// infer the "Access" (locked/unlocked) column: no control -> view-only. pub fn any_control(self) -> bool { self.fault_light || self.restart || self.pause || self.resume || self.power_limit || self.tuning || self.hashrate_target || self.supports_presets || self.firmware_flash || self.pools || self.timezone || self.change_password || self.factory_reset } } /// Per-hashboard health for the Boards column's status dots (round 11 #10): /// green = present and hashing, red = present but idle/faulty, grey = expected /// but not detected at all. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BoardHealth { Ok, Fault, Missing, } /// Which physical component a miner fault message is attributed to (round 16 #1). /// Mapped from asic-rs's structured `MinerMessage.component`; `Other` covers /// messages with no specific component (e.g. an ambient-temperature warning). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FaultComponent { Power, Control, Fan(usize), Board(usize), Other, } /// One structured fault/message from a miner (round 16 #1). Carries the specific /// human-readable text and the component it belongs to, so the Health column's /// per-icon tooltips can show the actual fault (e.g. "Slot 0 error reading chip /// id") on the specific board rather than a generic "faulted". #[derive(Debug, Clone)] pub struct Fault { pub component: FaultComponent, pub message: String, /// Firmware's numeric error code for this message, or 0 when none. Shown in /// the tooltip alongside the text (round 17 R2) so an operator can look the /// code up. pub code: u64, /// True for Error severity; false for Warning. (Info is dropped upstream.) pub is_error: bool, } impl Fault { /// The tooltip line for this fault: the message, with the firmware error code /// appended when there is one (round 17 R2). pub fn display_line(&self) -> String { if self.code != 0 { format!("{} (code {})", self.message, self.code) } else { self.message.clone() } } } /// One component's health for the Health icon column (round 13 #3). Rendered as a /// coloured icon: grey = unreachable / not detected, red = detected but not /// functioning, yellow = functioning sub-optimally, green = fully functioning. /// The `level` ordering (worst first) is also the sort order. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum CompHealth { Unreachable, Down, Degraded, Ok, } impl CompHealth { /// 0 (worst) .. 3 (best), for the Health column sort keys. pub fn level(self) -> i32 { match self { CompHealth::Unreachable => 0, CompHealth::Down => 1, CompHealth::Degraded => 2, CompHealth::Ok => 3, } } } /// Which component the Health column is currently sorted by (round 13 #3). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HealthFacet { Overall, Power, Fans, Boards, } /// One selectable firmware preset/profile (round 18 / roadmap G3). `name` is the /// identifier the firmware expects (e.g. LuxOS "540MHz", VNish "5560"); `pretty` /// is an optional human summary (e.g. "2485 W ~ 111.5 TH @ 540 MHz"). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct MinerPreset { pub name: String, pub pretty: Option, } /// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the /// scalar fields the table can display. Absent metrics are `None` / empty / /// 0.0 and render as a blank cell. #[derive(Debug, Clone, Default)] pub struct MinerRow { pub ip: String, pub selected: bool, /// What this miner supports being told to do (for the right-click menu). pub caps: MinerCaps, // identity pub model: String, /// Manufacturer brand ("Antminer", "WhatsMiner", ...), its own column so the /// Model column can carry just the cleaned model name. pub brand: String, /// Model sub-variant: WhatsMiner's version block ("VE40"); blank for Antminer /// (its hashboard type is not reported over the network by asic-rs). pub submodel: String, pub mac: String, pub hostname: String, pub serial: String, /// Firmware family only ("Stock", "VNish", "Braiins", ...); the Firmware /// column colours by this. The version string lives in `fw_version`. pub firmware: String, pub fw_version: String, pub api_version: String, /// Combined "CPU (code)" control-board label (e.g. "AML (C76)"); `cpu` and /// `board_code` hold the split halves for their own columns. pub control_board: String, pub cpu: String, pub board_code: String, /// Mining algorithm (e.g. "SHA256", "Scrypt", "Equihash"), from asic-rs. pub algorithm: String, /// ASIC chip type/model (e.g. "BM1370") and hashboard model/part /// (e.g. "A3HB70601"), where the firmware reports them (round 19 #10: /// WhatsMiner, Braiins, ePIC; not exposed by Antminer/LuxOS). Empty = unknown. pub chip_type: String, pub hashboard_model: 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 /// detection needs an on-board SSH/I2C probe (a separate feature). pub pic_present: Option, /// Whether this miner is locked to view-only (no command writes). Inferred /// from whether any control capability is available: `None` = unknown, /// `Some(true)` = locked, `Some(false)` = unlocked/writable. pub write_locked: Option, /// Structured error/event lines from the miner (severity + text), most /// severe first. Empty means none. The Error column shows a summary; the /// full list is the hover tooltip (added with the tooltip bridge support). pub errors: Vec, /// Structured faults with their attributed component (round 16 #1/#2/#3), /// used to colour each Health icon and drive its specific per-icon tooltip. pub faults: Vec, // performance pub hashrate_ths: f64, /// Whether the firmware actually reported a current hashrate. A reported 0 /// renders as "0.00T"; only an unreadable/absent reading (this is false) shows /// the "-" dash. `hashrate_ths` alone can't distinguish the two (both are 0.0). pub hashrate_known: bool, /// Rolling average hashrate windows in TH/s (round 19 #10, T2): 1m/5m/15m/24h. /// 0.0 means the firmware does not report that window. pub hashrate_1m_ths: f64, pub hashrate_5m_ths: f64, pub hashrate_15m_ths: f64, pub hashrate_24h_ths: f64, pub expected_ths: f64, /// Per-hashboard hashrate in TH/s, index-aligned with the hashboards (index 0 /// = board 1). Drives the per-board Health tooltip (round 17 R2). Empty when /// the firmware reports no per-board hashrate. pub board_hashrates: Vec, /// Per-hashboard EXPECTED hashrate in TH/s, index-aligned with the hashboards. /// The per-board tooltip shows actual / expected (round 18 #3). Empty when the /// firmware reports no per-board expected hashrate. pub board_expected_hashrates: Vec, /// Per-hashboard configured voltage (V) and frequency (MHz), index-aligned /// with the hashboards (round 18 / roadmap G7 read side). Shown in the per-board /// Health tooltip; 0.0 where the firmware reports no value. pub board_voltages: Vec, pub board_frequencies: Vec, #[allow(dead_code)] // retained for the "slow" band; not shown as its own column pub efficiency: f64, pub power_w: f64, /// PSU output voltage/current, when the firmware reports them (round 17 R2 / /// roadmap G15). `None` until the PSU-info scan lands; the power tooltip then /// shows "V / A" for a healthy PSU instead of a bare "PSU OK". pub psu_out_voltage_v: Option, pub psu_out_current_a: Option, /// PSU identity + rated voltage envelope, when the firmware reports it (round /// 17 R5 / G15; ePIC today). `psu_version` is blank when unknown. pub psu_version: String, /// PSU serial number where the firmware reports it (round 19 #10: Braiins, /// WhatsMiner V3, VNish). Empty = unknown. pub psu_serial: String, pub psu_voltage_min_v: Option, pub psu_voltage_max_v: Option, /// Current structured tuning target, rendered for display (e.g. "2832 W", /// "96 TH/s", "preset 3550"), or None (round 17 C). pub tuning_target_label: Option, /// The configured power-limit setpoint in watts, when the firmware's tuning /// target is a power target (round 21 #2). Its own numeric Power-limit column, /// distinct from the mixed `tuning_target_label`. None when the target is a /// mode/preset/hashrate target or unreported. pub power_limit_w: Option, /// The firmware's selectable named presets/profiles, read live at scan time /// when `caps.supports_presets` (round 18 / roadmap G3). Empty otherwise. pub presets: Vec, /// Advertised power-target envelope in watts, when the firmware reports one /// (round 17 C, e.g. Braiins 944-6435 W). Bounds + validate the power-target /// prompt; `None` leaves it unbounded. pub power_target_min_w: Option, pub power_target_max_w: Option, /// Advertised hashrate-target envelope in TH/s, when reported (round 17 C). pub hashrate_target_min_ths: Option, pub hashrate_target_max_ths: Option, pub tuning_percent: Option, // thermal / cooling /// Average chip temperature (used for sorting/colour banding of the /// combined Chip-temp cell). pub chip_temp_c: f64, /// Per-hashboard chip temperature (hottest chip per board), shown in the /// Chip-temp column as "77 / 64 / 74". Empty falls back to the average. pub board_temps: Vec, /// Coolant/immersion-fluid temperature (liquid-cooled miners only). pub fluid_temp_c: f64, /// Environment/ambient air temperature. asic-rs reports air-cooled miners' /// ambient reading in its `fluid_temperature` field (see the WhatsMiner /// backends' "Env Temp"/"environment-temperature" key); the scan routes it /// here for air-cooled models so it isn't mislabelled as a fluid temp /// (round 11 #17). pub env_temp_c: f64, pub outlet_temp_c: f64, /// Board temperature safety thresholds in Celsius (round 19 #10, T3): target / /// hot / dangerous. `None` per field when the firmware does not report it. pub temp_target_c: Option, pub temp_hot_c: Option, pub temp_dangerous_c: Option, /// Individual cooling-fan RPMs (empty if unknown). PSU fan is tracked /// separately below since it is not part of the cooling-fan set. pub fan_rpms: Vec, /// Miner-level fan duty cycle as a percentage (round 19 #10, T3); `None` when /// the firmware does not report it (no firmware exposes a maximum RPM). pub fan_speed_percent: Option, pub psu_fan_rpm: f64, pub fan_count: Option, pub expected_fans: Option, // hardware counts pub total_chips: Option, pub expected_chips: Option, pub hashboards: Option, pub expected_hashboards: Option, /// Per-hashboard health for the Boards status dots (round 11 #10), one entry /// per expected board, ordered by position (index 0 = board 1). Empty = no /// per-board data (the cell renders blank). pub board_status: Vec, // pool: active-pool convenience fields, plus the (url, worker) of each // configured pool (miners usually allow up to 3 redundant pools). pub worker: String, pub pool_url: String, pub pools: Vec<(String, String)>, // shares pub best_share: Option, pub session_best_share: Option, /// Accepted / rejected share counts, summed across all configured pools /// (round 19 #10). `None` when the firmware reports neither. pub accepted_shares: Option, pub rejected_shares: Option, /// Cumulative share statistics from the miner summary (round 19 #10, T2): /// difficulty-weighted accepted / rejected work, raw stale count, and blocks /// found. `None` where the firmware does not report the value. pub difficulty_accepted: Option, pub difficulty_rejected: Option, pub stale_shares: Option, pub found_blocks: Option, // state pub uptime_secs: u64, pub light_flashing: Option, pub operating_state: String, /// Auto-tuner status label (round 19 #10, T3); empty when not reported. pub tuner_status: String, pub is_mining: bool, pub slow: bool, /// Not-mining because an operator paused it (distinct from simply idle); /// see `is_paused`. pub paused: bool, } impl MinerRow { /// The row's status label. Only miners that actually responded to a scan /// become rows, so there is no "offline" state: a responding miner that is /// not mining is "not hashing". pub fn status(&self) -> &'static str { if self.slow { "slow" } else if self.paused { "paused" } else if self.is_mining { "hashing" } else { "not hashing" } } /// Power-supply health (round 13 #3). Green when the miner is drawing power, /// its PSU fan is spinning, or it is actively mining (all prove the PSU is /// live); grey (unknown) otherwise -- asic-rs has no direct PSU-fault flag, so /// a missing wattage reading is treated as unknown, never a false "down". pub fn power_health(&self) -> CompHealth { // A miner drawing power / spinning its PSU fan / actively mining has a live // PSU regardless of any warning flag. let delivering = self.power_w > 0.0 || self.psu_fan_rpm > 0.0 || self.is_mining; // A reported PSU fault while the miner is actually mining is a warning, not // a failure -- yellow, not red (round 18 #2: some WhatsMiners flag a PSU // error while running fine). A fault on a miner that is not mining is a real // failure (red). if self.faults_for(FaultComponent::Power).next().is_some() { return if self.is_mining { CompHealth::Degraded } else { CompHealth::Down }; } if delivering { CompHealth::Ok } else { CompHealth::Unreachable } } /// Control-board health (round 13 #3, round 16 #1). The miner answered the /// scan, so its control board is reachable; red if the miner reports a /// control-board fault, yellow if it reports a miner-level fault with no /// specific component (e.g. ambient temperature too high), else green. pub fn control_health(&self) -> CompHealth { if self.faults_for(FaultComponent::Control).next().is_some() { CompHealth::Down } else if self.general_faults().next().is_some() { CompHealth::Degraded } else { CompHealth::Ok } } /// Iterator over this row's Error-severity faults for a given component. fn faults_for(&self, component: FaultComponent) -> impl Iterator { self.faults .iter() .filter(move |f| f.is_error && f.component == component) } /// Error-severity faults not tied to a specific component (control-board / /// miner-level), for the control-board icon tooltip. fn general_faults(&self) -> impl Iterator { self.faults .iter() .filter(|f| f.is_error && matches!(f.component, FaultComponent::Other)) } /// Per-fan health (round 13 #3), front-to-back / top-to-bottom in the order /// the miner reports its fans. A spinning fan is green, unless it is running /// well below its fastest sibling (< 50% of the max reported RPM), which is a /// sub-optimal fan (yellow); a reported 0 RPM is a stopped fan (red); a fan the /// miner expects but does not report is grey (not detected). Empty when the /// miner reports no fans at all. pub fn fan_healths(&self) -> Vec { let expected = self.expected_fans.map(|n| n as usize).unwrap_or(0); let n = expected.max(self.fan_rpms.len()); let max_rpm = self.fan_rpms.iter().cloned().fold(0.0_f64, f64::max); (0..n) .map(|i| match self.fan_rpms.get(i) { Some(&rpm) if rpm > 0.0 => { if max_rpm > 0.0 && rpm < 0.5 * max_rpm { CompHealth::Degraded } else { CompHealth::Ok } } Some(_) => CompHealth::Down, None => CompHealth::Unreachable, }) .collect() } /// Per-hashboard health (round 13 #3, reworked round 16 #2/#3). Layers three /// signals, most-authoritative last: /// 1. Base: the per-board status the miner reports (green ok / red faulted / /// grey missing), else the present-vs-expected board counts. /// 2. Per-board fault messages (round 16 #3): when the miner reports /// board-specific faults, ONLY the named boards are red and the rest are /// green -- a whole-miner stall zeroes every board's hashrate, so the raw /// status wrongly reds working boards that the error codes exonerate. /// 3. Power-supply fault (round 16 #2): the boards can't be powered or /// evaluated, so every board is grey (not red). pub fn board_healths(&self) -> Vec { // 1. Base health from board status / counts. let ok = if self.slow { CompHealth::Degraded } else { CompHealth::Ok }; let mut base: Vec = if !self.board_status.is_empty() { self.board_status .iter() .map(|h| match h { BoardHealth::Ok => ok, BoardHealth::Fault => CompHealth::Down, BoardHealth::Missing => CompHealth::Unreachable, }) .collect() } else { let present = self.hashboards.map(|n| n as usize).unwrap_or(0); let expected = self .expected_hashboards .map(|n| n as usize) .unwrap_or(present); let n = present.max(expected); (0..n) .map(|i| { if i < present { CompHealth::Ok } else { CompHealth::Unreachable } }) .collect() }; if base.is_empty() { return base; } // 2. Board-specific faults layer onto the base, most-authoritative last. A // board is grey ONLY when it is genuinely not detected (base Missing). // An ERROR-severity fault reds a detected board (round 18 #4b -- // WhatsMiner codes 540/560 must show red; boards still hashing during a // PSU fault stay green). A WARNING-severity fault means the board is // still working but sub-optimal (e.g. a few dead chips while it keeps // hashing near its target) -> yellow, never red (round 20 #1b: a miner at // ~83% with some failed chips is degraded, not broken). A whole-miner // stall reds every board's base, so when error codes name specific boards, // exonerate the boards they did NOT name back to healthy. let board_faulted = |i: usize| self.faults_for(FaultComponent::Board(i)).next().is_some(); let board_warned = |i: usize| { self.faults .iter() .any(|f| !f.is_error && f.component == FaultComponent::Board(i)) }; let any_error = (0..base.len()).any(board_faulted); if any_error || (0..base.len()).any(board_warned) { for (i, h) in base.iter_mut().enumerate() { // A genuinely-undetected board stays grey ("not detected") even when a // fault text names it ("chain N not found" describes that missing // board); grey-vs-red is the documented distinction (round 18 #12). if *h == CompHealth::Unreachable { continue; } if board_faulted(i) { *h = CompHealth::Down; // red: an error fault on a detected board } else if any_error && *h == CompHealth::Down { *h = ok; // stall-reddened but not named by the error codes } // A warning (no error) degrades a still-running board to yellow, but // never upgrades a board already red. if !board_faulted(i) && board_warned(i) && *h != CompHealth::Down { *h = CompHealth::Degraded; } } } base } /// The sort key for the Health column and its facet pseudo-columns (round 13 /// #3): higher = healthier, so an ascending sort surfaces the most-broken /// miners first (matching the existing Boards-column behaviour). Encoded as /// `worst-component-level * 1000 + sum-of-levels` so any red/grey component /// dominates, with the healthy-icon count as the tiebreak. A component with no /// data scores as healthy so unknown-but-fine miners don't masquerade as /// broken. pub fn health_score(&self, facet: HealthFacet) -> f64 { let score = |comps: &[CompHealth]| -> i64 { if comps.is_empty() { return CompHealth::Ok.level() as i64 * 1000 + CompHealth::Ok.level() as i64; } let min = comps.iter().map(|c| c.level()).min().unwrap_or(3) as i64; let sum: i64 = comps.iter().map(|c| c.level() as i64).sum(); min * 1000 + sum }; let val = match facet { HealthFacet::Power => score(&[self.power_health()]), HealthFacet::Fans => score(&self.fan_healths()), HealthFacet::Boards => score(&self.board_healths()), HealthFacet::Overall => { let mut all = vec![self.power_health(), self.control_health()]; all.extend(self.fan_healths()); all.extend(self.board_healths()); score(&all) } }; val as f64 } /// Human-readable fault messages attributed to a specific component /// (round 16 #1), for that Health icon's hover tooltip. fn fault_texts_for(&self, component: FaultComponent) -> Vec { self.faults .iter() .filter(|f| f.component == component) .map(|f| f.display_line()) .collect() } /// Fault messages not tied to a specific board/fan/PSU (miner-level or /// control-board), for the control-board icon tooltip (round 16 #1). fn general_fault_texts(&self) -> Vec { self.faults .iter() .filter(|f| matches!(f.component, FaultComponent::Other | FaultComponent::Control)) .map(|f| f.display_line()) .collect() } /// Per-icon hover tooltips for the Health column, in the same draw order (and /// length) as `encode_component_health`'s segments: power, control, each fan /// padded to `max_fans`, each hashboard padded to `max_boards` (round 15 #15, /// round 16 #1/#2). Each icon's tooltip carries the specific faults the miner /// reports for that component. pub fn health_tooltips(&self, max_fans: usize, max_boards: usize) -> Vec { let mut tips: Vec = Vec::with_capacity(2 + max_fans + max_boards); // Power (bolt). A working PSU shows its output voltage + amperage when the // firmware reports them (else a short OK); a faulted one shows the error // and code instead (round 17 R2). asic-rs does not yet surface PSU output // V/A (roadmap G15), so `psu_output` is None until that lands and the OK // branch shows just the status. let power_faults = self.fault_texts_for(FaultComponent::Power); if !power_faults.is_empty() { tips.push(power_faults.join("\n")); } else { tips.push(match (self.power_health(), self.psu_output_label()) { (CompHealth::Ok, Some(va)) => va, (CompHealth::Ok, None) => "PSU OK".to_string(), (CompHealth::Degraded, _) => "PSU sub-optimal".to_string(), (CompHealth::Down, _) => "PSU not delivering".to_string(), (CompHealth::Unreachable, _) => "PSU unknown".to_string(), }); } // Control board (brain) -- its own and the miner's un-attributed faults // with codes; a short OK when clean. let ctl_faults = self.general_fault_texts(); if !ctl_faults.is_empty() { tips.push(ctl_faults.join("\n")); } else { tips.push(match self.control_health() { CompHealth::Ok => "Control board OK".to_string(), _ => "Control board fault".to_string(), }); } // Fans -- just the RPM, unless the fan has a fault (then the error+code). let fans = self.fan_healths(); for i in 0..max_fans { let fault = self.fault_texts_for(FaultComponent::Fan(i)); let t = if !fault.is_empty() { fault.join("\n") } else { match fans.get(i) { Some(_) => format!("{:.0} rpm", self.fan_rpms.get(i).copied().unwrap_or(0.0)), None => String::new(), // padding slot for fleet alignment } }; tips.push(t); } // Hashboards -- an operating board shows its number (counting DOWN, n-1..0, // left to right) and actual/expected hashrate; a faulted board shows its // error+code; a board that is genuinely not detected shows "not detected" // (round 17 R2, round 18 #3 actual/expected + #4b). No generic // "Hashboard N: faulted" prose. let boards = self.board_healths(); let n = self.hashboards.map(|v| v as usize).unwrap_or(boards.len()); let unit = self.hashrate_unit(); for i in 0..max_boards { let fault = self.fault_texts_for(FaultComponent::Board(i)); let t = if !fault.is_empty() { fault.join("\n") } else if matches!(boards.get(i), Some(CompHealth::Unreachable)) { "not detected".to_string() } else if i < n { let num = n - 1 - i; // count down, left to right let actual = self.board_hashrates.get(i).copied().unwrap_or(0.0); let expected = self.board_expected_hashrates.get(i).copied().unwrap_or(0.0); let a = hashrate_num_for(&self.algorithm, actual); let e = hashrate_num_for(&self.algorithm, expected); let mut s = match (a, e) { (Some(a), Some(e)) => format!("{num} \u{00b7} {a} / {e} {unit}"), (Some(a), None) => format!("{num} \u{00b7} {a} {unit}"), _ => num.to_string(), }; // Per-board configured frequency / voltage (round 18 / G7 read side), // appended when the firmware reports them. let freq = self.board_frequencies.get(i).copied().unwrap_or(0.0); let volt = self.board_voltages.get(i).copied().unwrap_or(0.0); if freq > 0.0 { s.push_str(&format!(" \u{00b7} {freq:.0} MHz")); } if volt > 0.0 { s.push_str(&format!(" \u{00b7} {volt:.2} V")); } s } else { String::new() // padding slot for fleet alignment }; tips.push(t); } tips } /// The PSU output "V / A" tooltip label when the firmware reports it, else /// None. asic-rs does not yet expose PSU output voltage/current (roadmap G15), /// so this is a forward-compatible hook that stays None for now (round 17 R2). fn psu_output_label(&self) -> Option { match (self.psu_out_voltage_v, self.psu_out_current_a) { (Some(v), Some(a)) if v > 0.0 => Some(format!("{v:.1} V \u{00b7} {a:.1} A")), (Some(v), None) if v > 0.0 => Some(format!("{v:.1} V")), _ => None, } } /// The display unit for this miner's hashrate, by mining algorithm (round 18 /// #7). SHA256/Scrypt miners report TH/s; Equihash miners (Antminer Z15 / /// Zcash) report in Sol/s and must not be labelled TH/s. pub fn hashrate_unit(&self) -> &'static str { if self.algorithm.eq_ignore_ascii_case("equihash") { "Sol/s" } else { "TH/s" } } /// Rejected-share percentage of all submitted shares (round 19 #10), or /// `None` when the firmware reports neither count. pub fn reject_ratio(&self) -> Option { match (self.accepted_shares, self.rejected_shares) { (Some(a), Some(r)) => { let total = a.saturating_add(r); Some(if total > 0 { r as f64 / total as f64 * 100.0 } else { 0.0 }) } _ => None, } } /// Efficiency as (value, unit) for display, computed per algorithm (round 19 /// #9/#23). asic-rs stores efficiency as watts-per-TH for EVERY algorithm, /// which is meaningless for Equihash (whose rate is really Sol/s reinterpreted /// through the base H unit), so recompute J-per-thousand-Sol there from the /// real Sol/s count. SHA256/Scrypt families reuse asic-rs's J/TH value. /// `None` when power or hashrate is unknown, so the cell stays blank rather /// than showing a garbage or zero figure. pub fn efficiency_display(&self) -> Option<(f64, &'static str)> { if self.algorithm.eq_ignore_ascii_case("equihash") { if self.power_w <= 0.0 || self.hashrate_ths <= 0.0 { return None; } let sol_per_s = self.hashrate_ths * 1e12; Some((self.power_w / sol_per_s * 1000.0, "J/kSol")) } else if self.efficiency > 0.0 { Some((self.efficiency, "J/TH")) } else { None } } /// Compact plain-text summary of component health (round 13 #3), used as the /// Health column's filter/sort-fallback text and the base of its hover /// tooltip. e.g. "power ok, fans 3/4, boards 3/3". pub fn health_summary(&self) -> String { let ok = |comps: &[CompHealth]| comps.iter().filter(|c| **c == CompHealth::Ok).count(); let fans = self.fan_healths(); let boards = self.board_healths(); let mut parts = vec![match self.power_health() { CompHealth::Ok => "power ok".to_string(), _ => "power ?".to_string(), }]; if !fans.is_empty() { parts.push(format!("fans {}/{}", ok(&fans), fans.len())); } if !boards.is_empty() { parts.push(format!("boards {}/{}", ok(&boards), boards.len())); } parts.join(", ") } /// Expand a worker-name template against this miner's scanned data (round 14 /// #7). Placeholders are case-insensitive and wrapped in braces: /// {ip1}..{ip4} the four IP octets {serial} serial number /// {mac} MAC with ':' removed {brand} manufacturer /// {model} model {submodel} model sub-variant /// {cpu} control-board CPU {cb} control-board code /// {firmware} firmware family {hostname} hostname /// {nameplate-hr} rated hashrate in TH (integer, no unit) /// Unknown placeholders are left untouched so a typo is visible. pub fn expand_worker_template(&self, template: &str) -> String { let octets: Vec<&str> = self.ip.split('.').collect(); let oct = |i: usize| octets.get(i).copied().unwrap_or("").to_string(); let nameplate = if self.expected_ths > 0.0 { format!("{:.0}", self.expected_ths) } else { String::new() }; let subs: [(&str, String); 15] = [ ("ip1", oct(0)), ("ip2", oct(1)), ("ip3", oct(2)), ("ip4", oct(3)), ("serial", self.serial.clone()), ("mac", self.mac.replace(':', "")), ("nameplate-hr", nameplate), ("brand", self.brand.clone()), ("model", self.model.clone()), ("submodel", self.submodel.clone()), ("cpu", self.cpu.clone()), ("cb", self.board_code.clone()), ("firmware", self.firmware.clone()), ("hostname", self.hostname.clone()), ("fw", self.firmware.clone()), ]; let mut out = template.to_string(); for (key, val) in subs { out = replace_placeholder_ci(&out, &format!("{{{key}}}"), &val); } out } /// Upsert into `rows` by ip; returns true if the row is new. pub fn upsert_into(self, rows: &mut Vec) -> bool { if let Some(r) = rows.iter_mut().find(|r| r.ip == self.ip) { let selected = r.selected; *r = self; r.selected = selected; return false; } rows.push(self); true } } /// The single source of truth for the "paused" classification: a miner is /// counted as operator-paused when it is not currently mining and its raw /// operating-state string says so (case-insensitively), shared by the live /// scan (`scan::to_row`) and the fixtures/tests. /// /// "Paused" covers every intentional, resumable halt -- operator- or /// firmware-initiated -- not just the literal "Paused" state: a miner an operator /// stopped is halted on purpose, not broken, so it must read blue in Health and /// count under the Paused KPI rather than "not hashing". Firmwares spell it /// differently: VNish reports "stopped", Braiins uses Paused/Stopped/Suspended, /// others "paused". A failure is a distinct Error state (never matched here) and /// still reads as broken (round 19 #19). pub fn is_paused(operating_state: &str, is_mining: bool) -> bool { if is_mining { return false; } let s = operating_state.to_lowercase(); s.contains("pause") || s.contains("stop") || s.contains("suspend") } /// The typed-confirmation gate for the irreversible firmware-flash action: the /// operator must type exactly "FLASH" (surrounding whitespace ignored, but not /// case-folded and not a prefix). Pure so the guard is unit-testable without a /// live dialog. pub fn flash_confirmed(input: &str) -> bool { input.trim() == "FLASH" } /// Model columns. Ip is fixed (always shown first); the rest map 1:1 to a /// scannable metric and can be shown/hidden/reordered. Row selection replaces /// the old checkbox column. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum Column { Ip, Hashrate, /// Sort-only pseudo-column (round 11 #16): the actual/expected hashrate /// ratio. Deliberately NOT in `ALL_COLUMNS`, so it never appears in the /// column picker or the display order; it exists only as a `sort` target the /// Hashrate header cycles into. HashrateRel, /// Rolling average hashrate windows (round 19 #10, T2): 1m/5m/15m/24h, each a /// single TH/s value. Populated per firmware where the API exposes the window /// (LuxOS and Braiins report all four; WhatsMiner V1 1m/5m/15m, V3 1m/15m; /// Antminer/ePIC/VNish report none). Auto-hidden when empty across the fleet. Hashrate1m, Hashrate5m, Hashrate15m, Hashrate24h, Power, ChipTemp, // Per-fan RPM columns (round 19 #8): the old single "Fan (RPM)" column packed // every fan into one slash-joined cell; these split it into one column per fan // (fans 1-4), auto-hidden when a miner has fewer. asic-rs exposes no maximum / // target RPM, so each shows the actual RPM only. Fan1, Fan2, Fan3, Fan4, /// Miner-level fan duty cycle % (round 19 #10, T3). No firmware exposes a /// maximum RPM, so this normalized duty cycle is the fan-load indicator. /// Populated on ePIC, LuxOS, and Braiins; others leave it empty (auto-hidden). FanSpeedPercent, Firmware, FwVersion, Worker, PoolAccount, Model, Brand, Submodel, /// Component-health icon column (round 13 #3): power, control board, each /// fan, and each hashboard drawn as a coloured icon (grey unreachable, red /// down, yellow sub-optimal, green healthy). Replaces the old Errors, Boards /// (hashboard dots) and Status columns. Health, /// Sort-only pseudo-columns (round 13 #3): the Health header left-click cycles /// its sort through these facets so the fleet can be ordered by whichever /// component matters (power, fans, hashboards) instead of overall health. /// Deliberately NOT in `ALL_COLUMNS`, so they never appear in the picker. HealthPower, HealthFans, HealthBoards, Status, Efficiency, FluidTemp, EnvTemp, OutletTemp, /// Board temperature safety thresholds (round 19 #10, T3): target / hot / /// dangerous. Populated where the firmware reports them (LuxOS full set, ePIC /// hot+dangerous, Braiins defaults, VNish target+dangerous); auto-hidden empty. TargetTemp, HotTemp, DangerousTemp, PsuFan, /// PSU identity + rated voltage envelope (round 17 R5). Populated where the /// firmware exposes PSU info (ePIC today). PsuVersion, PsuSerial, PsuVMin, PsuVMax, FanCount, ExpectedFans, TotalChips, Mac, Hostname, Serial, ApiVersion, Cpu, BoardCode, ChipType, HbType, Algorithm, Pic, Locked, Error, Uptime, Light, OperatingState, /// Auto-tuner status label (round 19 #10, T3); Braiins/ePIC today. Tuner, BestShare, SessionBestShare, TuningPercent, // Round 19 #10: more scanned values surfaced as columns. /// Current tuning target (power or hashrate), e.g. "3200 W" or "100 TH". Target, /// Configured power-limit setpoint in watts (round 21 #2), e.g. WhatsMiner /// "Power Limit". A dedicated numeric column, distinct from the mixed Target. PowerLimit, /// Accepted / rejected share counts and the rejection ratio. Accepted, Rejected, RejectRatio, /// Cumulative share statistics (round 19 #10, T2): difficulty-weighted /// accepted / rejected work, raw stale count, and blocks found. Populated on /// the cgminer family (Antminer, LuxOS, WhatsMiner V1/V2); other firmwares /// leave them empty (auto-hidden). DiffAccepted, DiffRejected, StaleShares, Blocks, /// Per-hashboard hashrate / voltage / frequency, slash-joined like Chip temp. BoardHashrate, BoardVoltage, BoardFrequency, PoolUrl, Pool1Url, Pool1Worker, Pool2Url, Pool2Worker, Pool3Url, Pool3Worker, } /// Every column, in registry order. Ip first, then the default-visible set /// (UI-SPEC order), then all remaining metrics. pub const ALL_COLUMNS: [Column; 73] = [ Column::Ip, Column::Hashrate, Column::Hashrate1m, Column::Hashrate5m, Column::Hashrate15m, Column::Hashrate24h, Column::Health, Column::Power, Column::ChipTemp, Column::Fan1, Column::Fan2, Column::Fan3, Column::Fan4, Column::FanSpeedPercent, Column::Firmware, Column::FwVersion, // Pool account (the part before the dot) before Worker (the rig part after // it), per round 19 #22. Column::PoolAccount, Column::Worker, Column::Model, Column::Brand, Column::Submodel, Column::Efficiency, Column::FluidTemp, Column::EnvTemp, Column::OutletTemp, Column::TargetTemp, Column::HotTemp, Column::DangerousTemp, Column::PsuFan, Column::PsuVersion, Column::PsuSerial, Column::PsuVMin, Column::PsuVMax, Column::FanCount, Column::ExpectedFans, Column::TotalChips, Column::Mac, Column::Hostname, Column::Serial, Column::ApiVersion, Column::Cpu, Column::BoardCode, Column::ChipType, Column::HbType, Column::Algorithm, Column::Pic, Column::Locked, Column::Uptime, Column::Light, Column::OperatingState, Column::Tuner, Column::BestShare, Column::SessionBestShare, Column::TuningPercent, Column::Target, Column::PowerLimit, Column::Accepted, Column::Rejected, Column::RejectRatio, Column::DiffAccepted, Column::DiffRejected, Column::StaleShares, Column::Blocks, Column::BoardHashrate, Column::BoardVoltage, Column::BoardFrequency, Column::PoolUrl, Column::Pool1Url, Column::Pool1Worker, Column::Pool2Url, Column::Pool2Worker, Column::Pool3Url, Column::Pool3Worker, ]; /// The columns shown by default (UI-SPEC), after the fixed IP column, in display /// order: model, health (component icons), hashrate, power, chip temp, firmware, /// CPU, access. The Health column (round 13 #3) folds the old Errors, Boards and /// Status columns into one row of per-component icons. pub const DEFAULT_VISIBLE: [Column; 9] = [ Column::Model, Column::Health, Column::Hashrate, Column::Power, Column::ChipTemp, Column::Firmware, Column::Cpu, Column::Locked, // Locate-light beacon, last (round 15 #6). Column::Light, ]; impl Column { pub fn title(self) -> &'static str { match self { Column::Ip => "IP", Column::Hashrate => "Hashrate", Column::HashrateRel => "Rel. hashrate", Column::Hashrate1m => "HR 1m", Column::Hashrate5m => "HR 5m", Column::Hashrate15m => "HR 15m", Column::Hashrate24h => "HR 24h", Column::Power => "Power", Column::ChipTemp => "Chip temp", Column::Fan1 => "Fan 1 (RPM)", Column::Fan2 => "Fan 2 (RPM)", Column::Fan3 => "Fan 3 (RPM)", Column::Fan4 => "Fan 4 (RPM)", Column::FanSpeedPercent => "Fan %", Column::Target => "Target", Column::PowerLimit => "Power limit", Column::Accepted => "Accepted", Column::Rejected => "Rejected", Column::RejectRatio => "Reject %", Column::DiffAccepted => "Diff acc", Column::DiffRejected => "Diff rej", Column::StaleShares => "Stale", Column::Blocks => "Blocks", Column::BoardHashrate => "Board HR", Column::BoardVoltage => "Board V", Column::BoardFrequency => "Board freq", Column::Firmware => "Firmware", Column::FwVersion => "FW Version", Column::Worker => "Worker", Column::PoolAccount => "Pool account", Column::Model => "Model", Column::Brand => "Brand", Column::Submodel => "Submodel", Column::Health => "Health", Column::HealthPower => "Health (power)", Column::HealthFans => "Health (fans)", Column::HealthBoards => "Health (boards)", Column::Status => "Status", Column::Efficiency => "Efficiency", Column::FluidTemp => "Fluid temp", Column::EnvTemp => "Env temp", Column::OutletTemp => "Outlet temp", Column::TargetTemp => "Target temp", Column::HotTemp => "Hot temp", Column::DangerousTemp => "Dangerous temp", Column::PsuFan => "PSU fan (RPM)", Column::PsuVersion => "PSU version", Column::PsuSerial => "PSU serial", Column::PsuVMin => "PSU Vmin", Column::PsuVMax => "PSU Vmax", Column::FanCount => "Fans", Column::ExpectedFans => "Fans (exp)", Column::TotalChips => "Chips", Column::Mac => "MAC", Column::Hostname => "Hostname", Column::Serial => "Serial", Column::ApiVersion => "API ver", Column::Cpu => "CPU", Column::BoardCode => "Control Board", Column::ChipType => "Chip", Column::HbType => "HB model", Column::Algorithm => "Algorithm", Column::Pic => "PIC", Column::Locked => "Access", Column::Error => "Errors", Column::Uptime => "Uptime", Column::Light => "Light", Column::OperatingState => "State", Column::Tuner => "Tuner", Column::BestShare => "Best share", Column::SessionBestShare => "Session best", Column::TuningPercent => "Tuning %", Column::PoolUrl => "Pool URL", Column::Pool1Url => "Pool 1 URL", Column::Pool1Worker => "Pool 1 worker", Column::Pool2Url => "Pool 2 URL", Column::Pool2Worker => "Pool 2 worker", Column::Pool3Url => "Pool 3 URL", Column::Pool3Worker => "Pool 3 worker", } } pub fn width(self) -> i32 { match self { Column::Ip => 130, Column::Hashrate => 110, Column::HashrateRel => 110, Column::Hashrate1m | Column::Hashrate5m | Column::Hashrate15m | Column::Hashrate24h => { 95 } Column::Power => 90, Column::ChipTemp | Column::FluidTemp | Column::EnvTemp | Column::OutletTemp => 95, Column::TargetTemp | Column::HotTemp | Column::DangerousTemp => 105, Column::Fan1 | Column::Fan2 | Column::Fan3 | Column::Fan4 | Column::PsuFan => 90, Column::FanSpeedPercent => 80, Column::Target => 110, Column::PowerLimit => 95, Column::Accepted | Column::Rejected => 100, Column::RejectRatio => 90, Column::DiffAccepted | Column::DiffRejected => 110, Column::StaleShares | Column::Blocks => 80, Column::BoardHashrate | Column::BoardVoltage | Column::BoardFrequency => 130, Column::PsuVersion => 100, Column::PsuSerial => 150, Column::PsuVMin | Column::PsuVMax => 90, Column::Firmware => 110, Column::FwVersion => 130, Column::Worker => 130, Column::PoolAccount => 120, Column::Model => 150, Column::Brand => 100, Column::Submodel => 100, // Wide enough for power + control board + several fan and hashboard // icons in a row (round 13 #3). Column::Health => 170, Column::HealthPower | Column::HealthFans | Column::HealthBoards => 170, Column::Status => 95, Column::Efficiency => 120, Column::FanCount | Column::TotalChips => 70, Column::ExpectedFans | Column::TuningPercent => 90, Column::Mac | Column::Hostname | Column::Serial => 150, Column::ApiVersion | Column::Light => 90, Column::Cpu => 70, Column::BoardCode => 70, Column::ChipType => 90, Column::HbType => 110, Column::Algorithm => 100, Column::Pic => 70, Column::Locked => 90, Column::Error => 160, Column::Uptime => 100, Column::OperatingState => 100, Column::Tuner => 100, Column::BestShare | Column::SessionBestShare => 110, Column::PoolUrl | Column::Pool1Url | Column::Pool2Url | Column::Pool3Url => 200, Column::Pool1Worker | Column::Pool2Worker | Column::Pool3Worker => 150, } } /// Whether the column holds a continuous numeric value. Such columns sort /// numerically and are excluded from the Excel-style value filter (a /// per-value checklist only makes sense for categorical data). pub fn is_numeric(self) -> bool { matches!( self, Column::Hashrate | Column::HashrateRel | Column::Hashrate1m | Column::Hashrate5m | Column::Hashrate15m | Column::Hashrate24h | Column::Power | Column::Efficiency | Column::ChipTemp | Column::FluidTemp | Column::EnvTemp | Column::OutletTemp | Column::TargetTemp | Column::HotTemp | Column::DangerousTemp | Column::Fan1 | Column::Fan2 | Column::Fan3 | Column::Fan4 | Column::FanSpeedPercent | Column::Accepted | Column::Rejected | Column::RejectRatio | Column::DiffAccepted | Column::DiffRejected | Column::StaleShares | Column::Blocks | Column::BoardHashrate | Column::BoardVoltage | Column::BoardFrequency | Column::PsuFan | Column::PsuVMin | Column::PsuVMax | Column::FanCount | Column::ExpectedFans | Column::TotalChips | Column::Uptime | Column::BestShare | Column::SessionBestShare | Column::TuningPercent | Column::PowerLimit ) } /// The numeric value used for numeric filtering, or `None` for a text column /// or a blank/missing cell (so `> 0` never matches an absent metric). A /// "blank" cell is exactly one the table renders empty -- several value-type /// columns store an absent reading as 0.0, which `cell()` blanks; mirror that /// here so a filter like "ChipTemp <= 50" cannot match a miner with no /// temperature reading. pub fn num_value(&self, r: &MinerRow) -> Option { // The combined (actual/expected) columns (Hashrate, TotalChips) must never // let a numeric filter match a row that only has an expected value: their cell() // renders "- / " (non-empty) in that case, so the generic // blank check below is not enough on its own. match self { // An unreadable hashrate has no numeric value; a reported 0 does (0.0), // so a filter like "hashrate > 0" excludes a stopped miner but "<= 50" // still matches it. Column::Hashrate if !r.hashrate_known => return None, Column::TotalChips if r.total_chips.is_none() => return None, _ => {} } if !self.is_numeric() || self.cell(r).is_empty() { return None; } match self.sort_key(r) { SortKey::Num(v) if v.is_finite() => Some(v), _ => None, } } /// Sort key. Numeric columns compare by their underlying number (absent = /// -inf so blanks sort to the bottom of a descending sort); others compare /// as lowercase strings. pub fn sort_key(&self, r: &MinerRow) -> SortKey { let none = f64::NEG_INFINITY; match self { Column::Hashrate => SortKey::Num(r.hashrate_ths), // Rolling average windows; a 0.0 (window not reported) sorts to the // bottom (round 19 #10, T2). Column::Hashrate1m => SortKey::Num(if r.hashrate_1m_ths > 0.0 { r.hashrate_1m_ths } else { none }), Column::Hashrate5m => SortKey::Num(if r.hashrate_5m_ths > 0.0 { r.hashrate_5m_ths } else { none }), Column::Hashrate15m => SortKey::Num(if r.hashrate_15m_ths > 0.0 { r.hashrate_15m_ths } else { none }), Column::Hashrate24h => SortKey::Num(if r.hashrate_24h_ths > 0.0 { r.hashrate_24h_ths } else { none }), // Relative hashrate = actual/expected; unknown expectation sorts to // the bottom (round 11 #16). Column::HashrateRel => { SortKey::Num(actual_expected_ratio(r.hashrate_ths, r.expected_ths).unwrap_or(none)) } Column::Power => SortKey::Num(r.power_w), Column::Efficiency => { SortKey::Num(r.efficiency_display().map(|(v, _)| v).unwrap_or(none)) } Column::ChipTemp => SortKey::Num(r.chip_temp_c), Column::FluidTemp => SortKey::Num(r.fluid_temp_c), Column::EnvTemp => SortKey::Num(r.env_temp_c), Column::OutletTemp => SortKey::Num(r.outlet_temp_c), Column::TargetTemp => SortKey::Num(r.temp_target_c.unwrap_or(none)), Column::HotTemp => SortKey::Num(r.temp_hot_c.unwrap_or(none)), Column::DangerousTemp => SortKey::Num(r.temp_dangerous_c.unwrap_or(none)), Column::Fan1 => SortKey::Num(r.fan_rpms.first().copied().unwrap_or(none)), Column::Fan2 => SortKey::Num(r.fan_rpms.get(1).copied().unwrap_or(none)), Column::Fan3 => SortKey::Num(r.fan_rpms.get(2).copied().unwrap_or(none)), Column::Fan4 => SortKey::Num(r.fan_rpms.get(3).copied().unwrap_or(none)), Column::FanSpeedPercent => SortKey::Num(r.fan_speed_percent.unwrap_or(none)), Column::Accepted => SortKey::Num(r.accepted_shares.map(|v| v as f64).unwrap_or(none)), Column::Rejected => SortKey::Num(r.rejected_shares.map(|v| v as f64).unwrap_or(none)), Column::RejectRatio => SortKey::Num(r.reject_ratio().unwrap_or(none)), Column::DiffAccepted => SortKey::Num(r.difficulty_accepted.unwrap_or(none)), Column::DiffRejected => SortKey::Num(r.difficulty_rejected.unwrap_or(none)), Column::StaleShares => SortKey::Num(r.stale_shares.map(|v| v as f64).unwrap_or(none)), Column::Blocks => SortKey::Num(r.found_blocks.map(|v| v as f64).unwrap_or(none)), Column::BoardHashrate => SortKey::Num(avg_or(&r.board_hashrates, none)), Column::BoardVoltage => SortKey::Num(avg_positive(&r.board_voltages, none)), Column::BoardFrequency => SortKey::Num(avg_positive(&r.board_frequencies, none)), Column::PsuFan => SortKey::Num(r.psu_fan_rpm), Column::PowerLimit => SortKey::Num(r.power_limit_w.unwrap_or(none)), Column::PsuVMin => SortKey::Num(r.psu_voltage_min_v.unwrap_or(none)), Column::PsuVMax => SortKey::Num(r.psu_voltage_max_v.unwrap_or(none)), Column::FanCount => SortKey::Num(r.fan_count.map(|v| v as f64).unwrap_or(none)), Column::ExpectedFans => SortKey::Num(r.expected_fans.map(|v| v as f64).unwrap_or(none)), Column::TotalChips => SortKey::Num(r.total_chips.map(|v| v as f64).unwrap_or(none)), Column::Uptime => SortKey::Num(if r.uptime_secs > 0 { r.uptime_secs as f64 } else { none }), Column::BestShare => SortKey::Num(r.best_share.unwrap_or(none)), Column::SessionBestShare => SortKey::Num(r.session_best_share.unwrap_or(none)), Column::TuningPercent => { SortKey::Num(r.tuning_percent.map(|v| v as f64).unwrap_or(none)) } // IP sorts numerically (u32 fits exactly in f64), not lexically. Column::Ip => SortKey::Num(ip_to_u32(&r.ip) as f64), // Health column + its facet pseudo-columns (round 13 #3): higher = // healthier, so ascending surfaces the most-broken miners. Column::Health => SortKey::Num(r.health_score(HealthFacet::Overall)), Column::HealthPower => SortKey::Num(r.health_score(HealthFacet::Power)), Column::HealthFans => SortKey::Num(r.health_score(HealthFacet::Fans)), Column::HealthBoards => SortKey::Num(r.health_score(HealthFacet::Boards)), _ => SortKey::Str(self.cell(r).to_lowercase()), } } pub fn cell(&self, r: &MinerRow) -> String { let num = |v: f64, dp: usize, suffix: &str| -> String { if v > 0.0 { match dp { 0 => format!("{v:.0}{suffix}"), _ => format!("{v:.1}{suffix}"), } } else { String::new() } }; let count = |v: Option| -> String { v.map(|n| n.to_string()).unwrap_or_default() }; let pool_url = |i: usize| r.pools.get(i).map(|(u, _)| u.clone()).unwrap_or_default(); let pool_worker = |i: usize| r.pools.get(i).map(|(_, w)| w.clone()).unwrap_or_default(); match self { Column::Ip => r.ip.clone(), Column::Hashrate => combined_si(r.hashrate_ths, r.hashrate_known, r.expected_ths), // Rolling average windows: a single TH/s value, blank when not reported // (round 19 #10, T2). Column::Hashrate1m => format_hashrate_ths(r.hashrate_1m_ths).unwrap_or_default(), Column::Hashrate5m => format_hashrate_ths(r.hashrate_5m_ths).unwrap_or_default(), Column::Hashrate15m => format_hashrate_ths(r.hashrate_15m_ths).unwrap_or_default(), Column::Hashrate24h => format_hashrate_ths(r.hashrate_24h_ths).unwrap_or_default(), // Never displayed as its own column; rendered as a percentage only for // completeness (e.g. a debug/self-test read of the cell). Column::HashrateRel => actual_expected_ratio(r.hashrate_ths, r.expected_ths) .map(|ratio| format!("{:.0}%", ratio * 100.0)) .unwrap_or_default(), Column::Power => { if r.power_w > 0.0 { format_si(r.power_w, "W") } else { String::new() } } // The unit lives in the value now, not the header (round 19 #9), and // is algorithm-aware (J/TH for SHA256 families, J/kSol for Equihash). Column::Efficiency => r .efficiency_display() .map(|(v, u)| format!("{v:.1} {u}")) .unwrap_or_default(), // Per-hashboard chip temps as integers ("77 / 64 / 74"); fall back to // the average (integer) when per-board readings aren't available. Column::ChipTemp => { if r.board_temps.is_empty() { if r.chip_temp_c > 0.0 { format!("{:.0}", r.chip_temp_c) } else { String::new() } } else { // 0.0 == a board with no reading; show "-" so positions align. r.board_temps .iter() .map(|&t| { if t > 0.0 { format!("{t:.0}") } else { "-".to_string() } }) .collect::>() .join(" / ") } } Column::FluidTemp => num(r.fluid_temp_c, 1, " C"), Column::EnvTemp => num(r.env_temp_c, 1, " C"), Column::OutletTemp => num(r.outlet_temp_c, 1, " C"), Column::TargetTemp => r.temp_target_c.map(|v| num(v, 0, " C")).unwrap_or_default(), Column::HotTemp => r.temp_hot_c.map(|v| num(v, 0, " C")).unwrap_or_default(), Column::DangerousTemp => r .temp_dangerous_c .map(|v| num(v, 0, " C")) .unwrap_or_default(), // Per-fan RPM: blank (not "-") when the fan index is absent, so a miner // with fewer fans leaves the extra Fan columns empty and auto-hide can // drop them (round 19 #8). Column::Fan1 => r .fan_rpms .first() .map(|&v| format_fan_rpm(v)) .unwrap_or_default(), Column::Fan2 => r .fan_rpms .get(1) .map(|&v| format_fan_rpm(v)) .unwrap_or_default(), Column::Fan3 => r .fan_rpms .get(2) .map(|&v| format_fan_rpm(v)) .unwrap_or_default(), Column::Fan4 => r .fan_rpms .get(3) .map(|&v| format_fan_rpm(v)) .unwrap_or_default(), Column::FanSpeedPercent => r .fan_speed_percent .map(|v| format!("{v:.0}%")) .unwrap_or_default(), Column::Target => r.tuning_target_label.clone().unwrap_or_default(), Column::PowerLimit => r .power_limit_w .map(|w| format!("{w:.0} W")) .unwrap_or_default(), Column::Accepted => r.accepted_shares.map(|v| v.to_string()).unwrap_or_default(), Column::Rejected => r.rejected_shares.map(|v| v.to_string()).unwrap_or_default(), Column::RejectRatio => r .reject_ratio() .map(|v| format!("{v:.2}%")) .unwrap_or_default(), // Difficulty-weighted work (SI-formatted like Best share); raw stale / // block counts as plain integers (round 19 #10, T2). Column::DiffAccepted => r .difficulty_accepted .map(|v| format_si(v, "")) .unwrap_or_default(), Column::DiffRejected => r .difficulty_rejected .map(|v| format_si(v, "")) .unwrap_or_default(), Column::StaleShares => r.stale_shares.map(|v| v.to_string()).unwrap_or_default(), Column::Blocks => r.found_blocks.map(|v| v.to_string()).unwrap_or_default(), // Per-hashboard hashrate / voltage / frequency, slash-joined like Chip // temp; "-" for a board with no reading, blank when none at all. Column::BoardHashrate => join_board(&r.board_hashrates, |v| { format_hashrate_ths(v).unwrap_or_else(|| "-".to_string()) }), Column::BoardVoltage => join_board(&r.board_voltages, |v| { if v > 0.0 { format!("{v:.2}") } else { "-".into() } }), Column::BoardFrequency => join_board(&r.board_frequencies, |v| { if v > 0.0 { format!("{v:.0}") } else { "-".into() } }), Column::PsuFan => num(r.psu_fan_rpm, 0, ""), Column::PsuVersion => r.psu_version.clone(), Column::PsuSerial => r.psu_serial.clone(), Column::PsuVMin => r .psu_voltage_min_v .map(|v| format!("{v:.2} V")) .unwrap_or_default(), Column::PsuVMax => r .psu_voltage_max_v .map(|v| format!("{v:.2} V")) .unwrap_or_default(), Column::FanCount => count(r.fan_count), Column::ExpectedFans => count(r.expected_fans), Column::TotalChips => combined_count(r.total_chips, r.expected_chips), Column::Firmware => r.firmware.clone(), Column::FwVersion => r.fw_version.clone(), Column::Worker => split_worker(&r.worker).1.to_string(), Column::PoolAccount => split_worker(&r.worker).0.to_string(), Column::PoolUrl => r.pool_url.clone(), Column::Model => r.model.clone(), Column::Brand => r.brand.clone(), Column::Submodel => r.submodel.clone(), Column::Mac => r.mac.clone(), Column::Hostname => r.hostname.clone(), Column::Serial => r.serial.clone(), Column::ApiVersion => r.api_version.clone(), Column::Cpu => r.cpu.clone(), Column::BoardCode => r.board_code.clone(), Column::ChipType => r.chip_type.clone(), Column::HbType => r.hashboard_model.clone(), Column::Algorithm => r.algorithm.clone(), Column::Pic => match r.pic_present { // A per-board PIC MCU is a known Antminer-hashboard property. Show // it only when known; anything unknown (non-Antminer makes, or an // Antminer model we can't classify) is blank, never "?" (round 18 #11). Some(true) => "PIC".to_string(), Some(false) => "noPIC".to_string(), None => String::new(), }, Column::Locked => match r.write_locked { Some(true) => "locked".to_string(), Some(false) => "unlocked".to_string(), None => "?".to_string(), }, // Just the count (blank when none); the full list is the hover // tooltip (see fill_rows). No "errors" word, even for a single one. Column::Error => match r.errors.len() { 0 => String::new(), n => n.to_string(), }, Column::Status => r.status().to_string(), // The Health column renders as component icons (see fill_rows); this // plain-text summary is its filter/sort-fallback text and tooltip base // (round 13 #3). The facet pseudo-columns are never displayed. Column::Health | Column::HealthPower | Column::HealthFans | Column::HealthBoards => { r.health_summary() } Column::Uptime => format_uptime(r.uptime_secs), Column::Light => match r.light_flashing { Some(true) => "on".to_string(), Some(false) => "off".to_string(), None => String::new(), }, Column::OperatingState => r.operating_state.clone(), Column::Tuner => r.tuner_status.clone(), Column::BestShare => r.best_share.map(|v| format_si(v, "")).unwrap_or_default(), Column::SessionBestShare => r .session_best_share .map(|v| format_si(v, "")) .unwrap_or_default(), Column::TuningPercent => r .tuning_percent .map(|v| format!("{v}%")) .unwrap_or_default(), Column::Pool1Url => pool_url(0), Column::Pool1Worker => pool_worker(0), Column::Pool2Url => pool_url(1), Column::Pool2Worker => pool_worker(1), Column::Pool3Url => pool_url(2), Column::Pool3Worker => pool_worker(2), } } /// The column's category, as a (sort-rank, label) pair, for the column /// picker's "Categories" grouping (round 13 #1). Lower rank sorts first; the /// label heads the group. Columns keep their registry order within a group. pub fn category(self) -> (u8, &'static str) { match self { Column::Ip | Column::Model | Column::Brand | Column::Submodel | Column::Mac | Column::Hostname | Column::Serial => (0, "Identity"), Column::Firmware | Column::FwVersion | Column::ApiVersion | Column::Algorithm | Column::Pic | Column::Cpu | Column::BoardCode | Column::ChipType | Column::HbType => (1, "Firmware & board"), Column::Health | Column::HealthPower | Column::HealthFans | Column::HealthBoards | Column::Status | Column::Error | Column::Locked | Column::Light | Column::OperatingState | Column::Tuner => (2, "Health & status"), Column::Hashrate | Column::HashrateRel | Column::Hashrate1m | Column::Hashrate5m | Column::Hashrate15m | Column::Hashrate24h | Column::Power | Column::Efficiency | Column::TuningPercent | Column::BestShare | Column::SessionBestShare | Column::Uptime | Column::Target | Column::PowerLimit | Column::BoardHashrate | Column::BoardVoltage | Column::BoardFrequency => (3, "Performance"), Column::ChipTemp | Column::FluidTemp | Column::EnvTemp | Column::OutletTemp | Column::TargetTemp | Column::HotTemp | Column::DangerousTemp => (4, "Temperature"), Column::Fan1 | Column::Fan2 | Column::Fan3 | Column::Fan4 | Column::PsuFan | Column::FanCount | Column::ExpectedFans | Column::FanSpeedPercent => (5, "Cooling"), Column::TotalChips | Column::PsuVersion | Column::PsuSerial | Column::PsuVMin | Column::PsuVMax => (6, "Hardware"), Column::Worker | Column::PoolAccount | Column::PoolUrl | Column::Pool1Url | Column::Pool1Worker | Column::Pool2Url | Column::Pool2Worker | Column::Pool3Url | Column::Pool3Worker | Column::Accepted | Column::Rejected | Column::RejectRatio | Column::DiffAccepted | Column::DiffRejected | Column::StaleShares | Column::Blocks => (7, "Pools"), } } } pub enum SortKey { Num(f64), Str(String), } /// Text-column filter operators (Excel-style text filters). #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum TextOp { Contains, NotContains, BeginsWith, EndsWith, Equals, } /// Numeric-column filter operators (Excel-style number filters). #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum NumOp { Between, Eq, Ne, Gt, Ge, Lt, Le, } /// One column's active filter. Text columns can filter by a value checklist /// ("is any of") or a text predicate; numeric columns by a numeric predicate. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum ColFilter { Values(HashSet), Text { op: TextOp, needle: String }, Num { op: NumOp, a: f64, b: f64 }, } impl ColFilter { /// Does `r`'s value in `col` satisfy this filter? pub fn matches(&self, col: Column, r: &MinerRow) -> bool { match self { ColFilter::Values(set) => set.contains(&col.cell(r)), ColFilter::Text { op, needle } => { let hay = col.cell(r).to_lowercase(); let n = needle.to_lowercase(); match op { TextOp::Contains => hay.contains(&n), TextOp::NotContains => !hay.contains(&n), TextOp::BeginsWith => hay.starts_with(&n), TextOp::EndsWith => hay.ends_with(&n), TextOp::Equals => hay == n, } } ColFilter::Num { op, a, b } => { let Some(v) = col.num_value(r) else { return false; }; let (a, b) = (*a, *b); match op { NumOp::Between => v >= a.min(b) && v <= a.max(b), NumOp::Eq => v == a, NumOp::Ne => v != a, NumOp::Gt => v > a, NumOp::Ge => v >= a, NumOp::Lt => v < a, NumOp::Le => v <= a, } } } } } /// Display state: order, visibility, sort, filter. #[derive(Clone)] pub struct ViewState { /// Model column order as displayed (Ip is always the first visible column). pub order: Vec, pub visible: HashSet, pub sort: Option<(Column, bool)>, // (column, ascending) /// Active per-column filters (AND across columns); empty = unfiltered. pub filters: HashMap, } impl Default for ViewState { fn default() -> Self { // Display order = Ip, then DEFAULT_VISIBLE in its own order, then every // remaining metric (so the initial columns match the UI-SPEC order rather // than the ALL_COLUMNS registry order). Default sort is by IP ascending. let mut order: Vec = Vec::with_capacity(ALL_COLUMNS.len()); order.push(Column::Ip); order.extend(DEFAULT_VISIBLE); for c in ALL_COLUMNS { if !order.contains(&c) { order.push(c); } } let mut visible: HashSet = DEFAULT_VISIBLE.iter().copied().collect(); visible.insert(Column::Ip); ViewState { order, visible, sort: Some((Column::Ip, true)), filters: HashMap::new(), } } } impl ViewState { pub fn display_columns(&self) -> Vec { // Ip is always shown first; the rest follow `order` filtered by visibility. self.order .iter() .copied() .filter(|c| *c == Column::Ip || self.visible.contains(c)) .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 { 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 } /// Apply a drag-reorder of the visible columns. `new_visible` is the visible /// columns in their new display order; it must be a permutation of the /// currently-visible set with Ip still first. The new order is spliced back /// into `order`, leaving hidden columns in their existing slots, so a /// reorder while some column is hidden never drops or duplicates a column. pub fn apply_visible_reorder(&mut self, new_visible: &[Column]) { if new_visible.first() != Some(&Column::Ip) { return; // Ip is fixed first } let shown: HashSet = new_visible.iter().copied().collect(); if shown.len() != new_visible.len() { return; // duplicates: not a permutation } // `new_visible` is the set of columns the table actually SHOWS in their new // order. That is `display_columns()` normally, but a SUBSET of it when // auto-hide-empty is on (the widget omits the empty columns). Every shown // column must be a real, currently-visible column; columns not in `shown` // (hidden, or hidden-because-empty) keep their slot. Reordering just the // shown subset is what lets drag-reorder work while a column is hidden // (round 18 #12: the old code compared against display_columns() and so // silently rejected every reorder whenever auto-hide-empty hid a column). let reorderable: HashSet = self .order .iter() .copied() .filter(|c| *c == Column::Ip || self.visible.contains(c)) .collect(); if !shown.is_subset(&reorderable) { return; // a non-visible column in the input: ignore } let mut next = new_visible.iter().copied(); self.order = self .order .iter() .map(|&c| { if shown.contains(&c) { next.next().unwrap_or(c) } else { c } }) .collect(); } /// Rows that pass every active filter (AND across columns). pub fn passes_filters(&self, r: &MinerRow) -> bool { self.filters.iter().all(|(col, f)| f.matches(*col, r)) } /// Filtered + sorted rows in display order. pub fn view(&self, rows: &[MinerRow]) -> Vec { let mut idx: Vec = (0..rows.len()) .filter(|&i| self.passes_filters(&rows[i])) .collect(); if let Some((col, asc)) = self.sort { // Decorate-sort-undecorate: compute each row's sort key exactly once // (a string key allocates), not twice per comparison. let mut keyed: Vec<(SortKey, usize)> = idx.iter().map(|&i| (col.sort_key(&rows[i]), i)).collect(); keyed.sort_by(|(ka, _), (kb, _)| { let ord = match (ka, kb) { (SortKey::Num(x), SortKey::Num(y)) => { x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal) } (SortKey::Str(x), SortKey::Str(y)) => x.cmp(y), _ => std::cmp::Ordering::Equal, }; if asc { ord } else { ord.reverse() } }); idx = keyed.into_iter().map(|(_, i)| i).collect(); } idx } } /// The KPIs (UI-SPEC header), derived from the filtered view. Every row is a /// miner that responded to a scan; a responding non-mining miner counts as /// `not_hashing`. pub struct Kpis { pub total: usize, pub hashing: usize, pub slow: usize, pub not_hashing: usize, 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 { let mut k = Kpis { total: view_idx.len(), hashing: 0, slow: 0, not_hashing: 0, 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 // never disagree with a row's own status text. match r.status() { "slow" => k.slow += 1, "paused" => k.paused += 1, "hashing" => k.hashing += 1, _ => k.not_hashing += 1, } 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 } #[cfg(test)] mod tests { //! Offline workflow tests: feed the bench-fleet fixtures (the expected //! hardware output) through the app's transforms and assert the produced //! result. These need no display and run under plain `cargo test`. use super::*; use crate::fixtures::bench_fleet; fn full_view() -> (Vec, ViewState, Vec) { let rows = bench_fleet(); let view = ViewState::default(); let idx = view.view(&rows); (rows, view, idx) } #[test] fn worker_template_expands_scanned_fields() { // Round 14 #7: placeholders are case-insensitive; MAC drops its colons; // nameplate-hr is the rated hashrate in whole TH; unknown keys are kept. let r = MinerRow { ip: "10.2.3.44".into(), serial: "SNXYZ".into(), mac: "AA:BB:CC:11:22:33".into(), brand: "Antminer".into(), model: "S19j Pro".into(), submodel: "".into(), cpu: "AML".into(), board_code: "C76".into(), firmware: "VNish".into(), hostname: "rig-1".into(), expected_ths: 104.0, ..Default::default() }; assert_eq!(r.expand_worker_template("{ip3}x{ip4}"), "3x44"); assert_eq!(r.expand_worker_template("{MAC}"), "AABBCC112233"); assert_eq!(r.expand_worker_template("{mac}"), "AABBCC112233"); assert_eq!(r.expand_worker_template("{nameplate-hr}TH"), "104TH"); assert_eq!( r.expand_worker_template("{brand}-{cpu}-{cb}-{fw}"), "Antminer-AML-C76-VNish" ); assert_eq!(r.expand_worker_template("{serial}"), "SNXYZ"); // Unknown placeholder is left untouched. assert_eq!(r.expand_worker_template("w-{bogus}"), "w-{bogus}"); // A plain worker name with no placeholders is unchanged. assert_eq!(r.expand_worker_template("worker1"), "worker1"); } #[test] fn component_health_maps_states_to_the_four_levels() { // Round 13 #3: power/control/fan/board health map to the grey/red/yellow/ // green four-state model, and the Health column is in the default view. assert!(DEFAULT_VISIBLE.contains(&Column::Health)); // A healthy mining miner: power ok, fans all spinning near each other, // boards ok. let mut r = MinerRow { is_mining: true, power_w: 3200.0, fan_rpms: vec![6000.0, 6100.0, 5900.0, 6000.0], expected_fans: Some(4), board_status: vec![BoardHealth::Ok, BoardHealth::Ok, BoardHealth::Ok], ..Default::default() }; assert_eq!(r.power_health(), CompHealth::Ok); assert_eq!(r.control_health(), CompHealth::Ok); assert!(r.fan_healths().iter().all(|h| *h == CompHealth::Ok)); assert!(r.board_healths().iter().all(|h| *h == CompHealth::Ok)); // A stopped fan is red, a fan at <50% of its fastest sibling is yellow. r.fan_rpms = vec![6000.0, 0.0, 2000.0, 6000.0]; let fans = r.fan_healths(); assert_eq!(fans[0], CompHealth::Ok); assert_eq!(fans[1], CompHealth::Down); // stopped assert_eq!(fans[2], CompHealth::Degraded); // 2000 < 0.5 * 6000 assert_eq!(fans[3], CompHealth::Ok); // A faulted / missing board is red / grey; a slow miner's ok boards go // yellow. r.board_status = vec![BoardHealth::Ok, BoardHealth::Fault, BoardHealth::Missing]; r.slow = true; let boards = r.board_healths(); assert_eq!(boards[0], CompHealth::Degraded); // ok but the miner is slow assert_eq!(boards[1], CompHealth::Down); assert_eq!(boards[2], CompHealth::Unreachable); // A silent miner (no power, no fan, not mining) reads grey for power. let dark = MinerRow::default(); assert_eq!(dark.power_health(), CompHealth::Unreachable); // Healthier miners score higher, so an ascending Health sort puts the // most-broken first. let broken = r.health_score(HealthFacet::Overall); let healthy = MinerRow { is_mining: true, power_w: 3200.0, fan_rpms: vec![6000.0, 6000.0], expected_fans: Some(2), board_status: vec![BoardHealth::Ok, BoardHealth::Ok], ..Default::default() } .health_score(HealthFacet::Overall); assert!( broken < healthy, "broken {broken} should score below healthy {healthy}" ); } #[test] fn faults_attribute_to_the_right_component() { // Round 16 #3: a whole-miner stall zeroes every board's hashrate, but the // per-board fault codes name only some boards. Only the named boards go // red; the un-named board stays green, and the tooltips carry the specific // message on the right board. let fault = |c: FaultComponent, m: &str| Fault { component: c, message: m.to_string(), code: 0, is_error: true, }; let r = MinerRow { is_mining: false, board_status: vec![BoardHealth::Fault, BoardHealth::Fault, BoardHealth::Fault], expected_fans: Some(2), fan_rpms: vec![6000.0, 6000.0], power_w: 3000.0, faults: vec![ fault(FaultComponent::Board(0), "Slot 0 error reading chip id."), fault(FaultComponent::Board(1), "Slot 1 loss of balance error."), ], ..Default::default() }; let boards = r.board_healths(); assert_eq!(boards[0], CompHealth::Down); // named -> red assert_eq!(boards[1], CompHealth::Down); // named -> red assert_eq!(boards[2], CompHealth::Ok); // NOT named -> green, despite Fault status // Tooltip for board 1 carries its specific message (not board 3's). let tips = r.health_tooltips(2, 3); let board_tips = &tips[2 + 2..]; // after power, control, 2 fans assert!(board_tips[0].contains("Slot 0 error reading chip id.")); assert!(!board_tips[2].contains("Slot"), "board 3 has no fault text"); // Round 18 #2/#4b: a PSU fault while the miner is NOT mining is a real // failure (red bolt), and boards keep their own reported state -- a PSU // fault no longer greys them. Faulted boards stay red. let psu = MinerRow { power_w: 40.0, board_status: vec![BoardHealth::Fault, BoardHealth::Fault, BoardHealth::Fault], expected_fans: Some(2), fan_rpms: vec![6000.0, 6000.0], faults: vec![fault(FaultComponent::Power, "Power current error.")], ..Default::default() // is_mining = false }; assert_eq!(psu.power_health(), CompHealth::Down); // fault + not mining -> red assert!(psu.board_healths().iter().all(|h| *h == CompHealth::Down)); // faulted -> red, not grey let ptips = psu.health_tooltips(2, 3); assert!(ptips[0].contains("Power current error.")); // Round 18 #2: the SAME PSU fault while the miner IS mining is a warning // (yellow bolt), and running boards stay GREEN (not grey). Round 18 #4b: // grey is reserved for genuinely-undetected boards. let psu_running = MinerRow { is_mining: true, power_w: 3000.0, board_status: vec![BoardHealth::Ok, BoardHealth::Ok, BoardHealth::Missing], faults: vec![fault(FaultComponent::Power, "Power vout warning.")], ..Default::default() }; assert_eq!(psu_running.power_health(), CompHealth::Degraded); // yellow, not red let rb = psu_running.board_healths(); assert_eq!(rb[0], CompHealth::Ok); // running -> green despite PSU fault assert_eq!(rb[1], CompHealth::Ok); assert_eq!(rb[2], CompHealth::Unreachable); // only the undetected board is grey // Round 18 #12: a genuinely-undetected board that is ALSO named by a board // fault (e.g. a "chain 2 not found" message attributed to Board(2)) must // stay grey ("not detected"), not turn red -- grey vs red is the // detected/undetected distinction. let missing_named = MinerRow { is_mining: true, board_status: vec![BoardHealth::Ok, BoardHealth::Ok, BoardHealth::Missing], faults: vec![fault( FaultComponent::Board(2), "Chain 2 not found, check connection", )], ..Default::default() }; let mb = missing_named.board_healths(); assert_eq!(mb[0], CompHealth::Ok); assert_eq!(mb[1], CompHealth::Ok); assert_eq!( mb[2], CompHealth::Unreachable, "undetected board named by a fault stays grey" ); } #[test] fn warning_fault_degrades_board_to_yellow_not_red() { // Round 21 #1: a board still mining near full hashrate with some failed/ // degraded chips reports a WARNING-severity fault. It must render yellow // (Degraded), not red (Down) -- red is reserved for an error (down board). let warn = |c: FaultComponent, m: &str| Fault { component: c, message: m.to_string(), code: 0, is_error: false, }; let err = |c: FaultComponent, m: &str| Fault { component: c, message: m.to_string(), code: 0, is_error: true, }; // Three mining boards; board 0 has a warning (dead chips), board 2 an error. let r = MinerRow { is_mining: true, board_status: vec![BoardHealth::Ok, BoardHealth::Ok, BoardHealth::Ok], faults: vec![ warn(FaultComponent::Board(0), "Hashboard 1: 10 failed chip(s)"), err(FaultComponent::Board(2), "Hashboard 3: stopped"), ], ..Default::default() }; let b = r.board_healths(); assert_eq!(b[0], CompHealth::Degraded, "warning -> yellow"); assert_eq!(b[1], CompHealth::Ok, "no fault -> green"); assert_eq!(b[2], CompHealth::Down, "error -> red"); // A warning never upgrades a board already red from an error on the same board. let both = MinerRow { is_mining: true, board_status: vec![BoardHealth::Ok], faults: vec![ warn(FaultComponent::Board(0), "degraded chips"), err(FaultComponent::Board(0), "stopped"), ], ..Default::default() }; assert_eq!( both.board_healths()[0], CompHealth::Down, "error wins over warning" ); } #[test] fn equihash_hashrate_units_round18() { // SHA256 shows the TH/s value directly; Equihash shows the Sol/s count // (ths * 1e12) with an SI prefix (round 18 #7). assert_eq!(hashrate_num_for("SHA256", 80.5).as_deref(), Some("80.5")); // 167,764 Sol/s -> SI mantissa+prefix ("168k"); paired with the "Sol/s" unit. assert_eq!( hashrate_num_for("Equihash", 167_764.0 / 1e12).as_deref(), Some("168k") ); assert_eq!(hashrate_num_for("Equihash", 0.0), None); let sha = MinerRow { algorithm: "SHA256".into(), ..Default::default() }; let equi = MinerRow { algorithm: "Equihash".into(), ..Default::default() }; assert_eq!(sha.hashrate_unit(), "TH/s"); assert_eq!(equi.hashrate_unit(), "Sol/s"); } #[test] fn health_tooltips_are_bare_data_round17_r2() { // R2: operating boards show their number counting DOWN (n-1..0) left to // right plus hashrate; fans show just RPM; a fault shows the message with // its code; no "Hashboard N: faulted" prose. let r = MinerRow { is_mining: true, hashboards: Some(3), board_status: vec![BoardHealth::Ok, BoardHealth::Ok, BoardHealth::Fault], board_hashrates: vec![33.5, 34.6, 0.0], expected_fans: Some(2), fan_rpms: vec![4700.0, 4650.0], power_w: 3000.0, faults: vec![Fault { component: FaultComponent::Board(2), message: "Slot 2 chip failure.".to_string(), code: 540, is_error: true, }], ..Default::default() }; let tips = r.health_tooltips(2, 3); // power OK (no V/A yet), control OK, 2 fans, 3 boards. assert_eq!(tips[0], "PSU OK"); assert_eq!(tips[1], "Control board OK"); assert_eq!(tips[2], "4700 rpm"); assert_eq!(tips[3], "4650 rpm"); // Boards count DOWN left->right: leftmost = 2, then 1, then 0. assert!( tips[4].starts_with("2") && tips[4].contains("33.5 TH/s"), "{}", tips[4] ); assert!( tips[5].starts_with("1") && tips[5].contains("34.6 TH/s"), "{}", tips[5] ); // The faulted board shows its error WITH the code, no "Hashboard" prose. assert!( tips[6].contains("Slot 2 chip failure.") && tips[6].contains("540"), "{}", tips[6] ); assert!(!tips[6].to_lowercase().contains("hashboard"), "{}", tips[6]); } #[test] fn kpis_match_expected_hardware_output() { // This does not hardcode fixture counts: it independently recomputes // each expected KPI bucket and sum straight from the rows (via // `status()`) and cross-checks `compute_kpis`'s output against that. let (rows, _v, idx) = full_view(); let k = compute_kpis(&rows, &idx); let mut exp_hashing = 0usize; let mut exp_slow = 0usize; let mut exp_paused = 0usize; let mut exp_not_hashing = 0usize; for &i in &idx { match rows[i].status() { "slow" => exp_slow += 1, "paused" => exp_paused += 1, "hashing" => exp_hashing += 1, "not hashing" => exp_not_hashing += 1, other => panic!("unexpected status: {other}"), } } assert_eq!(k.hashing, exp_hashing, "hashing"); assert_eq!(k.slow, exp_slow, "slow"); assert_eq!(k.paused, exp_paused, "paused"); assert_eq!(k.not_hashing, exp_not_hashing, "not hashing"); let exp_hashrate: f64 = idx.iter().map(|&i| rows[i].hashrate_ths).sum(); let exp_power: f64 = idx.iter().map(|&i| rows[i].power_w).sum(); assert!( (k.total_hashrate_ths - exp_hashrate).abs() < 1e-9, "hashrate {}", k.total_hashrate_ths ); assert!( (k.total_power_w - exp_power).abs() < 1e-9, "power {}", k.total_power_w ); assert_eq!(k.total, k.hashing + k.slow + k.not_hashing + k.paused); } #[test] fn slow_band_classification() { assert!(is_slow(true, 60.0, 200.0)); assert!(!is_slow(true, 90.0, 100.0)); assert!(!is_slow(true, 80.0, 100.0)); assert!(!is_slow(false, 0.0, 200.0)); assert!(!is_slow(true, 1.0, 0.0)); } #[test] fn si_formatting() { assert_eq!(format_si(21300.0, "W"), "21.3 kW"); assert_eq!(format_si(685e12, "H/s"), "685 TH/s"); assert_eq!(format_si(95e12, "H/s"), "95.0 TH/s"); assert_eq!(format_si(6.8e12, "H/s"), "6.8 TH/s"); assert_eq!(format_si(3250.0, "W"), "3.2 kW"); assert_eq!(format_si(0.0, "W"), "0 W"); } #[test] fn cell_formatting_blanks_zeroes() { let rows = bench_fleet(); let s17 = rows.iter().find(|r| r.ip == "10.255.1.112").unwrap(); assert_eq!(Column::Hashrate.cell(s17), ""); assert_eq!(Column::Power.cell(s17), ""); assert_eq!(Column::ChipTemp.cell(s17), ""); assert_eq!(Column::Status.cell(s17), "not hashing"); let s21 = rows.iter().find(|r| r.ip == "10.255.1.149").unwrap(); // Combined hashrate cell: both known -> "/" (no spaces). assert_eq!(Column::Hashrate.cell(s21), "60.0T/200T"); assert_eq!(Column::Power.cell(s21), "1.5 kW"); assert_eq!(Column::Status.cell(s21), "slow"); } #[test] fn default_view_sorts_by_ip_ascending() { // Fixture count/IPs are not hardcoded here (round-6 fixtures are being // extended concurrently): recompute the expected numeric-IP order // straight from the rows instead. let (rows, _v, idx) = full_view(); let ips: Vec = idx.iter().map(|&i| rows[i].ip.clone()).collect(); assert_eq!(ips.len(), rows.len(), "the default view has no filters"); let mut expected: Vec = rows.iter().map(|r| r.ip.clone()).collect(); expected.sort_by_key(|ip| ip_to_u32(ip)); assert_eq!( ips, expected, "default view should be IP-ascending (numeric)" ); } #[test] fn sort_by_hashrate() { let rows = bench_fleet(); let mut view = ViewState::default(); view.sort = Some((Column::Hashrate, false)); let idx = view.view(&rows); assert_eq!(rows[idx[0]].ip, "10.255.1.167"); assert!(rows[idx[0]].hashrate_ths >= rows[idx[1]].hashrate_ths); view.sort = Some((Column::Hashrate, true)); let idx = view.view(&rows); assert_eq!(rows[idx[0]].hashrate_ths, 0.0); } #[test] fn filter_by_status_slow() { let rows = bench_fleet(); let mut view = ViewState::default(); let mut allowed = HashSet::new(); allowed.insert("slow".to_string()); view.filters .insert(Column::Status, ColFilter::Values(allowed)); let idx = view.view(&rows); assert_eq!(idx.len(), 1); assert_eq!(rows[idx[0]].ip, "10.255.1.149"); } #[test] fn default_visible_is_the_ui_spec_set() { let view = ViewState::default(); let disp = view.display_columns(); // Ip first, then the 8 default columns in order. assert_eq!(disp[0], Column::Ip); assert_eq!(&disp[1..], &DEFAULT_VISIBLE[..]); // hidden-by-default metrics are still selectable (present in order). assert!(view.order.contains(&Column::Mac)); assert!(view.order.contains(&Column::Pool2Url)); assert!(!view.visible.contains(&Column::Mac)); } #[test] fn hiding_a_column_shifts_display_columns() { let mut view = ViewState::default(); let before = view.display_columns(); assert!(before.contains(&Column::Power)); view.visible.remove(&Column::Power); let after = view.display_columns(); assert!(!after.contains(&Column::Power)); assert_eq!(after[0], Column::Ip); assert_eq!(after.len(), before.len() - 1); let hr = after.iter().position(|c| *c == Column::Hashrate).unwrap(); assert_eq!(after[hr + 1], Column::ChipTemp); } #[test] fn showing_a_hidden_metric_adds_a_column() { let mut view = ViewState::default(); assert!(!view.display_columns().contains(&Column::Uptime)); view.visible.insert(Column::Uptime); assert!(view.display_columns().contains(&Column::Uptime)); } #[test] fn reorder_with_hidden_column_keeps_all_columns() { let mut view = ViewState::default(); view.visible.remove(&Column::Power); // Swap Hashrate and ChipTemp in the visible display order (order-agnostic: // find them by identity rather than by a fixed index). let mut vis = view.display_columns(); let hr0 = vis.iter().position(|c| *c == Column::Hashrate).unwrap(); let ct0 = vis.iter().position(|c| *c == Column::ChipTemp).unwrap(); vis.swap(hr0, ct0); view.apply_visible_reorder(&vis); assert!( view.order.contains(&Column::Power), "hidden column dropped!" ); assert_eq!(view.order.len(), ALL_COLUMNS.len()); let set: HashSet = view.order.iter().copied().collect(); assert_eq!(set.len(), ALL_COLUMNS.len()); let disp = view.display_columns(); let hr = disp.iter().position(|c| *c == Column::Hashrate).unwrap(); let ct = disp.iter().position(|c| *c == Column::ChipTemp).unwrap(); assert!(ct < hr, "reorder not applied"); assert_eq!(view.order[0], Column::Ip); } #[test] fn reorder_rejects_non_permutation() { let mut view = ViewState::default(); let before = view.order.clone(); // Ip not first -> ignored view.apply_visible_reorder(&[Column::Hashrate, Column::Ip, Column::Power]); assert_eq!(view.order, before); } /// Build a large synthetic fleet for benchmarking the transform pipeline. #[cfg(test)] fn synthetic_fleet(n: u32) -> Vec { (0..n) .map(|i| { let mut r = MinerRow { ip: format!("10.{}.{}.{}", (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff), hashrate_ths: (i % 200) as f64 + 0.5, expected_ths: 200.0, power_w: 3000.0 + (i % 500) as f64, chip_temp_c: 55.0 + (i % 25) as f64, fan_rpms: vec![4000.0 + (i % 900) as f64], is_mining: i % 7 != 0, model: format!("Model-{}", i % 12), firmware: format!("fw-{}", i % 6), worker: format!("blueflare.{i}"), ..Default::default() }; r.slow = is_slow(r.is_mining, r.hashrate_ths, r.expected_ths); r }) .collect() } /// Microbenchmark: the filter+sort view pipeline over a large fleet. Run with /// cargo test -p alkane-gui --release -- --ignored --nocapture bench_ /// Acts as a perf-regression gate in CI. #[test] #[ignore] fn bench_view_pipeline() { use std::time::Instant; let rows = synthetic_fleet(5000); let mut view = ViewState::default(); view.sort = Some((Column::Hashrate, false)); let iters = 200u32; let t = Instant::now(); let mut sink = 0usize; for _ in 0..iters { sink += view.view(&rows).len(); } let per = t.elapsed() / iters; println!( "bench_view_pipeline: {} rows, filter+sort view() = {:?}/op (sink={sink})", rows.len(), per ); assert!( per.as_millis() < 50, "view() regressed: {per:?}/op for 5000 rows" ); } /// Microbenchmark: KPI aggregation + cell rendering over a large fleet. #[test] #[ignore] fn bench_render_cells() { use std::time::Instant; let rows = synthetic_fleet(5000); let view = ViewState::default(); let idx = view.view(&rows); let cols = view.display_columns(); let iters = 50u32; let t = Instant::now(); let mut bytes = 0usize; for _ in 0..iters { let _k = compute_kpis(&rows, &idx); for &ri in &idx { for c in &cols { bytes += c.cell(&rows[ri]).len(); } } } let per = t.elapsed() / iters; println!( "bench_render_cells: {} rows x {} cols = {:?}/full-render (bytes={bytes})", rows.len(), cols.len(), per ); assert!(per.as_millis() < 100, "cell rendering regressed: {per:?}"); } /// Microbenchmark: component health scores and operator-facing diagnostics /// recomputed when scan results refresh the table. #[test] #[ignore] fn bench_health_diagnostics() { use std::hint::black_box; use std::time::Instant; let rows = bench_fleet(); let iters = 1000u32; let start = Instant::now(); let mut sink = 0usize; for _ in 0..iters { for row in &rows { for facet in [ HealthFacet::Overall, HealthFacet::Power, HealthFacet::Fans, HealthFacet::Boards, ] { sink += black_box(row.health_score(facet)) as usize; } sink += row.health_summary().len(); sink += row .health_tooltips(4, 3) .iter() .map(String::len) .sum::(); } } black_box(sink); let per = start.elapsed() / iters; println!( "bench_health_diagnostics: {} rows = {:?}/refresh", rows.len(), per ); assert!( per.as_millis() < 20, "health diagnostics regressed: {per:?}/refresh" ); } #[test] fn selection_survives_upsert() { let mut rows = bench_fleet(); rows[1].selected = true; let ip = rows[1].ip.clone(); let mut update = bench_fleet()[1].clone(); update.hashrate_ths = 12.3; let new = update.upsert_into(&mut rows); assert!(!new, "same IP is an update, not an insert"); let r = rows.iter().find(|r| r.ip == ip).unwrap(); assert!(r.selected, "selection preserved across upsert"); assert_eq!(r.hashrate_ths, 12.3, "data updated"); } // ---- harness-driven additions (correctness + coverage) ---- #[test] fn format_si_handles_zero_negative_and_nonfinite() { assert_eq!(format_si(0.0, "W"), "0 W"); assert_eq!(format_si(-5.0, "W"), "0 W"); assert_eq!(format_si(f64::NAN, "W"), "0 W"); assert_eq!(format_si(f64::INFINITY, "H/s"), "0 H/s"); } #[test] fn format_si_rolls_over_at_rounding_boundary() { // A mantissa that rounds up to 1000 must advance the prefix, never print // a 4-digit number (spec: at most 2 digits + 1 decimal after the prefix). assert_eq!(format_si(999.9, "W"), "1.0 kW"); assert_eq!(format_si(999_990.0, "W"), "1.0 MW"); assert_eq!(format_si(1000.0, "W"), "1.0 kW"); // [99.95, 100) rounds to 100 and drops the decimal (>=100 rule). assert_eq!(format_si(99.95, "W"), "100 W"); assert_eq!(format_si(45.6, "W"), "45.6 W"); assert_eq!(format_si(250.0, "W"), "250 W"); } #[test] fn format_uptime_boundaries() { assert_eq!(format_uptime(0), ""); assert_eq!(format_uptime(59), "59s"); assert_eq!(format_uptime(60), "1m"); assert_eq!(format_uptime(3599), "59m"); assert_eq!(format_uptime(3600), "1h 0m"); assert_eq!(format_uptime(86_399), "23h 59m"); assert_eq!(format_uptime(86_400), "1d 0h"); assert_eq!(format_uptime(90_061), "1d 1h"); } #[test] fn pic_locked_error_columns_render() { // PIC: known -> PIC/noPIC; anything unknown -> blank, never "?" (round 18 #11). let am = |pic| MinerRow { brand: "Antminer".into(), pic_present: pic, ..Default::default() }; assert_eq!(Column::Pic.cell(&am(Some(true))), "PIC"); assert_eq!(Column::Pic.cell(&am(Some(false))), "noPIC"); assert_eq!(Column::Pic.cell(&am(None)), ""); // unknown Antminer model -> blank // Non-Antminer makes: PIC has no meaning -> blank. let wm = MinerRow { brand: "WhatsMiner".into(), pic_present: None, ..Default::default() }; assert_eq!(Column::Pic.cell(&wm), ""); // Access column. let locked = MinerRow { write_locked: Some(true), ..Default::default() }; let unlocked = MinerRow { write_locked: Some(false), ..Default::default() }; assert_eq!(Column::Locked.cell(&locked), "locked"); assert_eq!(Column::Locked.cell(&unlocked), "unlocked"); assert_eq!(Column::Locked.cell(&MinerRow::default()), "?"); // Error column shows only the count (blank when none), even for one. let none = MinerRow { errors: vec![], ..Default::default() }; let one = MinerRow { errors: vec!["boom".into()], ..Default::default() }; let many = MinerRow { errors: vec!["a".into(), "b".into(), "c".into()], ..Default::default() }; assert_eq!(Column::Error.cell(&none), ""); assert_eq!(Column::Error.cell(&one), "1"); assert_eq!(Column::Error.cell(&many), "3"); } #[test] fn caps_any_control() { assert!(!MinerCaps::default().any_control(), "no caps -> view-only"); assert!(MinerCaps { restart: true, ..Default::default() } .any_control()); assert!(MinerCaps { firmware_flash: true, ..Default::default() } .any_control()); } #[test] fn ip_column_sorts_numerically() { // A plain string sort puts "10.255.1.10" before "10.255.1.2"; the IP // column must order by numeric value instead. let rows = vec![ MinerRow { ip: "10.255.1.10".into(), ..Default::default() }, MinerRow { ip: "10.255.1.2".into(), ..Default::default() }, MinerRow { ip: "10.255.1.112".into(), ..Default::default() }, MinerRow { ip: "10.255.1.9".into(), ..Default::default() }, ]; let idx = ViewState::default().view(&rows); // default = Ip ascending let order: Vec<&str> = idx.iter().map(|&i| rows[i].ip.as_str()).collect(); assert_eq!( order, ["10.255.1.2", "10.255.1.9", "10.255.1.10", "10.255.1.112"] ); } #[test] fn upsert_into_new_ip_inserts_and_returns_true() { let mut rows = bench_fleet(); let n0 = rows.len(); let fresh = MinerRow { ip: "10.9.9.9".into(), ..Default::default() }; let is_new = fresh.upsert_into(&mut rows); assert!(is_new, "a never-seen IP is an insert"); assert_eq!(rows.len(), n0 + 1); assert!(rows.iter().any(|r| r.ip == "10.9.9.9")); } #[test] fn cell_light_three_states() { let on = MinerRow { light_flashing: Some(true), ..Default::default() }; let off = MinerRow { light_flashing: Some(false), ..Default::default() }; let unknown = MinerRow { light_flashing: None, ..Default::default() }; assert_eq!(Column::Light.cell(&on), "on"); assert_eq!(Column::Light.cell(&off), "off"); assert_eq!(Column::Light.cell(&unknown), ""); } #[test] fn cell_pool_slots_including_out_of_range() { let r = MinerRow { pools: vec![ ("stratum+tcp://a:1".into(), "wA".into()), ("stratum+tcp://b:2".into(), "wB".into()), ], ..Default::default() }; assert_eq!(Column::Pool1Url.cell(&r), "stratum+tcp://a:1"); assert_eq!(Column::Pool1Worker.cell(&r), "wA"); assert_eq!(Column::Pool2Url.cell(&r), "stratum+tcp://b:2"); assert_eq!(Column::Pool2Worker.cell(&r), "wB"); // Third pool is unconfigured -> blank, not a panic. assert_eq!(Column::Pool3Url.cell(&r), ""); assert_eq!(Column::Pool3Worker.cell(&r), ""); } #[test] fn passes_filters_ands_across_columns() { let rows = vec![ MinerRow { ip: "10.0.0.1".into(), is_mining: true, model: "A".into(), ..Default::default() }, MinerRow { ip: "10.0.0.2".into(), is_mining: true, model: "B".into(), ..Default::default() }, MinerRow { ip: "10.0.0.3".into(), is_mining: false, model: "A".into(), ..Default::default() }, ]; let mut view = ViewState::default(); view.filters.insert( Column::Status, ColFilter::Values(HashSet::from(["hashing".to_string()])), ); view.filters.insert( Column::Model, ColFilter::Values(HashSet::from(["A".to_string()])), ); let idx = view.view(&rows); assert_eq!(idx.len(), 1, "only the hashing AND model-A row passes"); assert_eq!(rows[idx[0]].ip, "10.0.0.1"); } #[test] fn passes_filters_ors_within_one_column() { let rows = bench_fleet(); // Not hardcoded (fixture composition is changing concurrently): // recompute the expected count straight from the rows' own status(). let expected = rows .iter() .filter(|r| matches!(r.status(), "slow" | "not hashing")) .count(); let mut view = ViewState::default(); view.filters.insert( Column::Status, ColFilter::Values(HashSet::from([ "slow".to_string(), "not hashing".to_string(), ])), ); let idx = view.view(&rows); assert_eq!(idx.len(), expected); } #[test] fn apply_visible_reorder_rejects_non_permutation_same_length() { let mut view = ViewState::default(); let before = view.order.clone(); let hidden = *view .order .iter() .find(|c| **c != Column::Ip && !view.visible.contains(c)) .expect("a hidden column exists by default"); let mut disp = view.display_columns(); // Ip first, correct length disp[1] = hidden; // same length + Ip first, but no longer a permutation view.apply_visible_reorder(&disp); assert_eq!( view.order, before, "a same-length non-permutation must be ignored" ); } #[test] fn apply_visible_reorder_accepts_a_shown_subset() { // Auto-hide-empty shows only a subset of the visible columns; dragging // within that subset must be applied, not silently rejected (round 18 #12). let mut view = ViewState::default(); let disp = view.display_columns(); assert!(disp.len() >= 4, "default view has several visible columns"); // Pretend disp[2] is empty and therefore hidden by the widget. let dropped = disp[2]; let mut shown: Vec = disp.iter().copied().filter(|&c| c != dropped).collect(); shown.swap(1, 2); // reorder two columns of the shown subset let before_set: HashSet = view.order.iter().copied().collect(); view.apply_visible_reorder(&shown); assert_ne!( view.display_columns().iter().copied().collect::>(), disp, "a valid subset reorder must change the display order" ); // No column lost or duplicated; Ip still first; the hidden column kept its slot. assert_eq!( view.order.iter().copied().collect::>(), before_set ); assert_eq!(view.order.len(), before_set.len()); assert_eq!(view.display_columns().first(), Some(&Column::Ip)); assert_eq!(view.order.iter().filter(|&&c| c == dropped).count(), 1); } /// Microbenchmark: the DEFAULT view (Ip ascending) at 5000 rows. The existing /// bench_view_pipeline overrides sort to Hashrate, so it never exercised the /// default path (previously a lexical string sort). #[test] #[ignore] fn bench_view_pipeline_default_sort() { use std::time::Instant; let rows = synthetic_fleet(5000); let view = ViewState::default(); let iters = 200u32; let t = Instant::now(); let mut sink = 0usize; for _ in 0..iters { sink += view.view(&rows).len(); } let per = t.elapsed() / iters; println!( "bench_view_pipeline_default_sort: {:?}/op (sink={sink})", per ); assert!( per.as_millis() < 60, "default (Ip) sort regressed: {per:?}/op" ); } /// Microbenchmark: sort by every column once, at 5000 rows. Guards the /// decorate-sort-undecorate path (string columns must not re-allocate keys /// per comparison). #[test] #[ignore] fn bench_sort_by_each_column() { use std::time::Instant; let rows = synthetic_fleet(5000); let iters = 10u32; let mut worst = std::time::Duration::ZERO; for &col in ALL_COLUMNS.iter() { let mut view = ViewState::default(); view.sort = Some((col, false)); let t = Instant::now(); let mut sink = 0usize; for _ in 0..iters { sink += view.view(&rows).len(); } let per = t.elapsed() / iters; if per > worst { worst = per; } assert!( per.as_millis() < 120, "{col:?} sort regressed: {per:?}/op (sink={sink})" ); } println!("bench_sort_by_each_column: worst column = {:?}/op", worst); } /// Microbenchmark: filtered view (one selective predicate) at 5000 rows. #[test] #[ignore] fn bench_view_pipeline_with_filter() { use std::time::Instant; let rows = synthetic_fleet(5000); let mut view = ViewState::default(); view.filters.insert( Column::Model, ColFilter::Values(HashSet::from(["Model-3".to_string()])), ); view.sort = Some((Column::Hashrate, false)); let iters = 200u32; let t = Instant::now(); let mut sink = 0usize; for _ in 0..iters { sink += view.view(&rows).len(); } let per = t.elapsed() / iters; println!( "bench_view_pipeline_with_filter: {sink} avg matches, {:?}/op", per ); assert!( per.as_millis() < 60, "filtered view() regressed: {per:?}/op" ); } /// Microbenchmark: cold-start fleet population via upsert_into (the O(n) scan /// per insert; documents the quadratic worst case). #[test] #[ignore] fn bench_upsert_cold_start_population() { use std::time::Instant; let n = 3000u32; let fresh = synthetic_fleet(n); let t = Instant::now(); let mut rows: Vec = Vec::new(); for r in fresh { r.upsert_into(&mut rows); } let elapsed = t.elapsed(); println!( "bench_upsert_cold_start_population: {n} rows cold-start = {:?}", elapsed ); assert!( elapsed.as_millis() < 2000, "cold-start upsert regressed: {elapsed:?} for {n} rows" ); } // ---- Excel-style column filters (round 3) ---- #[test] fn text_filter_operators_are_case_insensitive() { let r = MinerRow { firmware: "WMOS H616".into(), ..Default::default() }; let c = Column::Firmware; let t = |op, needle: &str| { ColFilter::Text { op, needle: needle.into(), } .matches(c, &r) }; assert!(t(TextOp::Contains, "wmos")); assert!(!t(TextOp::Contains, "vnish")); assert!(!t(TextOp::NotContains, "wmos")); assert!(t(TextOp::NotContains, "vnish")); assert!(t(TextOp::BeginsWith, "WMOS")); assert!(!t(TextOp::BeginsWith, "616")); assert!(t(TextOp::EndsWith, "h616")); assert!(t(TextOp::Equals, "wmos h616")); assert!(!t(TextOp::Equals, "wmos")); } #[test] fn numeric_filter_operators() { let r = MinerRow { hashrate_ths: 100.0, hashrate_known: true, is_mining: true, ..Default::default() }; let c = Column::Hashrate; let n = |op, a: f64, b: f64| ColFilter::Num { op, a, b }.matches(c, &r); assert!(n(NumOp::Gt, 50.0, 0.0)); assert!(!n(NumOp::Gt, 150.0, 0.0)); assert!(n(NumOp::Ge, 100.0, 0.0)); assert!(n(NumOp::Lt, 150.0, 0.0)); assert!(n(NumOp::Le, 100.0, 0.0)); assert!(n(NumOp::Eq, 100.0, 0.0)); assert!(n(NumOp::Ne, 99.0, 0.0)); assert!(n(NumOp::Between, 90.0, 110.0)); assert!(n(NumOp::Between, 110.0, 90.0), "bounds are order-agnostic"); assert!(!n(NumOp::Between, 0.0, 50.0)); } #[test] fn num_value_none_for_text_and_blank() { let r = MinerRow { firmware: "x".into(), efficiency: 0.0, ..Default::default() }; assert_eq!(Column::Firmware.num_value(&r), None, "text column"); assert_eq!(Column::Ip.num_value(&r), None, "IP is text, not numeric"); assert_eq!( Column::Efficiency.num_value(&r), None, "blank numeric -> None" ); let r2 = MinerRow { hashrate_ths: 42.0, hashrate_known: true, ..Default::default() }; assert_eq!(Column::Hashrate.num_value(&r2), Some(42.0)); } #[test] fn caps_intersection_is_the_common_actions() { let full = MinerCaps { fault_light: true, restart: true, pause: true, resume: true, power_limit: true, tuning: true, hashrate_target: true, supports_presets: true, firmware_flash: true, pools: true, timezone: true, change_password: true, factory_reset: true, }; let idle = MinerCaps { fault_light: true, restart: true, ..Default::default() }; // Two full miners keep every action. assert_eq!(MinerCaps::intersect_all([full, full]), full); // A full + idle mix keeps only what both support. assert_eq!(MinerCaps::intersect_all([full, idle]), idle); // A single miner's caps are its own. assert_eq!(MinerCaps::intersect_all([full]), full); // Empty selection -> nothing common. assert_eq!(MinerCaps::intersect_all([]), MinerCaps::default()); assert!(MinerCaps::default().is_empty()); assert!(!full.is_empty()); } #[test] fn numeric_filter_excludes_blank_cells() { // A blank-displaying value-type cell (absent reading stored as 0.0) must // not match a numeric predicate -- it has no value to compare. let blank = MinerRow { hashrate_ths: 0.0, chip_temp_c: 0.0, power_w: 0.0, is_mining: false, ..Default::default() }; assert_eq!(Column::Hashrate.num_value(&blank), None); assert_eq!(Column::ChipTemp.num_value(&blank), None); assert_eq!(Column::Power.num_value(&blank), None); // "<= 50" and "<= 1000" must NOT match a miner with no temp / power. assert!(!ColFilter::Num { op: NumOp::Le, a: 50.0, b: 0.0 } .matches(Column::ChipTemp, &blank)); assert!(!ColFilter::Num { op: NumOp::Lt, a: 1000.0, b: 0.0 } .matches(Column::Power, &blank)); // A real reading still matches. let live = MinerRow { chip_temp_c: 45.0, is_mining: true, ..Default::default() }; assert!(ColFilter::Num { op: NumOp::Le, a: 50.0, b: 0.0 } .matches(Column::ChipTemp, &live)); } // ---- round 6: offline/paused rows, combined columns, fan RPMs, segments ---- #[test] fn format_fan_rpm_boundaries() { assert_eq!(format_fan_rpm(0.0), "-"); assert_eq!(format_fan_rpm(-100.0), "-"); assert_eq!(format_fan_rpm(f64::NAN), "-"); assert_eq!(format_fan_rpm(f64::INFINITY), "-"); assert_eq!(format_fan_rpm(950.0), "950"); assert_eq!(format_fan_rpm(4200.0), "4.2k"); // Shares format_si's rounding-rollover and >=100 rules. assert_eq!(format_fan_rpm(99.95), "100"); assert_eq!(format_fan_rpm(999.9), "1.0k"); } #[test] fn combined_cell_all_four_cases() { let neither = MinerRow::default(); assert_eq!(Column::Hashrate.cell(&neither), "", "both unknown -> blank"); assert_eq!(Column::TotalChips.cell(&neither), ""); let actual_only = MinerRow { hashrate_ths: 60.0, hashrate_known: true, total_chips: Some(210), ..Default::default() }; assert_eq!( Column::Hashrate.cell(&actual_only), "60.0T", "only actual -> bare actual" ); assert_eq!(Column::TotalChips.cell(&actual_only), "210"); let expected_only = MinerRow { expected_ths: 200.0, expected_chips: Some(228), ..Default::default() }; assert_eq!( Column::Hashrate.cell(&expected_only), "-/200T", "only expected (actual unreadable) -> '-/'" ); assert_eq!(Column::TotalChips.cell(&expected_only), "- / 228"); // A reported zero is a real reading -> "0.00T", never the dash. The dash // (expected_only above) is reserved for an unreadable actual. let reported_zero = MinerRow { hashrate_ths: 0.0, hashrate_known: true, expected_ths: 200.0, ..Default::default() }; assert_eq!( Column::Hashrate.cell(&reported_zero), "0.00T/200T", "reported 0 -> 0.00T, not a dash" ); let reported_zero_no_expected = MinerRow { hashrate_ths: 0.0, hashrate_known: true, ..Default::default() }; assert_eq!(Column::Hashrate.cell(&reported_zero_no_expected), "0.00T"); let both = MinerRow { hashrate_ths: 60.0, hashrate_known: true, expected_ths: 200.0, total_chips: Some(190), expected_chips: Some(228), ..Default::default() }; assert_eq!( Column::Hashrate.cell(&both), "60.0T/200T", "both known -> '/'" ); assert_eq!(Column::TotalChips.cell(&both), "190 / 228"); } #[test] fn num_value_none_when_only_expected_known() { // A numeric filter must never match a row that only has an expected // value -- there is no actual reading to compare. let expected_only = MinerRow { expected_ths: 200.0, expected_chips: Some(228), ..Default::default() }; assert_eq!(Column::Hashrate.num_value(&expected_only), None); assert_eq!(Column::TotalChips.num_value(&expected_only), None); let both = MinerRow { hashrate_ths: 60.0, hashrate_known: true, expected_ths: 200.0, total_chips: Some(190), expected_chips: Some(228), ..Default::default() }; assert_eq!(Column::Hashrate.num_value(&both), Some(60.0)); assert_eq!(Column::TotalChips.num_value(&both), Some(190.0)); } #[test] fn per_fan_columns_show_each_fan_and_hide_when_absent() { // Round 19 #8: the old slash-joined Cooling column is now one column per fan. let r = MinerRow { fan_rpms: vec![4200.0, 3990.0, 4500.0], ..Default::default() }; assert_eq!(Column::Fan1.cell(&r), "4.2k"); assert_eq!(Column::Fan2.cell(&r), "4.0k"); assert_eq!(Column::Fan3.cell(&r), "4.5k"); // A miner with only 3 fans leaves Fan 4 blank (so auto-hide can drop it). assert_eq!(Column::Fan4.cell(&r), ""); assert_eq!(Column::Fan1.num_value(&r), Some(4200.0)); assert_eq!(Column::Fan4.num_value(&r), None); let none = MinerRow::default(); assert_eq!(Column::Fan1.cell(&none), ""); assert_eq!(Column::Fan1.num_value(&none), None); } #[test] fn segments_round_trip_and_plain_passthrough() { let segs = vec![ (Some((255u8, 0u8, 0u8)), "Err".to_string()), (None, ": offline".to_string()), ]; let encoded = encode_segments(&segs); assert_eq!(encoded, "FF0000\u{1e}Err\u{1f}\u{1e}: offline"); assert_eq!(decode_segments_plain(&encoded), "Err: offline"); // A plain string with no segment markers round-trips unchanged. assert_eq!(decode_segments_plain("10.255.1.9"), "10.255.1.9"); assert_eq!(decode_segments_plain(""), ""); } #[test] fn actual_expected_ratio_handles_unknown_expected() { // 50/200 = 0.25 is exactly representable, so this is a safe exact // comparison (unlike e.g. 60/200, whose nearest-double result is not // guaranteed to bit-match a decimal literal). assert_eq!(actual_expected_ratio(50.0, 200.0), Some(0.25)); assert_eq!(actual_expected_ratio(60.0, 0.0), None); assert_eq!(actual_expected_ratio(0.0, 0.0), None); } #[test] fn status_precedence() { // A plain default row is a reachable, non-mining miner. let default_row = MinerRow { ..Default::default() }; assert_eq!(default_row.status(), "not hashing"); let paused = MinerRow { paused: true, ..Default::default() }; assert_eq!(paused.status(), "paused"); let hashing = MinerRow { is_mining: true, ..Default::default() }; assert_eq!(hashing.status(), "hashing"); // slow outranks paused (and hashing). let slow_and_paused = MinerRow { slow: true, paused: true, is_mining: true, ..Default::default() }; assert_eq!(slow_and_paused.status(), "slow"); // paused outranks hashing. let paused_but_mining = MinerRow { paused: true, is_mining: true, ..Default::default() }; assert_eq!(paused_but_mining.status(), "paused"); } #[test] fn is_paused_detection() { assert!(is_paused("Paused", false)); assert!(is_paused("PAUSED (manual)", false)); // Intentional halts other firmwares report: VNish "Stopped" (miner_state // "stopped"), Braiins "Suspended", a "Stopping" transition (round 19 #19 / // 10.4.1.122 read as broken before this). assert!( is_paused("Stopped", false), "an operator-stopped miner is paused, not broken" ); assert!(is_paused("Stopping", false)); assert!(is_paused("Suspended", false)); assert!( !is_paused("Stopped", true), "mining overrides a stale 'stopped' state string" ); assert!(!is_paused("Mining", false)); assert!( !is_paused("Error", false), "a failure is broken, not paused" ); assert!( !is_paused("Idling", false), "plain idle is not an explicit halt" ); assert!(!is_paused("", false)); } #[test] fn kpis_bucket_by_status_not_raw_flags() { // compute_kpis must bucket by status()'s precedence, so a row's KPI // bucket can never disagree with its status text. let rows = vec![ MinerRow { slow: true, paused: true, is_mining: true, ..Default::default() }, // slow wins MinerRow { paused: true, is_mining: true, ..Default::default() }, // paused over hashing MinerRow { is_mining: true, ..Default::default() }, // hashing MinerRow { ..Default::default() }, // not hashing ]; let idx: Vec = (0..rows.len()).collect(); let k = compute_kpis(&rows, &idx); assert_eq!(k.slow, 1); assert_eq!(k.paused, 1, "paused outranks the mining flag"); assert_eq!(k.hashing, 1); assert_eq!(k.not_hashing, 1); assert_eq!(k.total, 4); } #[test] fn flash_confirmed_requires_exact_word() { assert!(flash_confirmed("FLASH")); assert!( flash_confirmed(" FLASH "), "surrounding whitespace is trimmed" ); assert!(!flash_confirmed("flash"), "case-sensitive"); assert!(!flash_confirmed("Flash")); assert!(!flash_confirmed("FLASHING"), "not a prefix match"); assert!(!flash_confirmed("FLASH NOW")); assert!(!flash_confirmed("")); } }