Compare commits

...
7 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 95b8428c12 Round C G3: named firmware presets (LuxOS) end to end
The flagship structured-tuning parity item: list and select a firmware's named
profiles/presets, not just map a watts number onto one.

Backend (vendored asic-rs, patch 0022): LuxOS now implements SupportsPresets
(get_presets reads the live `profiles` RPC) and a real SupportsTuningConfig
(set_tuning_config routes Preset(name) -> profileset, Power -> set_power_limit).
Unit-tested (parse_profiles_to_presets); verified live-read on two production
LuxOS S19j Pro (10.4.1.60/.67). VNish already exposed presets.

GUI: MinerCaps.supports_presets + MinerRow.presets (read live at scan time for
preset-capable miners; ~1 RPC per such miner per 300 s rescan). New "Set
profile..." right-click item opens a selector populated from the profiles
common to the whole selection (so the chosen name is valid on every target),
applied via the new ConfigAction::Preset. Offline fixtures seed demo presets.

CLI: `miner_probe presets <ip>` (list) and `setpreset <ip> <name>` (select).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 17:34:26 -06:00
noahandClaude Opus 4.8 a7ed34b8e4 gui: pool "+" "Add new..." opens a preset manager window (round 18 #8b)
The pool-field "+" menu previously offered a one-shot "Add new" (append
the current box value) plus a "Remove saved value" submenu. Both are now
replaced by "Add new...", which opens a small manager window: a multiline
editable list of all saved values for that field, seeded with the current
box value as the last line. Save rewrites the whole saved list at once.

- pool_prefs: new save_all() rewrites a field's saved list; the trim /
  drop-empties / drop-presets / de-dup step is factored into a pure
  dedupe_saved() with unit tests. Removed the now-unused add_saved /
  remove_saved.
- ui: build_pool_presets_dialog + apply_pool_presets, wired to
  ID_POOL_PRESETS_SAVE/CANCEL; "+" menu shows "Add new..." and no longer
  builds the remove submenu; ID_POOL_MENU_REMOVE_BASE dropped.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 17:10:45 -06:00
noahandClaude Opus 4.8 b839e9012d gui: default column widths fit contents, capped (round 18 #10)
Columns previously always opened at generous fixed defaults, wasting
horizontal space. Now, the first time the table is populated after a
(re)build, each column is sized to the smaller of its content-fit width
(wxCOL_WIDTH_AUTOSIZE, floored at 24px) and its configured default (the
cap). Done once per rebuild via a new columns_autosized latch, so a
user's later manual resize is preserved -- scan-update refills skip it.

New bridge: wxbr_dvlc_autosize_col_capped (SetWidth AUTOSIZE, read back,
floor, clamp to cap, SetWidth) + Widget::dvlc_autosize_col_capped.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 17:01:25 -06:00
noahandClaude Opus 4.8 d378a484d6 ui: attribute hashboard faults + pools dialog + widths (round 18 #5/#8a/#8c)
- #5 Antminer-hardware firmwares (stock/VNish/Braiins/LuxOS) report faults with no
  component, so a real per-board fault landed on the control-board tooltip instead
  of the board it names. messages_to_faults now recovers the board index from the
  self-describing message text ("Chain 2 ...", "hashboard 0 ...", "Slot 1 ...") so
  the issue shows on the right hashboard's tooltip. WhatsMiner (which does attribute
  HashBoard{idx}) is unchanged.
- #8a The pools dialog is widened so the rightmost "+" preset buttons (Password
  column) are no longer clipped off a too-narrow dialog.
- #8c The pool column headers now span field-width + the 34px "+" button, so the
  "Address/Account/Worker/Password" titles line up with the boxes below them.

board_index unit test + SELFTEST pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 16:52:24 -06:00
noahandClaude Opus 4.8 64e084ddee ui: per-icon tooltip repositioning + Zcash units/expected (round 18 #4a/#6/#7)
- #4a Health-column tooltips now reposition per icon: the query-tooltip handler
  scopes GTK's tip area to the hovered icon's slot, so moving across icons hides
  the old tooltip and shows a fresh one at the new position (was stuck in place).
- #6 Plain Antminer Z15 firmware omits the expected hashrate (the Z15j reports it),
  so it's filled from the model nameplate (420 KSol/s) -- the actual/expected
  column + colour now work for Z15 like every other miner.
- #7 Equihash hashrate now shows correct units: Sol/s (not TH/s). The stored value
  is Sol/s/1e12, so ths*1e12 recovers the Sol/s count; the per-board tooltip and
  the hashrate KPI card now label Equihash as Sol/s with an SI prefix.

Unit tests (equihash_hashrate_units) + health tests pass; SELFTEST PASS.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 16:45:45 -06:00
noahandClaude Opus 4.8 93bd528430 health: PSU-fault colour rules + per-board actual/expected tooltip (round 18 #2/#3/#4b)
- #2 A PSU fault while the miner is mining is now a warning (yellow) not a failure
  (red); a fault on a non-mining miner stays red. Fixes WhatsMiners flagged red
  while running fine.
- #4b A PSU fault no longer greys the hashboards. Board colour reflects the board's
  own state: running -> green, faulted (e.g. WhatsMiner 540/560) -> red, and grey
  ONLY when the board is genuinely not detected. Stall-reddened boards the fault
  codes don't name are still exonerated to green; undetected boards stay grey.
- #3 The per-board tooltip shows actual / expected hashrate (e.g. "2  .  33.5 / 35.0
  TH/s"); a not-detected board shows "not detected". Adds MinerRow.board_expected_
  hashrates (from BoardData.expected_hashrate) + an algorithm-aware hashrate unit
  (Equihash -> Sol/s, groundwork for #7).

Health tests updated + pass; SELFTEST PASS.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 16:36:00 -06:00
noahandClaude Opus 4.8 e45e6eaf91 ui: shrink brain icon, light toggle, blank all unknown-PIC (round 18 #1/#9/#11)
- #1 The control-board (brain) Health icon is drawn at 82% in its full slot, like
  the fan, so it no longer reads oversized (slot advance + tooltip hit-test unchanged).
- #9 The right-click menu now shows a single state-based light toggle: "Stop
  flashing lights" when any selected miner's locate light is on, else "Flash lights".
- #11 The PIC column is blank for every unknown case (non-Antminer makes and
  unclassifiable Antminer models) -- no more "?".

SELFTEST PASS; pic test updated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
2026-09-22 16:28:26 -06:00
12 changed files with 920 additions and 140 deletions
+75
View File
@@ -598,6 +598,77 @@ async fn settune(ip_s: &str, kind: &str, value: f64) {
} }
} }
/// READ: list the firmware's selectable profiles/presets (roadmap G3).
async fn presets(ip_s: &str) {
let ip: std::net::IpAddr = match ip_s.parse() {
Ok(ip) => ip,
Err(e) => {
eprintln!("bad ip {ip_s}: {e}");
return;
}
};
let f = factory();
match f.scan_miner(ip).await {
Ok(Some(m)) => {
if !m.supports_presets() {
println!("{ip}: firmware does not expose named presets");
return;
}
let list = m.get_presets().await;
if list.is_empty() {
println!("{ip}: no presets reported");
return;
}
for p in list {
match (p.pretty, p.status) {
(Some(pretty), Some(status)) => println!("{}\t{pretty}\t[{status}]", p.name),
(Some(pretty), None) => println!("{}\t{pretty}", p.name),
(None, _) => println!("{}", p.name),
}
}
}
Ok(None) => eprintln!("no miner at {ip}"),
Err(e) => eprintln!("scan_miner {ip}: {e}"),
}
}
/// WRITE (reversible): select a named firmware profile/preset (roadmap G3).
/// `setpreset <ip> <name>`. Prints the prior target so it can be restored.
async fn setpreset(ip_s: &str, name: &str) {
use asic_rs::core::config::tuning::TuningConfig;
use asic_rs::core::data::miner::TuningTarget;
let ip: std::net::IpAddr = match ip_s.parse() {
Ok(ip) => ip,
Err(e) => {
eprintln!("bad ip {ip_s}: {e}");
return;
}
};
let f = factory();
match f.scan_miner(ip).await {
Ok(Some(m)) => {
let before = m.get_data().await;
eprintln!(
"target {ip}: {} {} {} (supports_presets={}); prior target = {:?}",
before.device_info.make,
before.device_info.firmware,
before.device_info.model,
m.supports_presets(),
before.tuning_target,
);
let cfg = TuningConfig::new(TuningTarget::Preset(name.to_string()));
match m.set_tuning_config(cfg, None).await {
Ok(v) => println!("set_tuning_config(preset {name}) -> Ok({v})"),
Err(e) => println!("set_tuning_config(preset {name}) -> Err: {e:#}"),
}
let after = m.get_data().await;
println!(" target now = {:?}", after.tuning_target);
}
Ok(None) => eprintln!("no miner at {ip}"),
Err(e) => eprintln!("scan_miner {ip}: {e}"),
}
}
fn main() { fn main() {
let args: Vec<String> = std::env::args().collect(); let args: Vec<String> = std::env::args().collect();
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() { let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
@@ -630,6 +701,8 @@ fn main() {
} }
Some("msgs") if args.len() == 3 => rt.block_on(msgs(&args[2])), Some("msgs") if args.len() == 3 => rt.block_on(msgs(&args[2])),
Some("tune") if args.len() == 3 => rt.block_on(tune(&args[2])), Some("tune") if args.len() == 3 => rt.block_on(tune(&args[2])),
Some("presets") if args.len() == 3 => rt.block_on(presets(&args[2])),
Some("setpreset") if args.len() == 4 => rt.block_on(setpreset(&args[2], &args[3])),
Some("settune") if args.len() == 5 && matches!(args[3].as_str(), "power" | "hashrate") => { Some("settune") if args.len() == 5 && matches!(args[3].as_str(), "power" | "hashrate") => {
let value: f64 = args[4].parse().unwrap_or(-1.0); let value: f64 = args[4].parse().unwrap_or(-1.0);
if value <= 0.0 { if value <= 0.0 {
@@ -651,6 +724,7 @@ fn main() {
\x20 hashrate <cidr> [<cidr>...] raw hashrate/algo dump\n\ \x20 hashrate <cidr> [<cidr>...] raw hashrate/algo dump\n\
\x20 msgs <ip> structured faults + per-board data\n\ \x20 msgs <ip> structured faults + per-board data\n\
\x20 tune <ip> structured-tuning support + capability envelope\n\ \x20 tune <ip> structured-tuning support + capability envelope\n\
\x20 presets <ip> list selectable firmware profiles/presets\n\
\n\ \n\
WRITE (MUTATES the miner -- use the test-bed miners, not production):\n\ WRITE (MUTATES the miner -- use the test-bed miners, not production):\n\
\x20 light <ip> <on|off> set the locate light\n\ \x20 light <ip> <on|off> set the locate light\n\
@@ -660,6 +734,7 @@ fn main() {
\x20 restart <ip> restart/reboot\n\ \x20 restart <ip> restart/reboot\n\
\x20 setpl <ip> <watts> set power limit\n\ \x20 setpl <ip> <watts> set power limit\n\
\x20 settune <ip> <power|hashrate> <v> set a structured tuning target (prints prior)\n\ \x20 settune <ip> <power|hashrate> <v> set a structured tuning target (prints prior)\n\
\x20 setpreset <ip> <name> select a named firmware profile/preset (prints prior)\n\
\x20 setpools <ip> <url> <user> <pass> set the default pool group\n\ \x20 setpools <ip> <url> <user> <pass> set the default pool group\n\
\x20 timezone <ip> [<IANA>] read (no arg) or set the timezone\n\ \x20 timezone <ip> [<IANA>] read (no arg) or set the timezone\n\
\x20 passwd <ip> <newpass> change the web/API password (DANGEROUS)\n\ \x20 passwd <ip> <newpass> change the web/API password (DANGEROUS)\n\
+12
View File
@@ -173,6 +173,7 @@ impl Board {
power_limit: self.mining, power_limit: self.mining,
tuning: self.mining, tuning: self.mining,
hashrate_target: self.mining, hashrate_target: self.mining,
supports_presets: self.mining,
firmware_flash, firmware_flash,
pools: true, pools: true,
timezone: self.mining, timezone: self.mining,
@@ -203,6 +204,17 @@ impl Board {
} else { } else {
Vec::new() Vec::new()
}, },
// Demo firmware presets (round 18 / G3) so the "Set profile..." dialog
// is exercisable offline on units that advertise preset support.
presets: if self.mining {
vec![
crate::model::MinerPreset { name: "default".into(), pretty: Some("2794 W ~ 121.8 TH @ 590 MHz".into()) },
crate::model::MinerPreset { name: "540MHz".into(), pretty: Some("2485 W ~ 111.5 TH @ 540 MHz".into()) },
crate::model::MinerPreset { name: "490MHz".into(), pretty: Some("2192 W ~ 101.1 TH @ 490 MHz".into()) },
]
} else {
Vec::new()
},
..Default::default() ..Default::default()
} }
} }
+134 -49
View File
@@ -75,6 +75,23 @@ pub fn format_hashrate_ths(ths: f64) -> Option<String> {
si_mantissa_and_prefix(ths * 1e12).map(|(num, prefix)| format!("{num}{prefix}")) si_mantissa_and_prefix(ths * 1e12).map(|(num, prefix)| format!("{num}{prefix}"))
} }
/// 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<String> {
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 /// 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 /// (<= 0.0) so a ratio-based color/warning never divides by zero or treats an
/// unknown expectation as a 0% shortfall. /// unknown expectation as a 0% shortfall.
@@ -217,6 +234,10 @@ pub struct MinerCaps {
/// `set_tuning_config` (the firmware actively tunes by hashrate, e.g. ePIC). /// `set_tuning_config` (the firmware actively tunes by hashrate, e.g. ePIC).
/// Power targets are covered by `power_limit`. /// Power targets are covered by `power_limit`.
pub hashrate_target: bool, 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` /// Whether this miner's asic-rs driver supports `upgrade_firmware`
/// (probed via `supports_upgrade_firmware()` at scan time). /// (probed via `supports_upgrade_firmware()` at scan time).
pub firmware_flash: bool, pub firmware_flash: bool,
@@ -241,6 +262,7 @@ impl MinerCaps {
power_limit: self.power_limit && other.power_limit, power_limit: self.power_limit && other.power_limit,
tuning: self.tuning && other.tuning, tuning: self.tuning && other.tuning,
hashrate_target: self.hashrate_target && other.hashrate_target, hashrate_target: self.hashrate_target && other.hashrate_target,
supports_presets: self.supports_presets && other.supports_presets,
firmware_flash: self.firmware_flash && other.firmware_flash, firmware_flash: self.firmware_flash && other.firmware_flash,
pools: self.pools && other.pools, pools: self.pools && other.pools,
timezone: self.timezone && other.timezone, timezone: self.timezone && other.timezone,
@@ -274,6 +296,7 @@ impl MinerCaps {
|| self.power_limit || self.power_limit
|| self.tuning || self.tuning
|| self.hashrate_target || self.hashrate_target
|| self.supports_presets
|| self.firmware_flash || self.firmware_flash
|| self.pools || self.pools
|| self.timezone || self.timezone
@@ -365,6 +388,15 @@ pub enum HealthFacet {
Boards, 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<String>,
}
/// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the /// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the
/// scalar fields the table can display. Absent metrics are `None` / empty / /// scalar fields the table can display. Absent metrics are `None` / empty /
/// 0.0 and render as a blank cell. /// 0.0 and render as a blank cell.
@@ -420,6 +452,10 @@ pub struct MinerRow {
/// = board 1). Drives the per-board Health tooltip (round 17 R2). Empty when /// = board 1). Drives the per-board Health tooltip (round 17 R2). Empty when
/// the firmware reports no per-board hashrate. /// the firmware reports no per-board hashrate.
pub board_hashrates: Vec<f64>, pub board_hashrates: Vec<f64>,
/// 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<f64>,
#[allow(dead_code)] // retained for the "slow" band; not shown as its own column #[allow(dead_code)] // retained for the "slow" band; not shown as its own column
pub efficiency: f64, pub efficiency: f64,
pub power_w: f64, pub power_w: f64,
@@ -436,6 +472,9 @@ pub struct MinerRow {
/// Current structured tuning target, rendered for display (e.g. "2832 W", /// Current structured tuning target, rendered for display (e.g. "2832 W",
/// "96 TH/s", "preset 3550"), or None (round 17 C). /// "96 TH/s", "preset 3550"), or None (round 17 C).
pub tuning_target_label: Option<String>, pub tuning_target_label: Option<String>,
/// 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<MinerPreset>,
/// Advertised power-target envelope in watts, when the firmware reports one /// 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 /// (round 17 C, e.g. Braiins 944-6435 W). Bounds + validate the power-target
/// prompt; `None` leaves it unbounded. /// prompt; `None` leaves it unbounded.
@@ -516,12 +555,17 @@ impl MinerRow {
/// live); grey (unknown) otherwise -- asic-rs has no direct PSU-fault flag, so /// 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". /// a missing wattage reading is treated as unknown, never a false "down".
pub fn power_health(&self) -> CompHealth { pub fn power_health(&self) -> CompHealth {
// A reported power-supply fault (round 16 #2) is authoritative: red, even // A miner drawing power / spinning its PSU fan / actively mining has a live
// if a residual wattage is still being read. // 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() { if self.faults_for(FaultComponent::Power).next().is_some() {
return CompHealth::Down; return if self.is_mining { CompHealth::Degraded } else { CompHealth::Down };
} }
if self.power_w > 0.0 || self.psu_fan_rpm > 0.0 || self.is_mining { if delivering {
CompHealth::Ok CompHealth::Ok
} else { } else {
CompHealth::Unreachable CompHealth::Unreachable
@@ -557,12 +601,6 @@ impl MinerRow {
.filter(|f| f.is_error && matches!(f.component, FaultComponent::Other)) .filter(|f| f.is_error && matches!(f.component, FaultComponent::Other))
} }
/// True when the miner reports a power-supply fault, which means the
/// hashboards cannot be powered or evaluated (round 16 #2).
fn power_supply_faulted(&self) -> bool {
self.faults_for(FaultComponent::Power).next().is_some()
}
/// Per-fan health (round 13 #3), front-to-back / top-to-bottom in the order /// 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 /// 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 /// well below its fastest sibling (< 50% of the max reported RPM), which is a
@@ -621,16 +659,22 @@ impl MinerRow {
if base.is_empty() { if base.is_empty() {
return base; return base;
} }
// 3. A PSU fault means no board can be powered/tested -> all grey. // 2. Board-specific faults are authoritative: red the named boards. A board
if self.power_supply_faulted() { // is grey ONLY when it is genuinely not detected (base Missing); a board
return vec![CompHealth::Unreachable; base.len()]; // that is running stays green and a faulted board is red, even when the
} // PSU also reports a fault (round 18 #4b -- WhatsMiner codes 540/560 must
// 2. Board-specific faults are authoritative: red only the named boards, // show red, not grey, and boards still hashing during a PSU fault stay
// green the rest (overriding a stall-induced all-red). // green). A whole-miner stall reds every board's base, so exonerate the
// boards the fault codes did NOT name back to healthy.
let board_faulted = |i: usize| self.faults_for(FaultComponent::Board(i)).next().is_some(); let board_faulted = |i: usize| self.faults_for(FaultComponent::Board(i)).next().is_some();
if (0..base.len()).any(board_faulted) { if (0..base.len()).any(board_faulted) {
for (i, h) in base.iter_mut().enumerate() { for (i, h) in base.iter_mut().enumerate() {
*h = if board_faulted(i) { CompHealth::Down } else { ok }; if board_faulted(i) {
*h = CompHealth::Down;
} else if *h == CompHealth::Down {
*h = ok; // stall-reddened but not named by the fault codes
}
// else keep the base (green Ok / grey Missing).
} }
} }
base base
@@ -736,22 +780,28 @@ impl MinerRow {
tips.push(t); tips.push(t);
} }
// Hashboards -- an operating board shows its number (counting DOWN, n-1..0, // Hashboards -- an operating board shows its number (counting DOWN, n-1..0,
// left to right) and hashrate; a faulted board shows its error+code; a // left to right) and actual/expected hashrate; a faulted board shows its
// board the failed PSU left untested shows "unpowered" (round 17 R2, // error+code; a board that is genuinely not detected shows "not detected"
// round 16 #2/#3). No generic "Hashboard N: faulted" prose. // (round 17 R2, round 18 #3 actual/expected + #4b). No generic
// "Hashboard N: faulted" prose.
let boards = self.board_healths(); let boards = self.board_healths();
let psu_down = self.power_supply_faulted();
let n = self.hashboards.map(|v| v as usize).unwrap_or(boards.len()); let n = self.hashboards.map(|v| v as usize).unwrap_or(boards.len());
let unit = self.hashrate_unit();
for i in 0..max_boards { for i in 0..max_boards {
let fault = self.fault_texts_for(FaultComponent::Board(i)); let fault = self.fault_texts_for(FaultComponent::Board(i));
let t = if !fault.is_empty() { let t = if !fault.is_empty() {
fault.join("\n") fault.join("\n")
} else if matches!(boards.get(i), Some(CompHealth::Unreachable)) && psu_down { } else if matches!(boards.get(i), Some(CompHealth::Unreachable)) {
"unpowered (PSU fault)".to_string() "not detected".to_string()
} else if i < n { } else if i < n {
let num = n - 1 - i; // count down, left to right let num = n - 1 - i; // count down, left to right
match self.board_hashrates.get(i).copied() { let actual = self.board_hashrates.get(i).copied().unwrap_or(0.0);
Some(hr) if hr > 0.0 => format!("{num} \u{00b7} {hr:.1} TH/s"), 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);
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(), _ => num.to_string(),
} }
} else { } else {
@@ -773,6 +823,17 @@ impl MinerRow {
} }
} }
/// 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"
}
}
/// Compact plain-text summary of component health (round 13 #3), used as the /// 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 /// Health column's filter/sort-fallback text and the base of its hover
/// tooltip. e.g. "power ok, fans 3/4, boards 3/3". /// tooltip. e.g. "power ok, fans 3/4, boards 3/3".
@@ -1290,20 +1351,14 @@ impl Column {
Column::Cpu => r.cpu.clone(), Column::Cpu => r.cpu.clone(),
Column::BoardCode => r.board_code.clone(), Column::BoardCode => r.board_code.clone(),
Column::Algorithm => r.algorithm.clone(), Column::Algorithm => r.algorithm.clone(),
Column::Pic => { Column::Pic => match r.pic_present {
// A per-board PIC MCU is an Antminer hashboard property; it has no // A per-board PIC MCU is a known Antminer-hashboard property. Show
// meaning for WhatsMiner or any other make, which show nothing // it only when known; anything unknown (non-Antminer makes, or an
// rather than a "?" that implies an unanswered Antminer question. // Antminer model we can't classify) is blank, never "?" (round 18 #11).
if !r.brand.eq_ignore_ascii_case("antminer") { Some(true) => "PIC".to_string(),
String::new() Some(false) => "noPIC".to_string(),
} else { None => String::new(),
match r.pic_present { },
Some(true) => "PIC".to_string(),
Some(false) => "noPIC".to_string(),
None => "?".to_string(),
}
}
}
Column::Locked => match r.write_locked { Column::Locked => match r.write_locked {
Some(true) => "locked".to_string(), Some(true) => "locked".to_string(),
Some(false) => "unlocked".to_string(), Some(false) => "unlocked".to_string(),
@@ -1749,22 +1804,51 @@ mod tests {
assert!(board_tips[0].contains("Slot 0 error reading chip id.")); assert!(board_tips[0].contains("Slot 0 error reading chip id."));
assert!(!board_tips[2].contains("Slot"), "board 3 has no fault text"); assert!(!board_tips[2].contains("Slot"), "board 3 has no fault text");
// Round 16 #2: a power-supply fault greys every board (they can't be // Round 18 #2/#4b: a PSU fault while the miner is NOT mining is a real
// powered/tested), turns the bolt red, and the PSU message shows on the // failure (red bolt), and boards keep their own reported state -- a PSU
// power tooltip. // fault no longer greys them. Faulted boards stay red.
let psu = MinerRow { let psu = MinerRow {
power_w: 40.0, power_w: 40.0,
board_status: vec![BoardHealth::Fault, BoardHealth::Fault, BoardHealth::Fault], board_status: vec![BoardHealth::Fault, BoardHealth::Fault, BoardHealth::Fault],
expected_fans: Some(2), expected_fans: Some(2),
fan_rpms: vec![6000.0, 6000.0], fan_rpms: vec![6000.0, 6000.0],
faults: vec![fault(FaultComponent::Power, "Power current error.")], faults: vec![fault(FaultComponent::Power, "Power current error.")],
..Default::default() ..Default::default() // is_mining = false
}; };
assert_eq!(psu.power_health(), CompHealth::Down); assert_eq!(psu.power_health(), CompHealth::Down); // fault + not mining -> red
assert!(psu.board_healths().iter().all(|h| *h == CompHealth::Unreachable)); assert!(psu.board_healths().iter().all(|h| *h == CompHealth::Down)); // faulted -> red, not grey
let ptips = psu.health_tooltips(2, 3); let ptips = psu.health_tooltips(2, 3);
assert!(ptips[0].contains("Power current error.")); assert!(ptips[0].contains("Power current error."));
assert!(ptips[2 + 2].contains("unpowered")); // first board tooltip
// 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
}
#[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] #[test]
@@ -2099,12 +2183,12 @@ mod tests {
#[test] #[test]
fn pic_locked_error_columns_render() { fn pic_locked_error_columns_render() {
// PIC (best-effort): Antminer known -> PIC/noPIC, unknown Antminer -> "?". // PIC: known -> PIC/noPIC; anything unknown -> blank, never "?" (round 18 #11).
let am = |pic| MinerRow { brand: "Antminer".into(), pic_present: pic, ..Default::default() }; 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(true))), "PIC");
assert_eq!(Column::Pic.cell(&am(Some(false))), "noPIC"); assert_eq!(Column::Pic.cell(&am(Some(false))), "noPIC");
assert_eq!(Column::Pic.cell(&am(None)), "?"); assert_eq!(Column::Pic.cell(&am(None)), ""); // unknown Antminer model -> blank
// Non-Antminer makes: PIC has no meaning -> blank, never "?". // Non-Antminer makes: PIC has no meaning -> blank.
let wm = MinerRow { brand: "WhatsMiner".into(), pic_present: None, ..Default::default() }; let wm = MinerRow { brand: "WhatsMiner".into(), pic_present: None, ..Default::default() };
assert_eq!(Column::Pic.cell(&wm), ""); assert_eq!(Column::Pic.cell(&wm), "");
@@ -2370,6 +2454,7 @@ mod tests {
power_limit: true, power_limit: true,
tuning: true, tuning: true,
hashrate_target: true, hashrate_target: true,
supports_presets: true,
firmware_flash: true, firmware_flash: true,
pools: true, pools: true,
timezone: true, timezone: true,
+16
View File
@@ -287,6 +287,22 @@ fn is_aml_140mm(clean_model: &str) -> bool {
m.contains("XP") || m.starts_with("S19k") || m.starts_with("S21") m.contains("XP") || m.starts_with("S19k") || m.starts_with("S21")
} }
/// Nameplate expected hashrate in Sol/s for an Equihash (Zcash) miner model, when
/// the firmware itself does not report an expected hashrate (round 18 #6). Plain
/// Antminer Z15 firmware omits the cgminer `total_rateideal` field (the Z15j does
/// report it), so its actual-vs-expected column and colour would otherwise be
/// blank. The Z15 nameplate is 420 KSol/s. Returns `None` for models with no known
/// nameplate (the caller then leaves expected unknown).
pub fn equihash_expected_sols(clean_model: &str) -> Option<f64> {
let m = clean_model.to_ascii_lowercase();
// Match the Z15 family (z15, z15j); both share the 420 KSol/s nameplate.
if m.contains("z15") {
Some(420_000.0)
} else {
None
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+43 -31
View File
@@ -1,8 +1,8 @@
//! Dropdown presets + user-saved values for the Configure-pools dialog (round 15 //! Dropdown presets + user-saved values for the Configure-pools dialog (round 15
//! #1). Each pool field (address / account / worker / password) has a "+" menu //! #1). Each pool field (address / account / worker / password) has a "+" menu
//! offering built-in presets (pool stratums, worker placeholders) plus values the //! offering built-in presets (pool stratums, worker placeholders) plus values the
//! user has saved, and the user can add the current box value to the saved list. //! user has saved. "Add new..." opens a manager window that edits the whole saved
//! Saved lists persist one-per-line under the config dir. //! list at once (round 18 #8b). Saved lists persist one-per-line under the config dir.
use std::path::PathBuf; use std::path::PathBuf;
@@ -72,42 +72,32 @@ pub fn load_saved(field: PoolField) -> Vec<String> {
.unwrap_or_default() .unwrap_or_default()
} }
/// Add `value` to `field`'s saved list (deduplicated, no-op if empty/already /// Replace `field`'s entire saved list with `values` (round 18 #8b: the preset
/// present or already a preset). Returns true if it was newly added. /// manager edits the whole list at once). Each value is trimmed; empties, exact
pub fn add_saved(field: PoolField, value: &str) -> bool { /// duplicates, and any value that is already a built-in preset are dropped.
let value = value.trim(); /// Returns the number of values actually written.
if value.is_empty() { pub fn save_all(field: PoolField, values: &[String]) -> std::io::Result<usize> {
return false; let out = dedupe_saved(&field.presets(), values);
}
if field.presets().iter().any(|p| *p == value) {
return false;
}
let mut saved = load_saved(field);
if saved.iter().any(|s| s == value) {
return false;
}
saved.push(value.to_string());
let p = config_path(field.saved_file()); let p = config_path(field.saved_file());
if let Some(dir) = p.parent() { if let Some(dir) = p.parent() {
let _ = std::fs::create_dir_all(dir); let _ = std::fs::create_dir_all(dir);
} }
let _ = std::fs::write(p, saved.join("\n")); std::fs::write(&p, out.join("\n"))?;
true Ok(out.len())
} }
/// Remove `value` from `field`'s saved list (round 16 #5). Returns true if it was /// Trim every value, then drop empties, values equal to a built-in preset, and
/// present and removed. Presets cannot be removed (they are not in the saved file). /// later exact duplicates (first occurrence wins). Order is otherwise preserved.
pub fn remove_saved(field: PoolField, value: &str) -> bool { fn dedupe_saved(presets: &[&str], values: &[String]) -> Vec<String> {
let value = value.trim(); let mut out: Vec<String> = Vec::new();
let mut saved = load_saved(field); for v in values {
let before = saved.len(); let v = v.trim();
saved.retain(|s| s != value); if v.is_empty() || presets.iter().any(|p| *p == v) || out.iter().any(|s| s == v) {
if saved.len() == before { continue;
return false; }
out.push(v.to_string());
} }
let p = config_path(field.saved_file()); out
let _ = std::fs::write(p, saved.join("\n"));
true
} }
/// The full dropdown list for a field: presets first, then the user's saved /// The full dropdown list for a field: presets first, then the user's saved
@@ -129,3 +119,25 @@ pub fn dropdown_entries(field: PoolField) -> Vec<(String, String)> {
} }
out out
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dedupe_saved_trims_drops_empties_presets_and_dupes() {
let presets = ["x", "{ip1}"];
let vals: Vec<String> = [" ", "myworker", "myworker", "x", " keep ", "{ip1}", "keep"]
.iter()
.map(|s| s.to_string())
.collect();
// " " (empty), the second "myworker", "x"/"{ip1}" (presets) and the second
// "keep" all drop; " keep " is trimmed and kept.
assert_eq!(dedupe_saved(&presets, &vals), vec!["myworker".to_string(), "keep".to_string()]);
}
#[test]
fn dedupe_saved_empty_input_is_empty() {
assert!(dedupe_saved(&[], &[]).is_empty());
}
}
+97 -2
View File
@@ -478,6 +478,35 @@ fn summarize_messages(messages: &[asic_rs::core::data::message::MinerMessage]) -
/// component (round 16 #1/#2/#3), so the Health column can colour and describe /// component (round 16 #1/#2/#3), so the Health column can colour and describe
/// each icon from the actual per-component faults. Info-severity messages are /// each icon from the actual per-component faults. Info-severity messages are
/// dropped; Error and Warning are kept (only Error drives colour). /// dropped; Error and Warning are kept (only Error drives colour).
/// Best-effort hashboard index from a fault message that names a board (round 18
/// #5). Only WhatsMiner's asic-rs backends attribute a message to a specific
/// `HashBoard { idx }`; every Antminer-hardware firmware (stock, VNish, Braiins,
/// LuxOS) builds messages with no component, so a real per-board fault would
/// otherwise land on the control-board (brain) tooltip instead of the board it
/// names. The message text is self-describing (e.g. "Chain 2 ... temperature"),
/// so pull the first integer after a board keyword and attribute the fault to that
/// board. Returns None when no board keyword is present.
fn board_index_from_text(text: &str) -> Option<usize> {
let lower = text.to_ascii_lowercase();
// Longest/most-specific keywords first so "hashboard" wins over "board".
for kw in ["hashboard", "hash board", "chain", "slot", "board"] {
let mut from = 0;
while let Some(rel) = lower[from..].find(kw) {
let after = &lower[from + rel + kw.len()..];
let digits: String = after
.trim_start_matches(|c: char| !c.is_ascii_digit())
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
if let Ok(n) = digits.parse::<usize>() {
return Some(n);
}
from += rel + kw.len();
}
}
None
}
fn messages_to_faults( fn messages_to_faults(
messages: &[asic_rs::core::data::message::MinerMessage], messages: &[asic_rs::core::data::message::MinerMessage],
) -> Vec<crate::model::Fault> { ) -> Vec<crate::model::Fault> {
@@ -500,7 +529,12 @@ fn messages_to_faults(
Some(MinerComponent::ControlBoard {}) => FaultComponent::Control, Some(MinerComponent::ControlBoard {}) => FaultComponent::Control,
Some(MinerComponent::Fan { idx }) => FaultComponent::Fan(*idx as usize), Some(MinerComponent::Fan { idx }) => FaultComponent::Fan(*idx as usize),
Some(MinerComponent::HashBoard { idx, .. }) => FaultComponent::Board(*idx as usize), Some(MinerComponent::HashBoard { idx, .. }) => FaultComponent::Board(*idx as usize),
None => FaultComponent::Other, // Unattributed (every Antminer-hardware firmware): recover a board
// index from the message text so hashboard faults show on the board
// they name, not the control-board tooltip (round 18 #5).
None => board_index_from_text(text)
.map(FaultComponent::Board)
.unwrap_or(FaultComponent::Other),
}; };
Some(Fault { Some(Fault {
component, component,
@@ -512,6 +546,21 @@ fn messages_to_faults(
.collect() .collect()
} }
#[cfg(test)]
mod board_index_tests {
use super::board_index_from_text;
#[test]
fn extracts_board_index_from_common_fault_texts() {
assert_eq!(board_index_from_text("Chain 2 temperature sensor error"), Some(2));
assert_eq!(board_index_from_text("hashboard 0 loss of balance"), Some(0));
assert_eq!(board_index_from_text("Slot 1 error reading chip id."), Some(1));
assert_eq!(board_index_from_text("Board #3 not responding"), Some(3));
// No board keyword -> not attributed to a board.
assert_eq!(board_index_from_text("Environment temperature is too high."), None);
assert_eq!(board_index_from_text("Power current error."), None);
}
}
/// Infer whether an Antminer's hashboards carry a per-board PIC MCU from the /// Infer whether an Antminer's hashboards carry a per-board PIC MCU from the
/// model string (round 14 #2). No firmware (stock cgminer, Vnish, LuxOS, Braiins) /// model string (round 14 #2). No firmware (stock cgminer, Vnish, LuxOS, Braiins)
/// exposes a PIC flag over the network; PIC-vs-noPIC is fixed by the hashboard /// exposes a PIC flag over the network; PIC-vs-noPIC is fixed by the hashboard
@@ -572,7 +621,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.as_ref() .as_ref()
.map(|h| h.clone().as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value) .map(|h| h.clone().as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value)
.unwrap_or(0.0); .unwrap_or(0.0);
let expected_ths = data let mut expected_ths = data
.expected_hashrate .expected_hashrate
.as_ref() .as_ref()
.map(|h| h.clone().as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value) .map(|h| h.clone().as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value)
@@ -614,6 +663,18 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.unwrap_or(0.0) .unwrap_or(0.0)
}) })
.collect(); .collect();
// Per-board expected hashrate (TH/s), index-aligned, for the actual/expected
// per-board tooltip (round 18 #3).
let board_expected_hashrates: Vec<f64> = data
.hashboards
.iter()
.map(|b| {
b.expected_hashrate
.as_ref()
.map(|h| h.clone().as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value)
.unwrap_or(0.0)
})
.collect();
let fan_rpms: Vec<f64> = data let fan_rpms: Vec<f64> = data
.fans .fans
.iter() .iter()
@@ -699,6 +760,14 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm())) .filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
.fold(0.0f64, f64::max); .fold(0.0f64, f64::max);
let algorithm = data.hashrate.as_ref().map(|h| h.algo.to_string()).unwrap_or_default(); let algorithm = data.hashrate.as_ref().map(|h| h.algo.to_string()).unwrap_or_default();
// Equihash (Z15) fallback: plain Z15 firmware omits the expected hashrate, so
// fill it from the model nameplate (Sol/s -> the ths-normalised value) so the
// actual/expected column + colour work like every other miner (round 18 #6).
if expected_ths <= 0.0 && algorithm.eq_ignore_ascii_case("equihash") {
if let Some(sols) = crate::naming::equihash_expected_sols(&model) {
expected_ths = sols / 1e12;
}
}
let is_mining = data.is_mining; let is_mining = data.is_mining;
let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths); let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths);
let operating_state = data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default(); let operating_state = data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default();
@@ -759,12 +828,26 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
power_limit, power_limit,
tuning: miner.supports_set_tuning_percent(), tuning: miner.supports_set_tuning_percent(),
hashrate_target, hashrate_target,
supports_presets: miner.supports_presets(),
firmware_flash: miner.supports_upgrade_firmware(), firmware_flash: miner.supports_upgrade_firmware(),
pools: miner.supports_pools_config(), pools: miner.supports_pools_config(),
timezone: miner.supports_timezone_config(), timezone: miner.supports_timezone_config(),
change_password: miner.supports_change_password(), change_password: miner.supports_change_password(),
factory_reset: miner.supports_factory_reset(), factory_reset: miner.supports_factory_reset(),
}; };
// The firmware's selectable named presets/profiles (round 18 / roadmap G3),
// read live only for miners that advertise them (LuxOS/VNish). One extra RPC
// at scan time for those miners; the default 300 s rescan makes it negligible.
let presets: Vec<crate::model::MinerPreset> = if caps.supports_presets {
miner
.get_presets()
.await
.into_iter()
.map(|p| crate::model::MinerPreset { name: p.name, pretty: p.pretty })
.collect()
} else {
Vec::new()
};
// PIC vs noPIC (round 14 #2 rework). No firmware exposes a PIC flag over the // PIC vs noPIC (round 14 #2 rework). No firmware exposes a PIC flag over the
// network -- it's a fixed hardware property of the hashboard type -- so infer // network -- it's a fixed hardware property of the hashboard type -- so infer
// it from the model, which every API reports. See `infer_pic`. // it from the model, which every API reports. See `infer_pic`.
@@ -816,6 +899,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
model, model,
brand, brand,
submodel, submodel,
presets,
mac: data.mac.map(|m| m.to_string()).unwrap_or_default(), mac: data.mac.map(|m| m.to_string()).unwrap_or_default(),
hostname: data.hostname.clone().unwrap_or_default(), hostname: data.hostname.clone().unwrap_or_default(),
serial: { serial: {
@@ -843,6 +927,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
hashrate_ths, hashrate_ths,
expected_ths, expected_ths,
board_hashrates, board_hashrates,
board_expected_hashrates,
efficiency: data.efficiency.unwrap_or(0.0), efficiency: data.efficiency.unwrap_or(0.0),
power_w, power_w,
// PSU info (round 17 R5/G15; ePIC exposes it today). A reported-but-zero // PSU info (round 17 R5/G15; ePIC exposes it today). A reported-but-zero
@@ -906,6 +991,7 @@ pub enum ConfigAction {
Resume, Resume,
PowerLimit(f64), // watts PowerLimit(f64), // watts
HashRateTarget(f64), // TH/s -- structured hashrate target (round 17 C) HashRateTarget(f64), // TH/s -- structured hashrate target (round 17 C)
Preset(String), // named firmware profile/preset (round 18 / G3)
TuningPercent(u8), TuningPercent(u8),
Timezone(String), // IANA zone, e.g. "America/Edmonton" (round 17 B / G10) Timezone(String), // IANA zone, e.g. "America/Edmonton" (round 17 B / G10)
ChangePassword(String), // new web/API password (round 17 B / G11) ChangePassword(String), // new web/API password (round 17 B / G11)
@@ -923,6 +1009,7 @@ impl ConfigAction {
ConfigAction::Resume => "resume".into(), ConfigAction::Resume => "resume".into(),
ConfigAction::PowerLimit(w) => format!("power target {w:.0} W"), ConfigAction::PowerLimit(w) => format!("power target {w:.0} W"),
ConfigAction::HashRateTarget(t) => format!("hashrate target {t:.0} TH/s"), ConfigAction::HashRateTarget(t) => format!("hashrate target {t:.0} TH/s"),
ConfigAction::Preset(name) => format!("preset {name}"),
ConfigAction::TuningPercent(p) => format!("tuning {p}%"), ConfigAction::TuningPercent(p) => format!("tuning {p}%"),
ConfigAction::Timezone(tz) => format!("timezone {tz}"), ConfigAction::Timezone(tz) => format!("timezone {tz}"),
ConfigAction::ChangePassword(_) => "change password".into(), ConfigAction::ChangePassword(_) => "change password".into(),
@@ -941,6 +1028,7 @@ impl ConfigAction {
ConfigAction::Resume => "resuming…".into(), ConfigAction::Resume => "resuming…".into(),
ConfigAction::PowerLimit(_) => "setting power…".into(), ConfigAction::PowerLimit(_) => "setting power…".into(),
ConfigAction::HashRateTarget(_) => "setting hashrate…".into(), ConfigAction::HashRateTarget(_) => "setting hashrate…".into(),
ConfigAction::Preset(_) => "setting preset…".into(),
ConfigAction::TuningPercent(_) => "tuning…".into(), ConfigAction::TuningPercent(_) => "tuning…".into(),
ConfigAction::Timezone(_) => "setting timezone…".into(), ConfigAction::Timezone(_) => "setting timezone…".into(),
ConfigAction::ChangePassword(_) => "changing password…".into(), ConfigAction::ChangePassword(_) => "changing password…".into(),
@@ -997,6 +1085,13 @@ async fn apply_action(miner: &dyn Miner, action: &ConfigAction) -> Result<bool,
let scaling = miner.get_scaling_config().await.ok(); let scaling = miner.get_scaling_config().await.ok();
miner.set_tuning_config(cfg, scaling).await miner.set_tuning_config(cfg, scaling).await
} }
ConfigAction::Preset(name) => {
use asic_rs::core::config::tuning::TuningConfig;
use asic_rs::core::data::miner::TuningTarget;
miner
.set_tuning_config(TuningConfig::new(TuningTarget::Preset(name.clone())), None)
.await
}
ConfigAction::TuningPercent(p) => miner.set_tuning_percent(*p).await, ConfigAction::TuningPercent(p) => miner.set_tuning_percent(*p).await,
ConfigAction::Timezone(tz) => { ConfigAction::Timezone(tz) => {
use asic_rs::core::config::timezone::{Tz, TimezoneConfig}; use asic_rs::core::config::timezone::{Tz, TimezoneConfig};
+243 -48
View File
@@ -67,6 +67,7 @@ const ID_CTX_RESUME: i32 = 726;
const ID_CTX_TUNING: i32 = 727; const ID_CTX_TUNING: i32 = 727;
const ID_CTX_POWER: i32 = 728; const ID_CTX_POWER: i32 = 728;
const ID_CTX_HASHRATE: i32 = 740; // Set hashrate target (round 17 C) const ID_CTX_HASHRATE: i32 = 740; // Set hashrate target (round 17 C)
const ID_CTX_PRESET: i32 = 741; // Set firmware profile/preset (round 18 / G3)
const ID_CTX_RESTART: i32 = 729; const ID_CTX_RESTART: i32 = 729;
// Round 17 B: timezone / change-password / factory-reset config actions. // Round 17 B: timezone / change-password / factory-reset config actions.
const ID_CTX_TIMEZONE: i32 = 737; const ID_CTX_TIMEZONE: i32 = 737;
@@ -84,12 +85,18 @@ const ID_RESTORE_CANCEL: i32 = 787;
const ID_CTX_POOLS: i32 = 736; const ID_CTX_POOLS: i32 = 736;
const ID_POOLS_OK: i32 = 788; const ID_POOLS_OK: i32 = 788;
const ID_POOLS_CANCEL: i32 = 789; const ID_POOLS_CANCEL: i32 = 789;
// Pool-preset manager dialog (round 18 #8b): edit the whole saved list at once.
const ID_POOL_PRESETS_SAVE: i32 = 790;
const ID_POOL_PRESETS_CANCEL: i32 = 791;
// Firmware profile/preset selector dialog (round 18 / roadmap G3).
const ID_FWPRESET_OK: i32 = 792;
const ID_FWPRESET_CANCEL: i32 = 793;
const ID_FWPRESET_CHOICE: i32 = 794;
// Pool-field "+" dropdown buttons (round 15 #1): 12 buttons (3 rows x 4 fields), // Pool-field "+" dropdown buttons (round 15 #1): 12 buttons (3 rows x 4 fields),
// id = base + row*4 + field. The dropdown menu items use their own id range. // id = base + row*4 + field. The dropdown menu items use their own id range.
const ID_POOL_PLUS_BASE: i32 = 800; const ID_POOL_PLUS_BASE: i32 = 800;
const ID_POOL_MENU_ADD: i32 = 819; // "add new" (adds current box value to the dropdown) const ID_POOL_MENU_ADD: i32 = 819; // "Add new..." -> opens the preset-manager window (round 18 #8b)
const ID_POOL_MENU_BASE: i32 = 820; // one id per dropdown entry (820 + index) const ID_POOL_MENU_BASE: i32 = 820; // one id per dropdown entry (820 + index)
const ID_POOL_MENU_REMOVE_BASE: i32 = 1000; // one id per removable saved entry (round 16 #5)
// Value-prompt dialog for power-limit / tuning-percent / timezone / password. // Value-prompt dialog for power-limit / tuning-percent / timezone / password.
const ID_ACTION_OK: i32 = 740; const ID_ACTION_OK: i32 = 740;
const ID_ACTION_CANCEL: i32 = 741; const ID_ACTION_CANCEL: i32 = 741;
@@ -632,6 +639,11 @@ pub struct App {
kpi_power: Widget, kpi_power: Widget,
progress: Widget, progress: Widget,
pub table: Option<Widget>, pub table: Option<Widget>,
// Whether the columns have had their one-time content-fit autosize applied
// since the table was last (re)built (round 18 #10). Reset on rebuild; set
// the first time fill_rows runs with rows present, so the default widths fit
// their contents (capped) once and manual resizes afterwards are preserved.
columns_autosized: bool,
table_parent: Widget, table_parent: Widget,
root_sizer: Widget, root_sizer: Widget,
pub scan: Option<scan::ScanHandle>, pub scan: Option<scan::ScanHandle>,
@@ -737,6 +749,18 @@ pub struct App {
pool_menu_target: usize, // which field the open "+" menu edits pool_menu_target: usize, // which field the open "+" menu edits
pool_menu_field: crate::pool_prefs::PoolField, pool_menu_field: crate::pool_prefs::PoolField,
pool_menu_values: Vec<String>, // values behind the open menu, by item index pool_menu_values: Vec<String>, // values behind the open menu, by item index
// The pool-preset manager dialog (round 18 #8b): a multiline editable list of
// the saved values for one field, reached from the "+" menu's "Manage saved".
pool_presets_dialog: Widget,
pool_presets_input: Widget,
pool_presets_field: crate::pool_prefs::PoolField,
// Firmware profile/preset selector (round 18 / roadmap G3): a Choice of the
// selected miner's presets, the names behind each entry, and the target IPs
// captured when the dialog opened.
fw_preset_dialog: Widget,
fw_preset_choice: Widget,
fw_preset_names: Vec<String>,
fw_preset_ips: Vec<String>,
// Saved view presets + the Presets dialog widgets. // Saved view presets + the Presets dialog widgets.
presets: Vec<crate::presets::Preset>, presets: Vec<crate::presets::Preset>,
presets_dialog: Widget, presets_dialog: Widget,
@@ -982,6 +1006,7 @@ pub fn build(frame: Widget) -> App {
kpi_power, kpi_power,
progress, progress,
table: None, table: None,
columns_autosized: false,
table_parent, table_parent,
root_sizer: root, root_sizer: root,
scan: Some(scan::start_scan(ranges.clone(), scan::load_scan_timeout())), scan: Some(scan::start_scan(ranges.clone(), scan::load_scan_timeout())),
@@ -1036,6 +1061,13 @@ pub fn build(frame: Widget) -> App {
pool_menu_target: 0, pool_menu_target: 0,
pool_menu_field: crate::pool_prefs::PoolField::Address, pool_menu_field: crate::pool_prefs::PoolField::Address,
pool_menu_values: Vec::new(), pool_menu_values: Vec::new(),
pool_presets_dialog: frame,
pool_presets_input: frame,
pool_presets_field: crate::pool_prefs::PoolField::Address,
fw_preset_dialog: frame,
fw_preset_choice: frame,
fw_preset_names: Vec::new(),
fw_preset_ips: Vec::new(),
presets: crate::presets::load_presets(), presets: crate::presets::load_presets(),
presets_dialog: frame, presets_dialog: frame,
presets_choice: frame, presets_choice: frame,
@@ -1170,6 +1202,9 @@ impl App {
// Re-apply the table zoom so a non-100% zoom survives this rebuild // Re-apply the table zoom so a non-100% zoom survives this rebuild
// (round 14 #3); the fresh columns come back at their 100% widths. // (round 14 #3); the fresh columns come back at their 100% widths.
wx_rs::table_zoom_reapply(); wx_rs::table_zoom_reapply();
// Fresh columns come back at their configured default widths; let the
// next fill_rows shrink them to fit their contents (round 18 #10).
self.columns_autosized = false;
self.fill_rows(); self.fill_rows();
} }
@@ -1275,6 +1310,17 @@ impl App {
} }
} }
} }
// Item 10: the first time we have rows to measure after a (re)build, set
// each column's width to the smaller of its content-fit width and its
// configured default (the cap), so columns are no wider than needed. Done
// once per rebuild; the user's later manual resizes are then preserved
// because subsequent fill_rows calls (scan updates) skip this.
if !self.columns_autosized && !self.view_idx.is_empty() {
for (pos, c) in cols.iter().enumerate() {
t.dvlc_autosize_col_capped(pos, c.width());
}
self.columns_autosized = true;
}
if let Some(row) = top { if let Some(row) = top {
t.dvlc_ensure_visible(row.min(self.view_idx.len().saturating_sub(1))); t.dvlc_ensure_visible(row.min(self.view_idx.len().saturating_sub(1)));
} }
@@ -1311,14 +1357,16 @@ impl App {
// With a single algorithm running (the common case) the card shows that // With a single algorithm running (the common case) the card shows that
// algorithm's total under a "<Algo> Hashrate" caption; when several are // algorithm's total under a "<Algo> Hashrate" caption; when several are
// running, clicking the card cycles `hashrate_algo_idx` through them. // running, clicking the card cycles `hashrate_algo_idx` through them.
let (algo_label, algo_ths) = if k.hashrate_by_algo.is_empty() { let (algo_label, algo_ths, algo_unit) = if k.hashrate_by_algo.is_empty() {
("SHA-256".to_string(), 0.0) ("SHA-256".to_string(), 0.0, "H")
} else { } else {
let i = self.hashrate_algo_idx % k.hashrate_by_algo.len(); let i = self.hashrate_algo_idx % k.hashrate_by_algo.len();
let (a, t) = &k.hashrate_by_algo[i]; let (a, t) = &k.hashrate_by_algo[i];
(pretty_algo(a), *t) // Equihash miners (Z15/Zcash) are counted in Sol/s, not H/s (round 18 #7).
let unit = if a.eq_ignore_ascii_case("equihash") { "Sol" } else { "H" };
(pretty_algo(a), *t, unit)
}; };
self.kpi_hashrate.set_label(&format_si(algo_ths * 1e12, "H")); self.kpi_hashrate.set_label(&format_si(algo_ths * 1e12, algo_unit));
self.kpi_hashrate_lbl.set_label(&format!("{algo_label} Hashrate")); self.kpi_hashrate_lbl.set_label(&format!("{algo_label} Hashrate"));
self.kpi_power.set_label(&format_si(k.total_power_w, "W")); self.kpi_power.set_label(&format_si(k.total_power_w, "W"));
// set_label resizes the static text; re-run each card's sizer so the // set_label resizes the static text; re-run each card's sizer so the
@@ -1472,8 +1520,14 @@ impl App {
if !caps.is_empty() { if !caps.is_empty() {
let sfx = if n == 1 { String::new() } else { format!(" ({n})") }; let sfx = if n == 1 { String::new() } else { format!(" ({n})") };
if caps.fault_light { if caps.fault_light {
menu.menu_append(ID_CTX_LIGHT_ON, &format!("Flash lights on{sfx}")); // A single state-based toggle (round 18 #9): if any selected miner's
menu.menu_append(ID_CTX_LIGHT_OFF, &format!("Flash lights off{sfx}")); // locate light is on, offer to stop; otherwise offer to flash.
let any_on = selected.iter().any(|r| r.light_flashing == Some(true));
if any_on {
menu.menu_append(ID_CTX_LIGHT_OFF, &format!("Stop flashing lights{sfx}"));
} else {
menu.menu_append(ID_CTX_LIGHT_ON, &format!("Flash lights{sfx}"));
}
} }
if caps.pause { if caps.pause {
menu.menu_append(ID_CTX_PAUSE, &format!("Pause mining{sfx}")); menu.menu_append(ID_CTX_PAUSE, &format!("Pause mining{sfx}"));
@@ -1490,6 +1544,9 @@ impl App {
if caps.hashrate_target { if caps.hashrate_target {
menu.menu_append(ID_CTX_HASHRATE, &format!("Set hashrate target...{sfx}")); menu.menu_append(ID_CTX_HASHRATE, &format!("Set hashrate target...{sfx}"));
} }
if caps.supports_presets {
menu.menu_append(ID_CTX_PRESET, &format!("Set profile...{sfx}"));
}
if caps.restart { if caps.restart {
menu.menu_append(ID_CTX_RESTART, &format!("Restart{sfx}")); menu.menu_append(ID_CTX_RESTART, &format!("Restart{sfx}"));
} }
@@ -1579,16 +1636,19 @@ impl App {
l.set_min_size(w, -1); l.set_min_size(w, -1);
l l
}; };
// Each column on screen is the text field PLUS its 34px "+" button, so each
// header must span field_width + 34 to line up with the boxes below it
// (round 18 #8c). The Pool-label column is 46 to match the row label.
const PLUS_W: i32 = 34;
let widths = [170, 110, 110, 70]; // address, account, worker, password
head.add(hl("", 46), 0, sf::BORDER_LEFT, 6); head.add(hl("", 46), 0, sf::BORDER_LEFT, 6);
head.add(hl("Address", 176), 0, sf::BORDER_LEFT, 6); head.add(hl("Address", widths[0] + PLUS_W), 0, sf::BORDER_LEFT, 6);
head.add(hl("Account", 116), 0, sf::BORDER_LEFT, 6); head.add(hl("Account", widths[1] + PLUS_W), 0, sf::BORDER_LEFT, 6);
head.add(hl("Worker", 116), 0, sf::BORDER_LEFT, 6); head.add(hl("Worker", widths[2] + PLUS_W), 0, sf::BORDER_LEFT, 6);
head.add(hl("Password", 76), 0, sf::BORDER_LEFT, 6); head.add(hl("Password", widths[3] + PLUS_W), 0, sf::BORDER_LEFT, 6);
root.add_sizer(head, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6); root.add_sizer(head, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
let mut fields: Vec<Widget> = Vec::with_capacity(12); let mut fields: Vec<Widget> = Vec::with_capacity(12);
// widths per field type (address, account, worker, password).
let widths = [170, 110, 110, 70];
for row in 0..3usize { for row in 0..3usize {
let rsizer = Widget::box_sizer(false); let rsizer = Widget::box_sizer(false);
let lbl = Widget::static_text(dlg, &format!("Pool {}", row + 1)); let lbl = Widget::static_text(dlg, &format!("Pool {}", row + 1));
@@ -1599,7 +1659,7 @@ impl App {
input.set_min_size(widths[field], -1); input.set_min_size(widths[field], -1);
rsizer.add(input, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT, 6); rsizer.add(input, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT, 6);
let plus = Widget::button(dlg, "+", ID_POOL_PLUS_BASE + (row * 4 + field) as i32); let plus = Widget::button(dlg, "+", ID_POOL_PLUS_BASE + (row * 4 + field) as i32);
plus.set_min_size(34, -1); // wide enough that the "+" glyph isn't clipped plus.set_min_size(PLUS_W, -1); // wide enough that the "+" glyph isn't clipped
rsizer.add(plus, 0, sf::ALIGN_CENTRE_VERTICAL, 0); rsizer.add(plus, 0, sf::ALIGN_CENTRE_VERTICAL, 0);
fields.push(input); fields.push(input);
} }
@@ -1611,7 +1671,9 @@ impl App {
btns.add(Widget::button(dlg, "Cancel", ID_POOLS_CANCEL), 0, sf::BORDER_ALL, 6); btns.add(Widget::button(dlg, "Cancel", ID_POOLS_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg); root.set_sizer_on(dlg);
dlg.set_min_size(560, 220); // round 16 #5: narrower; fit() grows to content // Wide enough for the label + all four field+button columns so the "+"
// buttons on the right (Password) are never clipped (round 18 #8a).
dlg.set_min_size(700, 220);
dlg.fit(dlg); dlg.fit(dlg);
self.pools_dialog = dlg; self.pools_dialog = dlg;
self.pool_fields = fields; self.pool_fields = fields;
@@ -1644,17 +1706,10 @@ impl App {
self.pool_menu_values.push(value); self.pool_menu_values.push(value);
} }
menu.menu_append_separator(); menu.menu_append_separator();
menu.menu_append(ID_POOL_MENU_ADD, "Add new"); // "Add new..." opens the preset-manager window: an editable list of all the
// Let the user remove values they previously added (round 16 #5); presets // saved values for this field, so the user can add, edit and remove them in
// are built-in and stay. Listed in a submenu keyed by saved-list index. // one place (round 18 #8b -- replaces the old add-one / remove-submenu pair).
let saved = crate::pool_prefs::load_saved(field); menu.menu_append(ID_POOL_MENU_ADD, "Add new...");
if !saved.is_empty() {
let sub = Widget::menu_new();
for (i, val) in saved.iter().enumerate() {
sub.menu_append(ID_POOL_MENU_REMOVE_BASE + i as i32, val);
}
menu.menu_append_submenu("Remove saved value", sub);
}
self.pool_menu_target = target; self.pool_menu_target = target;
self.pool_menu_field = field; self.pool_menu_field = field;
self.pending_popup = Some((self.pools_dialog, menu)); self.pending_popup = Some((self.pools_dialog, menu));
@@ -1662,29 +1717,12 @@ impl App {
/// A pool dropdown item was chosen (round 15 #1). Worker values insert at the /// A pool dropdown item was chosen (round 15 #1). Worker values insert at the
/// cursor (so several placeholders can be combined); other fields replace. /// cursor (so several placeholders can be combined); other fields replace.
/// ("Add new..." is handled in on_menu_item, which opens the preset manager.)
fn choose_pool_dropdown(&mut self, id: i32) { fn choose_pool_dropdown(&mut self, id: i32) {
use crate::pool_prefs::PoolField; use crate::pool_prefs::PoolField;
let Some(input) = self.pool_fields.get(self.pool_menu_target).copied() else { let Some(input) = self.pool_fields.get(self.pool_menu_target).copied() else {
return; return;
}; };
if id == ID_POOL_MENU_ADD {
let val = input.get_value();
if crate::pool_prefs::add_saved(self.pool_menu_field, &val) {
wx_rs::set_status_text("added to the dropdown list");
}
return;
}
// Remove a previously-saved value (round 16 #5).
if id >= ID_POOL_MENU_REMOVE_BASE {
let ri = (id - ID_POOL_MENU_REMOVE_BASE) as usize;
let saved = crate::pool_prefs::load_saved(self.pool_menu_field);
if let Some(val) = saved.get(ri) {
if crate::pool_prefs::remove_saved(self.pool_menu_field, val) {
wx_rs::set_status_text("removed from the dropdown list");
}
}
return;
}
let idx = (id - ID_POOL_MENU_BASE) as usize; let idx = (id - ID_POOL_MENU_BASE) as usize;
let Some(value) = self.pool_menu_values.get(idx).cloned() else { let Some(value) = self.pool_menu_values.get(idx).cloned() else {
return; return;
@@ -1696,6 +1734,73 @@ impl App {
} }
} }
/// Build (but do not show) the pool-preset manager (round 18 #8b): a multiline
/// editable list of the saved values for the field whose "+" menu is open. The
/// current box value (if non-empty and not already saved or a built-in preset)
/// is seeded as the last line, so "Add new..." pre-fills what the user typed.
fn build_pool_presets_dialog(&mut self) -> Widget {
use crate::pool_prefs::PoolField;
let field = self.pool_menu_field;
let field_name = match field {
PoolField::Address => "address",
PoolField::Account => "account",
PoolField::Worker => "worker",
PoolField::Password => "password",
};
let mut lines = crate::pool_prefs::load_saved(field);
if let Some(input) = self.pool_fields.get(self.pool_menu_target).copied() {
let cur = input.get_value().trim().to_string();
if !cur.is_empty()
&& !lines.iter().any(|l| l == &cur)
&& !field.presets().iter().any(|p| *p == cur)
{
lines.push(cur);
}
}
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &format!("Saved {field_name} values"));
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(
dlg,
"One value per line. These appear in the + menu below the built-in\npresets. Edit freely, then Save.",
),
0,
sf::BORDER_ALL,
8,
);
let input = Widget::text_ctrl(dlg, true);
input.set_value(&lines.join("\n"));
input.set_min_size(360, 220);
root.add(input, 1, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Save", ID_POOL_PRESETS_SAVE), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_POOL_PRESETS_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(400, 340);
dlg.fit(dlg);
self.pool_presets_dialog = dlg;
self.pool_presets_input = input;
self.pool_presets_field = field;
dlg
}
/// Save the edited pool-preset list back to disk (round 18 #8b). Blank lines,
/// duplicates and built-in presets are dropped by pool_prefs::save_all.
fn apply_pool_presets(&mut self) {
let text = self.pool_presets_input.get_value();
let values: Vec<String> = text.lines().map(|l| l.trim().to_string()).collect();
match crate::pool_prefs::save_all(self.pool_presets_field, &values) {
Ok(n) => {
self.pool_presets_dialog.close(1);
wx_rs::set_status_text(&format!("saved {n} value(s)"));
}
Err(e) => wx_rs::set_status_text(&format!("failed to save: {e}")),
}
}
/// Read the 3 pool rows, expand each row's worker per selected miner, and /// Read the 3 pool rows, expand each row's worker per selected miner, and
/// start the background pool-config action (round 15 #1). Rows missing an /// start the background pool-config action (round 15 #1). Rows missing an
/// address or account are skipped; a miner with no usable rows is skipped. /// address or account are skipped; a miner with no usable rows is skipped.
@@ -2056,9 +2161,12 @@ impl App {
/// A menu item was chosen. Direct actions start immediately; the value-input /// A menu item was chosen. Direct actions start immediately; the value-input
/// actions (power limit / tuning %) return a prompt dialog to show modally. /// actions (power limit / tuning %) return a prompt dialog to show modally.
fn on_menu_item(&mut self, id: i32) -> Option<Widget> { fn on_menu_item(&mut self, id: i32) -> Option<Widget> {
// Pool "+" dropdown selections (round 15 #1): the "add current" item and // Pool "+" dropdown selections (round 15 #1). "Add new..." opens the preset
// one id per dropdown entry from ID_POOL_MENU_BASE up. // manager (round 18 #8b, shown modally); the rest fill the box in place.
if id == ID_POOL_MENU_ADD || id >= ID_POOL_MENU_BASE { if id == ID_POOL_MENU_ADD {
return Some(self.build_pool_presets_dialog());
}
if id >= ID_POOL_MENU_BASE {
self.choose_pool_dropdown(id); self.choose_pool_dropdown(id);
return None; return None;
} }
@@ -2121,6 +2229,7 @@ impl App {
// Value entry is itself the confirmation. // Value entry is itself the confirmation.
ID_CTX_POWER => return Some(self.build_action_prompt(PromptKind::Power)), ID_CTX_POWER => return Some(self.build_action_prompt(PromptKind::Power)),
ID_CTX_HASHRATE => return Some(self.build_action_prompt(PromptKind::HashRateTarget)), ID_CTX_HASHRATE => return Some(self.build_action_prompt(PromptKind::HashRateTarget)),
ID_CTX_PRESET => return self.build_fw_preset_dialog(),
ID_CTX_TUNING => return Some(self.build_action_prompt(PromptKind::Tuning)), ID_CTX_TUNING => return Some(self.build_action_prompt(PromptKind::Tuning)),
ID_CTX_TIMEZONE => return Some(self.build_action_prompt(PromptKind::Timezone)), ID_CTX_TIMEZONE => return Some(self.build_action_prompt(PromptKind::Timezone)),
ID_CTX_PASSWORD => return Some(self.build_action_prompt(PromptKind::Password)), ID_CTX_PASSWORD => return Some(self.build_action_prompt(PromptKind::Password)),
@@ -2340,6 +2449,86 @@ impl App {
} }
} }
/// Build (but do not show) the firmware profile/preset selector (round 18 /
/// roadmap G3). Populated live from the presets read at scan time; only the
/// profiles common (by name) to every selected preset-capable miner are
/// offered, so the chosen profile is valid on all of them. Returns None (with
/// a status hint) when there is nothing to offer.
fn build_fw_preset_dialog(&mut self) -> Option<Widget> {
let supporting: Vec<&MinerRow> = self
.selected_rows()
.into_iter()
.filter(|r| r.caps.supports_presets && !r.presets.is_empty())
.collect();
if supporting.is_empty() {
wx_rs::set_status_text("no firmware profiles available for the selection yet");
return None;
}
// Intersect the profile names across the selection so the chosen name is
// valid on every target; keep the first miner's pretty labels.
let mut common: Vec<crate::model::MinerPreset> = supporting[0].presets.clone();
for r in &supporting[1..] {
let names: std::collections::HashSet<&str> =
r.presets.iter().map(|p| p.name.as_str()).collect();
common.retain(|p| names.contains(p.name.as_str()));
}
if common.is_empty() {
wx_rs::set_status_text("selected miners share no common firmware profile");
return None;
}
self.fw_preset_ips = supporting.iter().map(|r| r.ip.clone()).collect();
self.fw_preset_names = common.iter().map(|p| p.name.clone()).collect();
let n = self.fw_preset_ips.len();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Set profile");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(dlg, &format!("Firmware profile for {n} miner(s):")),
0,
sf::BORDER_ALL,
8,
);
let choice = Widget::choice(dlg, ID_FWPRESET_CHOICE);
for p in &common {
let label = match &p.pretty {
Some(pretty) => format!("{} -- {pretty}", p.name),
None => p.name.clone(),
};
choice.choice_append(&label);
}
choice.choice_set_selection(0);
choice.set_min_size(340, -1);
root.add(choice, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Apply", ID_FWPRESET_OK), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_FWPRESET_CANCEL), 0, sf::BORDER_ALL, 6);
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
root.set_sizer_on(dlg);
dlg.set_min_size(420, -1);
dlg.fit(dlg);
self.fw_preset_dialog = dlg;
self.fw_preset_choice = choice;
Some(dlg)
}
/// Apply the selected firmware profile to the captured targets (round 18 / G3).
fn apply_fw_preset(&mut self) {
let sel = self.fw_preset_choice.choice_get_selection();
let Some(name) = usize::try_from(sel)
.ok()
.and_then(|i| self.fw_preset_names.get(i))
.cloned()
else {
wx_rs::set_status_text("select a profile");
return;
};
let ips = std::mem::take(&mut self.fw_preset_ips);
self.fw_preset_dialog.close(1);
self.start_action(ips, scan::ConfigAction::Preset(name));
}
/// Strong typed confirmation before flashing firmware to hardware: the /// Strong typed confirmation before flashing firmware to hardware: the
/// operator must type FLASH exactly, on top of seeing the image's file /// operator must type FLASH exactly, on top of seeing the image's file
/// name and how many of the selected miners actually support it. Built /// name and how many of the selected miners actually support it. Built
@@ -3847,6 +4036,12 @@ impl App {
} }
ID_POOLS_OK => self.apply_pools(), ID_POOLS_OK => self.apply_pools(),
ID_POOLS_CANCEL => self.pools_dialog.close(0), ID_POOLS_CANCEL => self.pools_dialog.close(0),
// Pool-preset manager buttons (round 18 #8b).
ID_POOL_PRESETS_SAVE => self.apply_pool_presets(),
ID_POOL_PRESETS_CANCEL => self.pool_presets_dialog.close(0),
// Firmware profile/preset selector buttons (round 18 / G3).
ID_FWPRESET_OK => self.apply_fw_preset(),
ID_FWPRESET_CANCEL => self.fw_preset_dialog.close(0),
// Pool-field "+" dropdown buttons (round 15 #1). // Pool-field "+" dropdown buttons (round 15 #1).
id if (ID_POOL_PLUS_BASE..ID_POOL_PLUS_BASE + 12).contains(&id) => { id if (ID_POOL_PLUS_BASE..ID_POOL_PLUS_BASE + 12).contains(&id) => {
self.open_pool_dropdown((id - ID_POOL_PLUS_BASE) as usize); self.open_pool_dropdown((id - ID_POOL_PLUS_BASE) as usize);
@@ -0,0 +1,159 @@
Subject: [PATCH 0022] luxminer: named presets + set_tuning_config (roadmap G3)
LuxOS tunes by discrete named profiles. This exposes them as first-class
presets and wires the structured tuning-config setter, so the toolkit can list
and select a profile (not only map a watts number onto one via SetPowerLimit).
- SupportsPresets: supports_presets()=true and get_presets() reads the live
`profiles` RPC into PresetInfo{name, pretty="<W> W ~ <TH> TH @ <MHz> MHz",
status=IsTuned?tuned:untuned}. Never hardcoded -- the step list varies by
model and tune state. New helper parse_profiles_to_presets + unit test.
- SupportsTuningConfig: supports_tuning_config()=true and set_tuning_config
handles Preset(name) -> profileset(name) (the same privileged RPC set_power_limit
already uses, proven in patch 0017) and Power(w) -> set_power_limit; hashrate /
mining-mode / manual targets are refused with clear messages.
Verified live (read) on two production LuxOS S19j Pro (10.4.1.60 / .67): the
profile ladders and supports_tuning_config=true are reported correctly. The
write path reuses the already-proven profileset(name) call; per the parity
roadmap, LuxOS profile writes are bench-only (never on the .60/.67 production
units), so the setter is not exercised against them here.
diff --git a/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs b/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs
index a4db1e03..b5a5a73c 100644
--- a/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs
+++ b/vendor/asic-rs-firmwares-luxminer/src/backends/v1/mod.rs
@@ -5,6 +5,8 @@ use asic_rs_core::{
config::{
collector::{ConfigCollector, ConfigExtractor, ConfigField, ConfigLocation},
pools::{PoolConfig, PoolGroupConfig},
+ preset::PresetInfo,
+ tuning::TuningConfig,
},
data::{
board::{BoardData, ChipData, MinerControlBoard},
@@ -1102,6 +1104,38 @@ fn parse_profile_watts(profiles: &Value) -> Vec<(String, f64)> {
.unwrap_or_default()
}
+/// Parse a LuxOS `profiles` RPC reply into the firmware's tunable presets, one
+/// per dynamic profile (round 18 / roadmap G3). The `Profile Name` is the
+/// identifier `profileset` expects; the pretty string summarises the profile's
+/// watt / hashrate / frequency operating point, and `status` reflects `IsTuned`.
+fn parse_profiles_to_presets(profiles: &Value) -> Vec<PresetInfo> {
+ profiles
+ .get("PROFILES")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|p| {
+ let name = p.get("Profile Name").and_then(Value::as_str)?.to_string();
+ let watts = p.get("Watts").and_then(Value::as_f64);
+ let hashrate = p.get("Hashrate").and_then(Value::as_f64);
+ let freq = p.get("Frequency").and_then(Value::as_f64);
+ let pretty = match (watts, hashrate, freq) {
+ (Some(w), Some(h), Some(f)) => Some(format!("{w:.0} W ~ {h:.1} TH @ {f:.0} MHz")),
+ (Some(w), Some(h), None) => Some(format!("{w:.0} W ~ {h:.1} TH")),
+ (Some(w), None, _) => Some(format!("{w:.0} W")),
+ _ => None,
+ };
+ let status = p
+ .get("IsTuned")
+ .and_then(Value::as_bool)
+ .map(|t| if t { "tuned" } else { "untuned" }.to_string());
+ Some(PresetInfo { name, pretty, status })
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
/// Choose the LuxOS profile name to satisfy a watts power limit: the highest-watt
/// profile that does not exceed `target_w`, or -- when the target is below every
/// profile -- the lowest-watt profile. Returns None only when there are no
@@ -1284,7 +1318,38 @@ impl Validate for LuxMinerV1 {
#[async_trait]
impl SupportsTuningConfig for LuxMinerV1 {
fn supports_tuning_config(&self) -> bool {
- false
+ true
+ }
+
+ /// LuxOS tunes by named profile (roadmap G3). A `Preset` target is applied
+ /// straight through `profileset`; a `Power` target reuses the watts->profile
+ /// mapping in `set_power_limit`. LuxOS has no hashrate/mining-mode targets and
+ /// per-board manual tuning is not wired, so those targets are refused.
+ async fn set_tuning_config(
+ &self,
+ config: TuningConfig,
+ _scaling_config: Option<asic_rs_core::config::scaling::ScalingConfig>,
+ ) -> anyhow::Result<bool> {
+ match config.target {
+ TuningTarget::Preset(name) => {
+ let resp = self.rpc.profileset(&name).await?;
+ Ok(resp
+ .pointer("/STATUS/0/STATUS")
+ .and_then(Value::as_str)
+ .map(|s| matches!(s, "S" | "I"))
+ .unwrap_or(true))
+ }
+ TuningTarget::Power(p) => self.set_power_limit(p).await,
+ TuningTarget::HashRate(_) => {
+ anyhow::bail!("LuxOS does not tune by hashrate target; select a named profile")
+ }
+ TuningTarget::MiningMode(_) => {
+ anyhow::bail!("LuxOS has no mining modes; select a named profile")
+ }
+ TuningTarget::Manual { .. } => {
+ anyhow::bail!("Per-board manual tuning is not wired for LuxOS")
+ }
+ }
}
}
@@ -1299,7 +1364,21 @@ impl SupportsTemperatureConfig for LuxMinerV1 {}
impl GetTuningPercent for LuxMinerV1 {}
impl SetTuningPercent for LuxMinerV1 {}
-impl SupportsPresets for LuxMinerV1 {}
+#[async_trait]
+impl SupportsPresets for LuxMinerV1 {
+ fn supports_presets(&self) -> bool {
+ true
+ }
+
+ /// The firmware's tunable profiles, read live from the `profiles` RPC (roadmap
+ /// G3). Never hardcoded -- the step list varies by model and tune state.
+ async fn get_presets(&self) -> Vec<PresetInfo> {
+ match self.rpc.profiles().await {
+ Ok(profiles) => parse_profiles_to_presets(&profiles),
+ Err(_) => Vec::new(),
+ }
+ }
+}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
@@ -1361,6 +1440,22 @@ mod tests {
assert!(select_profile_at_or_below(&parsed, 2500.0).is_some());
}
+ #[test]
+ fn profiles_parse_to_presets() {
+ // The `profiles` reply becomes one PresetInfo per profile (roadmap G3).
+ let profiles: Value = serde_json::from_str(PROFILES).unwrap();
+ let presets = parse_profiles_to_presets(&profiles);
+ assert_eq!(presets.len(), 25, "one preset per fixture profile");
+ // The factory point is named "default"; its pretty string carries the
+ // watt / hashrate / frequency operating point.
+ let default = presets.iter().find(|p| p.name == "default").unwrap();
+ assert_eq!(default.pretty.as_deref(), Some("2794 W ~ 121.8 TH @ 590 MHz"));
+ // IsTuned maps to the status string.
+ let tuned = presets.iter().find(|p| p.name == "290MHz").unwrap();
+ assert_eq!(tuned.status.as_deref(), Some("tuned"));
+ assert_eq!(default.status.as_deref(), Some("untuned"));
+ }
+
#[tokio::test]
async fn test_luxminer_v1() -> anyhow::Result<()> {
@@ -335,14 +335,15 @@ int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
if (h < 8) h = 8; if (h < 8) h = 8;
int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h; int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h;
if (w < 1) w = 1; if (w < 1) w = 1;
// The Font Awesome fan glyph fills its square box more than the other health // The Font Awesome fan and brain glyphs fill their square box more than the
// icons (brain/chip/bolt), so at the shared size it reads as oversized. Draw // other health icons (chip/bolt), so at the shared size they read as oversized.
// it a bit smaller, centred in its full-size slot, so the slot advance and the // Draw them a bit smaller, centred in their full-size slot, so the slot advance
// per-icon tooltip hit-test (both keyed to the full width) are unchanged // and the per-icon tooltip hit-test (both keyed to the full width) are
// (round 17 R1). // unchanged (round 17 R1; round 18 #1 brain).
int dw = w, dh = h; int dw = w, dh = h;
if (shape == SHAPE_FAN) { double glyph_scale = (shape == SHAPE_FAN) ? 0.80 : (shape == SHAPE_BRAIN) ? 0.82 : 1.0;
dh = (int)(h * 0.80 + 0.5); if (glyph_scale < 1.0) {
dh = (int)(h * glyph_scale + 0.5);
if (dh < 8) dh = 8; if (dh < 8) dh = 8;
dw = (sv->vbh > 0) ? (int)((double)dh * sv->vbw / sv->vbh + 0.5) : dh; dw = (sv->vbh > 0) ? (int)((double)dh * sv->vbw / sv->vbh + 0.5) : dh;
if (dw < 1) dw = 1; if (dw < 1) dw = 1;
@@ -982,6 +983,17 @@ static gboolean dvlc_query_tooltip(GtkWidget* tv, gint x, gint y, gboolean keybo
if (slot >= (int)iit->second.size()) slot = (int)iit->second.size() - 1; if (slot >= (int)iit->second.size()) slot = (int)iit->second.size() - 1;
const wxString& tip = iit->second[(size_t)slot]; const wxString& tip = iit->second[(size_t)slot];
if (tip.IsEmpty()) return FALSE; if (tip.IsEmpty()) return FALSE;
// Scope the tooltip's "tip area" to just this icon's slot (round 18 #4a).
// Without a tip area GTK defaults it to the whole widget, so it never re-queries
// or moves the tooltip as the pointer crosses from one icon to the next -- the
// old tooltip just stays put with stale text. Setting a per-slot area makes GTK
// hide + re-show + reposition the tooltip for each icon.
GdkRectangle area;
area.x = crect.x + slot * adv;
area.y = crect.y;
area.width = adv;
area.height = crect.height;
gtk_tooltip_set_tip_area(tooltip, &area);
gtk_tooltip_set_text(tooltip, tip.utf8_str()); gtk_tooltip_set_text(tooltip, tip.utf8_str());
return TRUE; return TRUE;
} }
@@ -1279,6 +1291,23 @@ void wxbr_dvlc_autosize_col(void* win, int pos) {
if (c) c->SetWidth(wxCOL_WIDTH_AUTOSIZE); if (c) c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
} }
// Size a column to fit its content + header, then clamp to cap_px so the default
// width is min(reasonable cap, content-fit) -- a short column shrinks to its
// content, a long one is capped at the caller's sensible default (round 18 #10).
// A small floor keeps a column from collapsing to nothing.
void wxbr_dvlc_autosize_col_capped(void* win, int pos, int cap_px) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (pos < 0 || (unsigned)pos >= dv->GetColumnCount()) return;
wxDataViewColumn* c = dv->GetColumn((unsigned)pos);
if (!c) return;
c->SetWidth(wxCOL_WIDTH_AUTOSIZE);
int w = c->GetWidth();
const int floor_px = 24;
if (w < floor_px) w = floor_px;
if (cap_px > 0 && w > cap_px) w = cap_px;
c->SetWidth(w);
}
// Update a column's header text in place (creation index) without recreating // Update a column's header text in place (creation index) without recreating
// the control -- used to refresh the ASCII sort marker on a sort click. // the control -- used to refresh the ASCII sort marker on a sort click.
void wxbr_dvlc_set_col_title(void* win, int col, const char* title) { void wxbr_dvlc_set_col_title(void* win, int col, const char* title) {
+7
View File
@@ -68,6 +68,7 @@ mod notsafe {
pub fn wxbr_dvlc_get_cell(win: *mut c_void, row: usize, col: usize, buf: *mut c_char, cap: c_int) -> c_int; pub fn wxbr_dvlc_get_cell(win: *mut c_void, row: usize, col: usize, buf: *mut c_char, cap: c_int) -> c_int;
pub fn wxbr_dvlc_col_count(win: *mut c_void) -> c_int; pub fn wxbr_dvlc_col_count(win: *mut c_void) -> c_int;
pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int); pub fn wxbr_dvlc_autosize_col(win: *mut c_void, pos: c_int);
pub fn wxbr_dvlc_autosize_col_capped(win: *mut c_void, pos: c_int, cap_px: c_int);
pub fn wxbr_dvlc_set_col_title(win: *mut c_void, col: c_int, title: *const c_char); pub fn wxbr_dvlc_set_col_title(win: *mut c_void, col: c_int, title: *const c_char);
pub fn wxbr_dvlc_set_sort_indicator(win: *mut c_void, col: c_int, active: c_int, ascending: c_int); pub fn wxbr_dvlc_set_sort_indicator(win: *mut c_void, col: c_int, active: c_int, ascending: c_int);
pub fn wxbr_dvlc_col_at_pos(win: *mut c_void, pos: c_int) -> c_int; pub fn wxbr_dvlc_col_at_pos(win: *mut c_void, pos: c_int) -> c_int;
@@ -647,6 +648,12 @@ impl Widget {
unsafe { notsafe::wxbr_dvlc_autosize_col(self.0, pos as c_int) } unsafe { notsafe::wxbr_dvlc_autosize_col(self.0, pos as c_int) }
} }
/// Size the column at display position `pos` to its content, then clamp to
/// `cap_px`: the width becomes min(cap, content-fit) (round 18 #10).
pub fn dvlc_autosize_col_capped(&self, pos: usize, cap_px: i32) {
unsafe { notsafe::wxbr_dvlc_autosize_col_capped(self.0, pos as c_int, cap_px) }
}
/// Model column index shown at display position `pos` (after drag reorder). /// Model column index shown at display position `pos` (after drag reorder).
pub fn dvlc_col_at_pos(&self, pos: usize) -> Option<usize> { pub fn dvlc_col_at_pos(&self, pos: usize) -> Option<usize> {
let v = unsafe { notsafe::wxbr_dvlc_col_at_pos(self.0, pos as c_int) }; let v = unsafe { notsafe::wxbr_dvlc_col_at_pos(self.0, pos as c_int) };
+1 -1
View File
@@ -1 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"fe8effe2bfdda5d4c390656c016729f531a2b1c60033228557659c0befdde9f2","Cargo.lock":"a2b2cb45bb8b574e4f29ffdcdb5ebafd1dd87a0e6e11b47383973a99be367784","Cargo.toml":"503efa00123f8567f5fe40bf6a93e9e453d13094df0e0e1b7e98bdacdfbd2595","Cargo.toml.orig":"1c4ba0315fb491c086fc22a5c9bafaf7288c6b1fd48679c3d03dbd9df156a8b5","src/backends/mod.rs":"548d988b877410e330a55e275f64b2adad95ca5f1a0f085fe144957c96b8906f","src/backends/v1/mod.rs":"0c12f7714b8486372054261afd263b61f432a446cef8ae9e6cd72550a0cf4f8f","src/backends/v1/rpc.rs":"25b0b9d56fbf113d5b8c3d3bc8eb7a0d67967b1f90f6d855da0b9f6ff24ae335","src/firmware.rs":"d95345295ae5043dfc357e69ae56c564b261fdb3b19b5c0ad1765267ff05ab3f","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"24191681066d5cf6a3022ad59c1baa92b57e3ce7717bb78d6a682af9e19a38c4","src/test/json/v1/config.json":"6ca9e6217d853d4bf1e75d69159630e9c9184ede96751706b88dfb699b5d59ad","src/test/json/v1/devs.json":"8f746dc6a02953eee5ee96dcf53be8dc7880a8ffc2c6e303f0284bcf6a97f42d","src/test/json/v1/events.json":"913683ff97af3333018807e1cc6e43467ea8a55925e5964dc402616615e2a5e3","src/test/json/v1/fans.json":"f8a9a1234d651055c80f4ebb1380bbb4e6d19eb33012902c55fff1385e592447","src/test/json/v1/healthchipget_0.json":"10619460049333ca016b2beec59ecc514ed9077fb19bdf7d0ed697201f8cb96c","src/test/json/v1/healthchipget_1.json":"80927fb1480c95be7f3a4e155d63f68f97720530ff7cf5d5ade06f2a3e810bf0","src/test/json/v1/healthchipget_2.json":"1e93ee2ab472ee7af58add08b4251e3ce0ad4f986d4325abbf43fd4c9b3dd28f","src/test/json/v1/mod.rs":"5a050f07455e622e35ad79ab1c8a6daf2ea38c4198472e49c6bbfe80538a9e48","src/test/json/v1/pools.json":"0068745327e31853fec051172abb7337f18a4cf9972c51967113d63f4f31f504","src/test/json/v1/power.json":"80534bb4581de7c8b747bf33b5d629b909c6e16a531d18ecb4afd7ffad3f014f","src/test/json/v1/profiles.json":"1f00429036e270daa08f12cd2d7357135070c57acd7a899a3c0af6167fe82abb","src/test/json/v1/stats.json":"2b105f0eb927046c9d2389bde978a43e3d54d12a420dfbe400786bb2f0ae31ca","src/test/json/v1/summary.json":"aaea3378eb7040952037e2f1ef7bd5f20a1b242bf93d4ba0501c46104b0b31a0","src/test/json/v1/temps.json":"1ee781cd2be3ed6a6a07e23be930248735fb51348c160453ba10f6ef71fcb7f1","src/test/json/v1/version.json":"4beb6ca5c0ebf359cee0434fdcc4d0a1a0607436634e46be3fd951e2256595df","src/test/json/v1/voltageget_0.json":"c445fa8674c2542b2d296fbafdd3166c53008dfbd9da8095327217989d37f1da","src/test/json/v1/voltageget_1.json":"96b91c3447dd66e7f1f575ed3b99611062e8b1d516d31422b74e425c46b2f49c","src/test/json/v1/voltageget_2.json":"7d40544021b2e32401135ae333067b770d2d736ada9e60deaca8fd8f5a79a1e3","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"513792d93a2a21d5258d9e6ac0e6dc9e0a6365118934514b4e656792add78066"} {"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"fe8effe2bfdda5d4c390656c016729f531a2b1c60033228557659c0befdde9f2","Cargo.lock":"a2b2cb45bb8b574e4f29ffdcdb5ebafd1dd87a0e6e11b47383973a99be367784","Cargo.toml":"503efa00123f8567f5fe40bf6a93e9e453d13094df0e0e1b7e98bdacdfbd2595","Cargo.toml.orig":"1c4ba0315fb491c086fc22a5c9bafaf7288c6b1fd48679c3d03dbd9df156a8b5","src/backends/mod.rs":"548d988b877410e330a55e275f64b2adad95ca5f1a0f085fe144957c96b8906f","src/backends/v1/mod.rs":"abcf1ffb8443efa70838489b026730ac19de774ba9e6f7c9a9800e3ba03c06a4","src/backends/v1/rpc.rs":"25b0b9d56fbf113d5b8c3d3bc8eb7a0d67967b1f90f6d855da0b9f6ff24ae335","src/firmware.rs":"d95345295ae5043dfc357e69ae56c564b261fdb3b19b5c0ad1765267ff05ab3f","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"24191681066d5cf6a3022ad59c1baa92b57e3ce7717bb78d6a682af9e19a38c4","src/test/json/v1/config.json":"6ca9e6217d853d4bf1e75d69159630e9c9184ede96751706b88dfb699b5d59ad","src/test/json/v1/devs.json":"8f746dc6a02953eee5ee96dcf53be8dc7880a8ffc2c6e303f0284bcf6a97f42d","src/test/json/v1/events.json":"913683ff97af3333018807e1cc6e43467ea8a55925e5964dc402616615e2a5e3","src/test/json/v1/fans.json":"f8a9a1234d651055c80f4ebb1380bbb4e6d19eb33012902c55fff1385e592447","src/test/json/v1/healthchipget_0.json":"10619460049333ca016b2beec59ecc514ed9077fb19bdf7d0ed697201f8cb96c","src/test/json/v1/healthchipget_1.json":"80927fb1480c95be7f3a4e155d63f68f97720530ff7cf5d5ade06f2a3e810bf0","src/test/json/v1/healthchipget_2.json":"1e93ee2ab472ee7af58add08b4251e3ce0ad4f986d4325abbf43fd4c9b3dd28f","src/test/json/v1/mod.rs":"5a050f07455e622e35ad79ab1c8a6daf2ea38c4198472e49c6bbfe80538a9e48","src/test/json/v1/pools.json":"0068745327e31853fec051172abb7337f18a4cf9972c51967113d63f4f31f504","src/test/json/v1/power.json":"80534bb4581de7c8b747bf33b5d629b909c6e16a531d18ecb4afd7ffad3f014f","src/test/json/v1/profiles.json":"1f00429036e270daa08f12cd2d7357135070c57acd7a899a3c0af6167fe82abb","src/test/json/v1/stats.json":"2b105f0eb927046c9d2389bde978a43e3d54d12a420dfbe400786bb2f0ae31ca","src/test/json/v1/summary.json":"aaea3378eb7040952037e2f1ef7bd5f20a1b242bf93d4ba0501c46104b0b31a0","src/test/json/v1/temps.json":"1ee781cd2be3ed6a6a07e23be930248735fb51348c160453ba10f6ef71fcb7f1","src/test/json/v1/version.json":"4beb6ca5c0ebf359cee0434fdcc4d0a1a0607436634e46be3fd951e2256595df","src/test/json/v1/voltageget_0.json":"c445fa8674c2542b2d296fbafdd3166c53008dfbd9da8095327217989d37f1da","src/test/json/v1/voltageget_1.json":"96b91c3447dd66e7f1f575ed3b99611062e8b1d516d31422b74e425c46b2f49c","src/test/json/v1/voltageget_2.json":"7d40544021b2e32401135ae333067b770d2d736ada9e60deaca8fd8f5a79a1e3","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"513792d93a2a21d5258d9e6ac0e6dc9e0a6365118934514b4e656792add78066"}
+97 -2
View File
@@ -5,6 +5,8 @@ use asic_rs_core::{
config::{ config::{
collector::{ConfigCollector, ConfigExtractor, ConfigField, ConfigLocation}, collector::{ConfigCollector, ConfigExtractor, ConfigField, ConfigLocation},
pools::{PoolConfig, PoolGroupConfig}, pools::{PoolConfig, PoolGroupConfig},
preset::PresetInfo,
tuning::TuningConfig,
}, },
data::{ data::{
board::{BoardData, ChipData, MinerControlBoard}, board::{BoardData, ChipData, MinerControlBoard},
@@ -1102,6 +1104,38 @@ fn parse_profile_watts(profiles: &Value) -> Vec<(String, f64)> {
.unwrap_or_default() .unwrap_or_default()
} }
/// Parse a LuxOS `profiles` RPC reply into the firmware's tunable presets, one
/// per dynamic profile (round 18 / roadmap G3). The `Profile Name` is the
/// identifier `profileset` expects; the pretty string summarises the profile's
/// watt / hashrate / frequency operating point, and `status` reflects `IsTuned`.
fn parse_profiles_to_presets(profiles: &Value) -> Vec<PresetInfo> {
profiles
.get("PROFILES")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|p| {
let name = p.get("Profile Name").and_then(Value::as_str)?.to_string();
let watts = p.get("Watts").and_then(Value::as_f64);
let hashrate = p.get("Hashrate").and_then(Value::as_f64);
let freq = p.get("Frequency").and_then(Value::as_f64);
let pretty = match (watts, hashrate, freq) {
(Some(w), Some(h), Some(f)) => Some(format!("{w:.0} W ~ {h:.1} TH @ {f:.0} MHz")),
(Some(w), Some(h), None) => Some(format!("{w:.0} W ~ {h:.1} TH")),
(Some(w), None, _) => Some(format!("{w:.0} W")),
_ => None,
};
let status = p
.get("IsTuned")
.and_then(Value::as_bool)
.map(|t| if t { "tuned" } else { "untuned" }.to_string());
Some(PresetInfo { name, pretty, status })
})
.collect()
})
.unwrap_or_default()
}
/// Choose the LuxOS profile name to satisfy a watts power limit: the highest-watt /// Choose the LuxOS profile name to satisfy a watts power limit: the highest-watt
/// profile that does not exceed `target_w`, or -- when the target is below every /// profile that does not exceed `target_w`, or -- when the target is below every
/// profile -- the lowest-watt profile. Returns None only when there are no /// profile -- the lowest-watt profile. Returns None only when there are no
@@ -1284,7 +1318,38 @@ impl Validate for LuxMinerV1 {
#[async_trait] #[async_trait]
impl SupportsTuningConfig for LuxMinerV1 { impl SupportsTuningConfig for LuxMinerV1 {
fn supports_tuning_config(&self) -> bool { fn supports_tuning_config(&self) -> bool {
false true
}
/// LuxOS tunes by named profile (roadmap G3). A `Preset` target is applied
/// straight through `profileset`; a `Power` target reuses the watts->profile
/// mapping in `set_power_limit`. LuxOS has no hashrate/mining-mode targets and
/// per-board manual tuning is not wired, so those targets are refused.
async fn set_tuning_config(
&self,
config: TuningConfig,
_scaling_config: Option<asic_rs_core::config::scaling::ScalingConfig>,
) -> anyhow::Result<bool> {
match config.target {
TuningTarget::Preset(name) => {
let resp = self.rpc.profileset(&name).await?;
Ok(resp
.pointer("/STATUS/0/STATUS")
.and_then(Value::as_str)
.map(|s| matches!(s, "S" | "I"))
.unwrap_or(true))
}
TuningTarget::Power(p) => self.set_power_limit(p).await,
TuningTarget::HashRate(_) => {
anyhow::bail!("LuxOS does not tune by hashrate target; select a named profile")
}
TuningTarget::MiningMode(_) => {
anyhow::bail!("LuxOS has no mining modes; select a named profile")
}
TuningTarget::Manual { .. } => {
anyhow::bail!("Per-board manual tuning is not wired for LuxOS")
}
}
} }
} }
@@ -1299,7 +1364,21 @@ impl SupportsTemperatureConfig for LuxMinerV1 {}
impl GetTuningPercent for LuxMinerV1 {} impl GetTuningPercent for LuxMinerV1 {}
impl SetTuningPercent for LuxMinerV1 {} impl SetTuningPercent for LuxMinerV1 {}
impl SupportsPresets for LuxMinerV1 {} #[async_trait]
impl SupportsPresets for LuxMinerV1 {
fn supports_presets(&self) -> bool {
true
}
/// The firmware's tunable profiles, read live from the `profiles` RPC (roadmap
/// G3). Never hardcoded -- the step list varies by model and tune state.
async fn get_presets(&self) -> Vec<PresetInfo> {
match self.rpc.profiles().await {
Ok(profiles) => parse_profiles_to_presets(&profiles),
Err(_) => Vec::new(),
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -1361,6 +1440,22 @@ mod tests {
assert!(select_profile_at_or_below(&parsed, 2500.0).is_some()); assert!(select_profile_at_or_below(&parsed, 2500.0).is_some());
} }
#[test]
fn profiles_parse_to_presets() {
// The `profiles` reply becomes one PresetInfo per profile (roadmap G3).
let profiles: Value = serde_json::from_str(PROFILES).unwrap();
let presets = parse_profiles_to_presets(&profiles);
assert_eq!(presets.len(), 25, "one preset per fixture profile");
// The factory point is named "default"; its pretty string carries the
// watt / hashrate / frequency operating point.
let default = presets.iter().find(|p| p.name == "default").unwrap();
assert_eq!(default.pretty.as_deref(), Some("2794 W ~ 121.8 TH @ 590 MHz"));
// IsTuned maps to the status string.
let tuned = presets.iter().find(|p| p.name == "290MHz").unwrap();
assert_eq!(tuned.status.as_deref(), Some("tuned"));
assert_eq!(default.status.as_deref(), Some("untuned"));
}
#[tokio::test] #[tokio::test]
async fn test_luxminer_v1() -> anyhow::Result<()> { async fn test_luxminer_v1() -> anyhow::Result<()> {