Compare commits

...
11 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 a6d286a147 GUI round 12 (#12): scan miner logs over the firmware API (PIC + metrics)
Adds a right-click "View log (API)..." action that fetches a miner's log through
its firmware API and regex-scans it -- the "logs through API" path for PIC
detection and other metrics without SSH.

Per firmware (crates/alkane-gui/src/log_scan.rs, curl-based like the access
probe, stdout drained on a thread so a large log never deadlocks the pipe):
- VNish: POST /api/v1/unlock -> bearer -> GET /api/v1/logs/miner (the full miner
  log: PSU init, per-chain chip detection, tuning, errors).
- Stock Antminer: GET /cgi-bin/log.cgi (digest); older models (Z15) that do not
  serve it are reported as "no log over its web API".
- WhatsMiner: get_error_code on :4028 (unauthenticated) formatted as the log.

The summary regex reports PIC status ("not present (no-PIC miner)" / "present --
<version line>"), the latest per-chain chip-detection line, and recent errors
from the log history. Creds reuse the round 12 #13 per-firmware defaults (VNish
password, else "admin"; Antminer web login from the saved global creds).

Verified live: VNish S19j Pro (10.7.1.25) log -> "PIC: not present (log reports a
no-PIC miner)" + chains + recent errors; WhatsMiner (10.8.1.45) -> its active
error codes; Z15 (10.5.1.196) -> honest "no log over its web API". Unit tests for
the summary + a headless ALKANE_LOG_SCAN diagnostic; self-test passes.

Note: WhatsMiner fault codes already surface in the Errors column via asic-rs's
get_error_code -> messages; this adds the raw-log view and the PIC scan on top.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-20 10:54:52 -06:00
noahandClaude Opus 4.8 3ba3211371 GUI round 12 (#8b, part 1): correct WhatsMiner lock/access with the :4028 token API
WhatsMiners were shown "locked/unauthenticated" even with their default login.
Two causes, both fixed:

- The access probe hit an Antminer-only endpoint (/cgi-bin/get_miner_conf.cgi via
  curl --digest) for EVERY make; WhatsMiners answer 307 there, so the check was
  always indeterminate. Added a real WhatsMiner check over its :4028 token API:
  get_token (unauthenticated) -> derive the AES key from the password (md5crypt +
  SHA256, the same scheme the vendored asic-rs whatsminer backend uses) -> send a
  NON-mutating encrypted `summary`. An encrypted reply means the password was
  accepted (unlocked); a plaintext "enc json load err" means rejected (locked).
  probe_access now branches on the miner brand. Candidate passwords: a per-firmware
  override (round 12 #13) if set, else the factory defaults admin (V1/V2) and super
  (V3); all attempts are non-mutating so trying both is safe.
- The scan-time lock guess (!caps.any_control()) falsely marked older WhatsMiners
  locked because they route to the asic-rs V1 backend, which declares no control
  commands even though the miner is controllable via the token API. WhatsMiner
  lock state is now left unknown at scan time and decided by the real probe.

Live-verified on the fleet: older 20220422.18.REL units (10.8.1.176, 10.7.1.196)
and newer M30S+ (10.8.1.45) all report UNLOCKED with the default admin login;
the Antminer digest path is unchanged (Z15 -> 200 with root/root -> unlocked).
Added a headless `ALKANE_ACCESS_PROBE="<ip> <make>"` diagnostic and a
deterministic AES unit test. Self-test passes.

Note: this is the access/lock half of #8b. Implementing the full reverse-
engineered WhatsMiner command set (control + monitoring over the token API) is
tracked separately.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-20 09:29:43 -06:00
noahandClaude Opus 4.8 c8d5cd71c4 GUI round 12 (#10): Z15 realtime hashrate + control board, from data we can read
Stock Antminer Z15/Z15J were mis-handled: their control board showed blank and
their realtime hashrate looked absent next to the target. Root cause: the version
detector only read summary.cgi, which the Z15 does not serve (404), so version
detection returned nothing and AntMiner::new fell through to the newest backend,
which mis-parsed the miner. Fixes (all in the vendored asic-rs antminer crate,
verified live on 10.5.1.x):

- Backend routing: fall back to the cgminer :4028 `version` RPC's CompileTime when
  summary.cgi is absent, so a 2020 Z15 routes to the v2020 backend instead of the
  default newest one.
- Control board "read, not guess": the Z15 has no miner_type.cgi, so read the
  control board from the kernel build string in get_system_info.cgi
  ("Linux 4.6.0-xilinx-..." -> Xilinx). The ControlBoardVersion field now carries
  both the subtype and the kernel; the parser prefers the explicit subtype and
  falls back to the kernel marker (xilinx/zynq -> Xilinx, aml/meson -> AMLogic).
- Malformed cgminer stats: the Z15 emits a stats array with no commas between its
  objects (invalid JSON serde rejected, which dropped every stats-derived field).
  Insert the missing separators before parsing (a no-op on valid responses),
  restoring expected hashrate, fans, hashboards and uptime. Expected hashrate now
  gets the same Equihash Sol/s reinterpretation as the realtime rate, so both read
  on one scale (e.g. 144k / 320k) instead of expected reading ~1e6x larger.

Live result: Z15/Z15J now report control board "Xilinx" and realtime/expected
hashrate on the same scale. asic-rs antminer crate tests (35) pass; GUI self-test
passes. Vendored source + refreshed checksum committed; patch queue adds 0006.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-20 08:59:53 -06:00
noahandClaude Opus 4.8 c74e8ebaca GUI round 12 (#6): fade the locate-light dot in and out
The Light column's flashing-light dot now pulses (fades between ~30% and 100%
opacity over a ~1.6 s cycle) instead of sitting static, so a flashing locate
light reads as live.

- A distinct SHAPE_PULSE_DOT sentinel marks the fading dot, so only the locate
  light pulses -- the hashboard health dots stay solid.
- A wxTimer in the bridge advances an animation phase and, each 100 ms tick, emits
  a row change so the custom cell renderer re-runs (a plain Refresh() does not
  re-invoke a custom renderer under wxGTK's cell caching); the renderer blends the
  dot toward its cell background by the phase. The timer runs only while a visible
  row's light is actually flashing -- fill_rows calls set_light_pulse(true/false)
  -- so there is no idle repaint loop.

Verified under Xvfb: with the fixture whose locate light flashes and the Light
column shown, the dot's measured intensity oscillates across frames (strong amber
to a pale tint and back); with no flashing light the timer stays stopped.
Self-test still passes. wx-rs patches 0002/0003 regenerated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-20 00:20:37 -06:00
noahandClaude Opus 4.8 282f0b195c GUI round 12 (#13): editable per-firmware default scan credentials
Adds a per-firmware default-login editor so the operator can set the discovery
credentials each firmware is probed with, rather than a single global pair.

- credentials.rs: a per-firmware store (firmware-credentials.txt, 0600, one
  "name<TAB>user<TAB>pass" line per firmware) keyed by the asic-rs firmware
  registry's Display name -- the same key the factory uses for
  with_firmware_discovery_auth. A firmware_default_creds() table seeds the editor
  with each firmware's shipped default (mirrors the asic-rs backends' default_auth
  constants; asic-rs does not expose them at the entry level).
- configured_factory() precedence is now: a per-firmware override wins; else the
  single global scan credential (unchanged back-compat) applies to every backend;
  else the backend's own default_auth. Nothing saved -> plain MinerFactory::new().
- UI: the "Set scan credentials..." dialog gains a "Per-firmware defaults..."
  button opening an editor that lists every firmware in the compiled-in registry
  (read at runtime, not hard-coded) with editable user/pass fields prefilled from
  the saved override or the shipped default. Save persists only rows that differ
  from the shipped default (so defaults evolve with asic-rs and the file stays
  minimal); Reset to defaults clears all overrides.

Verified under Xvfb: the editor lists all 16 registry firmwares with correct
default logins (AntMiner root/root, WhatsMiner admin/admin, VNish blank/admin,
UMC OS blank/letmein, ...). Round-trip/permissions/precedence covered by a unit
test (folded into the existing HOME-scoped credentials test to avoid a parallel
HOME race); self-test still passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-20 00:06:37 -06:00
noahandClaude Opus 4.8 1857a9e1a0 GUI round 12 (#9, #11): SVG icons in table cells (access padlocks + status)
Adds an SVG-backed icon path to the table's segment renderer: the Rust side
registers a raw SVG per shape sentinel (with its viewBox dims), and the renderer
recolours it to the cell's segment colour, rasterises once per (sentinel, colour,
height) and caches the bitmap. The recolour matches the KPI cards' svg_recolored
(replace currentColor + inject a root fill so fill-less SVGs inherit the colour).

- #9: the Access column padlocks now use the operator-supplied Font Awesome
  lock/unlock SVGs (red closed = view-only, green open = writable) instead of the
  hand-drawn vector padlock. The vector padlock remains as a fallback if the SVG
  is somehow unregistered.
- #11: the Status column renders its KPI icon (green rabbit = hashing, amber
  turtle = slow, red cracked wine glass = not hashing, blue otter = paused)
  instead of the status text, matching the dashboard cards. An unrecognised
  status still falls back to coloured text.

The status dots (hashboards, locate light) stay vector so the round-12 #6 fade
can drive them later. Self-test updated (Status is now a shape cell, verified
structurally like the other icon columns) and still passes. Verified under Xvfb:
the Access column shows the FA padlocks and, with the Status column enabled, the
four status icons render in their KPI colours. wx-rs patches 0002/0003
regenerated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-19 23:55:37 -06:00
noahandClaude Opus 4.8 b7a77cbed8 GUI round 12 (#7): batch multi-select in the Columns and Filter menus
Both list widgets now support Excel-style batch selection so several rows can be
toggled at once.

- Filter menu value list (wxCheckListBox): was wxLB_SINGLE, so only one value
  could ever be selected. Switched to wxLB_EXTENDED -- ctrl-click, shift-click
  and rubber-band drag now select a range of values. Clicking any selected
  row's checkbox applies that new checked state to every selected row.
- Columns menu list (wxListCtrl): already multi-select for the drag-reorder, but
  a checkbox toggle only affected the clicked row. A toggle on a row that is part
  of a multi-row selection now applies to every selected row, so several columns
  can be shown/hidden together. Re-entrancy guarded (CheckItem re-fires the
  event).

Verified under Xvfb by driving the real dialogs: ctrl-click selects several
columns and one checkbox click toggles them together; shift-click selects a
range of filter values and one checkbox click toggles them together. Headless
self-test still passes. wx-rs patch 0003 regenerated to match the edited bridge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-19 23:38:57 -06:00
noahandClaude Opus 4.8 606ae85781 GUI round 12 (#2): keep KPI units visible when the window shrinks
The two wide KPI cards (SHA-256 Hashrate, Est. power) carry a units-bearing
value like "685 TH" / "21.3 kW". When the window was narrowed the row squeezed
these cards below the width their value needs, clipping the trailing unit so it
read as "21.3" with no "kW". Two fixes:

- A nested wxPanel does not re-run its own sizer when its parent resizes it, so
  each card's value/label centring kept whatever slot width it had at the
  previous window size. on_resize now re-lays-out every card on each size event,
  so the value stays centred and gets its full best-size width allocation.
- Raise the wide-card minimum width (150 -> 176) to fit a ~20px icon + a value
  up to "118.0 PH" + the card's side inset, and derive the collapse threshold
  from the real per-card minimums. The wide cards now either show their full
  units or drop out of the row cleanly -- they never render a clipped value.

Verified under Xvfb: at 1050px all seven cards show "685 TH" / "21.3 kW" in
full; at 960px the two wide cards collapse and the five count cards fill the
row. Headless self-test still passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-19 23:29:36 -06:00
noahandClaude Opus 4.8 ad9b0dc868 GUI round 12 (batch 1): black hashrate value, Control Board label, blank placeholder serials, sensible WhatsMiner temps
- #1: the total-hashrate KPI value renders in the default (black) text colour
  instead of accent blue (and now dims with focus like the other neutral cards).
- #4: the board-code column header is now "Control Board".
- #5 (serial): placeholder serials ("N/A", "none", "null", ...) render as an
  empty cell instead of the literal placeholder.
- #3: the Chip-temp cell now prefers each board's board/PCB temperature over the
  hottest-chip (outlet) reading. WhatsMiner's outlet_chip is the max chip temp
  (verified live: ~100C on the hottest board of a M30S+ VE40) which read
  alarmingly high and didn't match the ~60-79C the miner itself reports; the
  board temperature is the figure the miner's UI shows. Falls back to the chip
  temp when no board temp is reported. Applies to all makes for consistency.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-19 23:02:39 -06:00
noahandClaude Opus 4.8 aaf049bbfc GUI round 11: use the exact potraced beehive for the Hashrate KPI icon
Replaced the hand-traced beehive with an exact potrace of the operator-supplied
beehive.png (parent miner-firmware folder): potrace -s on the flattened bilevel
bitmap, then the black fill rewritten to currentColor so it recolours to the
Hashrate accent. Renders correctly via wxBitmapBundle::FromSVG (nanosvg).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-19 22:26:02 -06:00
noahandClaude Opus 4.8 8b7b0c70b4 GUI round 11: hand-traced beehive KPI icon (Hashrate)
Replaced the placeholder skep with a beehive matching the operator's reference
(branch + hook on top, stacked pill bands, centre entrance), as an outline SVG
using stroke="currentColor" so it recolours to the Hashrate accent. Hand-traced
because a chat-pasted raster can't be reached as a file for potrace; if the
source raster is saved to disk later, it can be image-traced for an exact match.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-19 22:14:12 -06:00
21 changed files with 1849 additions and 113 deletions
Generated
+6
View File
@@ -76,13 +76,19 @@ dependencies = [
name = "alkane-gui"
version = "0.1.0"
dependencies = [
"aes",
"alkane-core",
"alkane-discovery",
"asic-rs",
"base64 0.21.7",
"ecb",
"futures-util",
"hex",
"md5crypt",
"measurements",
"serde",
"serde_json",
"sha2",
"tokio",
"wx-rs",
]
+8
View File
@@ -19,3 +19,11 @@ tokio = { version = "1", features = ["rt"] }
futures-util = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# WhatsMiner :4028 token-auth access check (round 12 #8b) -- same crates the
# vendored asic-rs whatsminer backend uses, so no new versions enter the lock.
md5crypt = "1"
sha2 = "0.10"
aes = "0.8"
ecb = "0.1"
base64 = "0.21"
hex = "0.4"
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><g fill="currentColor"><rect x="176" y="40" width="160" height="70" rx="35"/><rect x="128" y="130" width="256" height="70" rx="35"/><rect x="80" y="220" width="352" height="72" rx="36"/><rect x="48" y="312" width="416" height="80" rx="40"/></g></svg>
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="511.104248pt" height="512.144915pt" viewBox="0 0 511.104248 512.144915" preserveAspectRatio="xMidYMid meet"><g transform="translate(-0.500000,511.997478) scale(0.100000,-0.100000)" fill="currentColor" stroke="none"><path d="M82 5103 c-52 -25 -77 -69 -77 -133 0 -41 6 -63 22 -86 49 -68 -31 -64 1237 -64 l1146 0 0 -150 0 -150 -323 0 c-292 0 -332 -2 -403 -20 -201 -52 -370 -228 -414 -432 -8 -34 -11 -94 -8 -155 5 -90 12 -119 52 -214 6 -14 -9 -17 -121 -22 -142 -7 -205 -22 -304 -73 -123 -65 -229 -192 -272 -329 -33 -106 -30 -264 7 -360 15 -38 30 -77 32 -85 4 -12 -9 -20 -49 -33 -76 -24 -163 -83 -228 -156 -160 -176 -193 -424 -86 -638 61 -123 195 -242 315 -280 40 -13 52 -21 48 -33 -2 -8 -17 -46 -32 -85 -38 -95 -41 -253 -7 -360 56 -178 206 -323 393 -380 32 -9 108 -19 182 -22 l126 -6 -25 -66 c-31 -81 -42 -233 -23 -319 45 -210 221 -387 433 -437 94 -22 1622 -22 1716 0 108 26 188 71 272 155 126 125 176 255 167 437 -5 90 -12 119 -52 214 -6 14 9 17 122 22 147 6 246 33 337 92 110 70 199 186 238 310 33 106 30 264 -7 360 -15 39 -30 77 -32 85 -4 12 9 20 49 33 211 67 377 303 377 537 0 233 -167 470 -378 537 -40 13 -52 21 -48 33 2 8 17 47 32 85 37 96 40 254 7 360 -39 122 -130 241 -240 311 -89 58 -188 85 -335 91 -113 5 -128 8 -122 22 40 95 47 124 52 214 6 119 -7 184 -55 287 -46 97 -157 210 -254 257 -117 58 -159 63 -516 63 l-323 0 0 150 0 150 618 0 617 0 210 -211 c116 -116 227 -219 247 -230 122 -63 256 59 207 187 -5 16 -60 79 -121 141 l-112 113 313 0 c346 0 360 2 404 64 31 43 31 129 0 172 -50 70 173 64 -2535 64 -2230 0 -2446 -2 -2476 -17z m3337 -918 c94 -52 141 -134 141 -244 -1 -102 -60 -192 -155 -237 l-50 -24 -795 0 -795 0 -50 24 c-61 28 -116 87 -140 149 -26 70 -17 172 21 235 31 49 104 105 158 121 18 6 363 9 821 8 l790 -2 54 -30z m649 -834 c95 -43 162 -147 162 -251 0 -66 -30 -131 -85 -187 -84 -83 -84 -83 -593 -83 l-434 0 -55 50 c-281 257 -719 257 -1005 0 l-57 -51 -453 3 c-452 3 -453 3 -500 26 -92 45 -158 151 -158 252 0 119 99 235 221 259 24 5 688 8 1474 8 l1430 -2 53 -24z m-1317 -623 c130 -64 224 -184 249 -317 5 -29 10 -98 10 -151 0 -53 -5 -122 -10 -151 -25 -133 -119 -253 -249 -317 -73 -36 -77 -37 -191 -37 -114 0 -118 1 -191 37 -125 62 -210 164 -244 293 -20 79 -20 271 0 350 39 149 147 263 300 318 38 13 74 17 151 15 93 -3 107 -6 175 -40z m-924 -235 c-16 -51 -16 -415 0 -465 l11 -38 -547 0 -548 0 -62 31 c-87 43 -138 117 -148 213 -11 110 44 211 145 263 l64 33 548 0 548 0 -11 -37z m2580 24 c60 -22 117 -72 148 -128 26 -46 30 -64 30 -129 0 -65 -4 -83 -30 -129 -31 -56 -88 -106 -148 -128 -23 -8 -187 -12 -578 -12 l-546 -1 13 68 c17 86 17 318 0 405 l-13 67 546 -1 c391 0 555 -4 578 -12z m-2349 -878 c286 -256 725 -255 1006 1 l55 51 453 -3 c452 -3 453 -3 500 -26 90 -44 158 -151 158 -247 0 -99 -69 -204 -162 -246 l-53 -24 -1455 0 -1455 0 -53 24 c-95 43 -162 147 -162 251 0 66 30 131 85 187 83 82 79 81 588 82 l439 1 56 -51z m1342 -820 c97 -43 160 -138 160 -240 0 -111 -47 -192 -141 -244 l-54 -30 -783 -3 c-518 -2 -796 1 -822 8 -59 16 -131 70 -164 122 -38 63 -47 165 -21 235 24 62 79 121 140 149 l50 24 795 0 c778 0 796 -1 840 -21z"/></g></svg>

Before

Width:  |  Height:  |  Size: 313 B

After

Width:  |  Height:  |  Size: 3.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Pro 7.3.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2026 Fonticons, Inc. --><path fill="currentColor" d="M128 192l128 0 0-64c0-35.3-28.7-64-64-64s-64 28.7-64 64l0 64zm-64 0l0-64C64 57.3 121.3 0 192 0S320 57.3 320 128l0 64c35.3 0 64 28.7 64 64l0 192c0 35.3-28.7 64-64 64L64 512c-35.3 0-64-28.7-64-64L0 256c0-35.3 28.7-64 64-64zm256 64l-256 0 0 192 256 0 0-192z"/></svg>

After

Width:  |  Height:  |  Size: 522 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Pro 7.3.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2026 Fonticons, Inc. --><path fill="currentColor" d="M320 128c0-35.3 28.7-64 64-64s64 28.7 64 64l0 128 64 0 0-128C512 57.3 454.7 0 384 0S256 57.3 256 128l0 64-192 0c-35.3 0-64 28.7-64 64L0 448c0 35.3 28.7 64 64 64l256 0c35.3 0 64-28.7 64-64l0-192c0-35.3-28.7-64-64-64l0-64zM64 256l256 0 0 192-256 0 0-192z"/></svg>

After

Width:  |  Height:  |  Size: 520 B

+171 -6
View File
@@ -14,10 +14,29 @@
//! rather than add an HTTP+digest crate, so the offline/vendored build is
//! unaffected. `Some(true)` = locked, `Some(false)` = unlocked, `None` =
//! indeterminate (unreachable, or an endpoint/vendor this probe doesn't cover).
//!
//! WhatsMiner has no such digest-gated web endpoint (it returns a 307 redirect
//! for the Antminer paths, so the curl probe always read "indeterminate" and the
//! table fell back to a capability guess that marked older units "locked" even
//! with the default login -- round 12 #8b). Instead we run the WhatsMiner
//! :4028 token handshake: `get_token` (unauthenticated) yields a salt, we derive
//! the AES key from the password, and send a NON-mutating encrypted `summary`.
//! An encrypted reply means the key (hence password) was accepted -> unlocked;
//! a plaintext `enc json load err` means it was rejected -> locked.
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::process::Command;
use std::time::Duration;
use aes::Aes256;
use aes::cipher::{BlockEncryptMut, KeyInit, block_padding::ZeroPadding};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use sha2::{Digest, Sha256};
type Aes256EcbEnc = ecb::Encryptor<Aes256>;
/// Classify a miner's access state from an HTTP status code string (curl's
/// `%{http_code}` output). Conservative: anything other than a clear
/// authenticated/unauthorized answer is `None`.
@@ -35,12 +54,16 @@ fn endpoint(_firmware: &str) -> &'static str {
"/cgi-bin/get_miner_conf.cgi"
}
/// Probe one miner's access state over its web API with the given credentials.
/// Returns `Ok(Some(true/false))` on a decisive lock/unlock answer, `Ok(None)`
/// if reachable-but-indeterminate or a vendor this probe doesn't cover, or
/// `Err` only on a failure to run curl at all.
pub fn probe_access(ip: &str, firmware: &str, user: &str, pass: &str) -> Result<Option<bool>, String> {
let url = format!("http://{ip}{}", endpoint(firmware));
/// Probe one miner's access state. `make` is the miner brand ("Whatsminer" /
/// "Antminer"): WhatsMiner uses the :4028 token handshake, everything else the
/// digest-auth web probe. Returns `Ok(Some(true/false))` on a decisive
/// lock/unlock answer, `Ok(None)` if indeterminate, `Err` only on a probe that
/// could not run at all.
pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result<Option<bool>, String> {
if make.eq_ignore_ascii_case("whatsminer") {
return Ok(probe_whatsminer_access(ip, &whatsminer_password_candidates()));
}
let url = format!("http://{ip}{}", endpoint(make));
let userpass = format!("{user}:{pass}");
let mut cmd = Command::new("curl");
cmd.args([
@@ -96,6 +119,137 @@ fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process
}
}
/// Passwords to try for a WhatsMiner access check: a user-set per-firmware
/// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for
/// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe.
fn whatsminer_password_candidates() -> Vec<String> {
if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock") {
if !pass.is_empty() {
return vec![pass.clone()];
}
}
vec!["admin".to_string(), "super".to_string()]
}
/// Fetch a WhatsMiner's active fault codes over the unauthenticated :4028
/// get_error_code command and format them one per line for the log viewer
/// (round 12 #12). Returns None if the miner does not answer.
pub fn whatsminer_get_error_code(ip: &str) -> Option<String> {
let resp = wm_rpc(ip, "{\"command\":\"get_error_code\"}", Duration::from_secs(6)).ok()?;
let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
let codes = v.get("Msg").and_then(|m| m.get("error_code")).and_then(|c| c.as_array());
let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")];
match codes {
Some(arr) if !arr.is_empty() => {
for entry in arr {
if let Some(obj) = entry.as_object() {
for (code, when) in obj {
lines.push(format!(" error {code}: {}", when.as_str().unwrap_or("")));
}
}
}
}
_ => lines.push(" no active error codes".to_string()),
}
Some(lines.join("\n"))
}
/// One WhatsMiner :4028 request/response (the miner closes the socket after it
/// replies). Returns the NUL-trimmed body.
fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result<String, String> {
let addr: SocketAddr = format!("{ip}:4028")
.parse()
.map_err(|e| format!("bad address {ip}: {e}"))?;
let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| e.to_string())?;
stream.set_read_timeout(Some(timeout)).ok();
stream.set_write_timeout(Some(timeout)).ok();
stream.write_all(payload.as_bytes()).map_err(|e| e.to_string())?;
let mut buf = Vec::new();
let mut chunk = [0u8; 4096];
loop {
match stream.read(&mut chunk) {
Ok(0) => break,
Ok(n) => {
buf.extend_from_slice(&chunk[..n]);
if buf.len() > 1 << 20 {
break; // cap a runaway response
}
}
Err(_) => break,
}
}
Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string())
}
/// AES-256-ECB encrypt `data` under SHA256(pwd_md5), base64-encoded -- the exact
/// scheme the WhatsMiner btminer API expects (mirrors the vendored asic-rs
/// whatsminer v2 backend).
fn wm_aes_ecb_enc(pwd_md5: &str, data: &str) -> Option<String> {
let key = Sha256::digest(pwd_md5.as_bytes()); // 32 bytes
let mut buffer = data.as_bytes().to_vec();
while !buffer.len().is_multiple_of(16) {
buffer.push(0);
}
let ct = Aes256EcbEnc::new_from_slice(&key)
.ok()?
.encrypt_padded_mut::<ZeroPadding>(&mut buffer, data.len())
.ok()?;
Some(BASE64.encode(ct))
}
/// Check a WhatsMiner's access via the :4028 token handshake, trying each
/// candidate password. Returns `Some(false)` (unlocked) on the first password
/// the miner accepts, `Some(true)` (locked) if all are rejected, `None` if the
/// miner is unreachable or speaks an unexpected dialect. Non-mutating: only
/// `get_token` and a read-only `summary` are ever sent.
fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option<bool> {
let timeout = Duration::from_secs(6);
let mut reachable = false;
for pass in passwords {
// 1. get_token (no auth) -> salt / newsalt / time.
let tok_resp = match wm_rpc(ip, "{\"command\":\"get_token\"}", timeout) {
Ok(s) => s,
Err(_) => return None,
};
let v: serde_json::Value = match serde_json::from_str(&tok_resp) {
Ok(v) => v,
Err(_) => return None,
};
let Some(msg) = v.get("Msg") else { return None };
let (Some(salt), Some(newsalt), Some(time)) = (
msg.get("salt").and_then(|s| s.as_str()),
msg.get("newsalt").and_then(|s| s.as_str()),
msg.get("time").and_then(|s| s.as_str()),
) else {
return None;
};
reachable = true;
// 2. Derive the md5crypt password hash + write-token from the password.
let crypted = md5crypt::md5crypt(pass.as_bytes(), salt.as_bytes());
let full = String::from_utf8_lossy(&crypted);
let Some(pwd_md5) = full.split('$').nth(3) else { continue };
let sign_crypted = md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes());
let sign_full = String::from_utf8_lossy(&sign_crypted);
let host_sign = sign_full.split('$').nth(3).unwrap_or("");
// 3. Send an encrypted, read-only `summary`. If the AES key (from the
// password) is right the miner replies encrypted; if wrong it returns
// a plaintext "enc json load err".
let cmd = format!("{{\"command\":\"summary\",\"token\":\"{host_sign}\"}}");
let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else { continue };
let payload = format!("{{\"enc\":1,\"data\":\"{enc}\"}}");
let resp = match wm_rpc(ip, &payload, timeout) {
Ok(s) => s,
Err(_) => return None,
};
if resp.contains("\"enc\"") {
return Some(false); // accepted -> unlocked/writable
}
// rejected -> try the next candidate password
}
// Reached the miner and every candidate password was rejected -> locked.
if reachable { Some(true) } else { None }
}
#[cfg(test)]
mod tests {
use super::*;
@@ -112,4 +266,15 @@ mod tests {
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
assert_eq!(classify_http_code(""), None);
}
#[test]
fn whatsminer_aes_ecb_matches_reference() {
// Deterministic vector from the verified btminer scheme: AES-256-ECB over
// SHA256(pwd_md5), zero-padded, base64. Guards the WhatsMiner access
// handshake crypto (round 12 #8b) without needing a live miner.
assert_eq!(
wm_aes_ecb_enc("abc123def456", "{\"command\":\"summary\"}").as_deref(),
Some("jn5Wru/5hhMtU1IgamxLoUd/YTxaLTxEeiCQxu5pO+Q=")
);
}
}
+141 -8
View File
@@ -5,6 +5,7 @@
//! is the one place that fans a saved username/password out across the whole
//! firmware registry, so `scan`'s callers never have to think about it.
use std::collections::HashMap;
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
@@ -14,6 +15,10 @@ use asic_rs::core::traits::miner::MinerAuth;
use crate::scan::config_path;
pub const CREDENTIALS_FILE: &str = "scan-credentials.txt";
/// Per-firmware default logins the operator can override (round 12 #13). One
/// `firmware-name<TAB>user<TAB>pass` line per firmware, 0600 like the others.
/// Keyed by the firmware registry's Display name (see `firmware_default_creds`).
pub const FIRMWARE_CREDENTIALS_FILE: &str = "firmware-credentials.txt";
/// SSH login for the control board (used by the PIC probe; distinct from the
/// web/API scan credentials above -- miners' SSH root login is usually not the
/// same account as the web digest-auth login).
@@ -87,16 +92,115 @@ pub fn clear_credentials() -> std::io::Result<()> {
}
}
/// Build a `MinerFactory` with the saved credentials (if any) applied as
/// discovery auth for every firmware backend, so scans, refreshes, config
/// actions, and firmware flashes all authenticate against a non-default
/// login the same way. With no saved credentials this is plain `MinerFactory::new()`
/// and every backend falls back to its own default auth.
/// The stock/default login each firmware ships with, keyed by the firmware
/// registry's Display name (round 12 #13). These seed the per-firmware editor and
/// let it tell an override from an unchanged default; they mirror the
/// `default_auth()` constants in the vendored asic-rs backends (a single
/// best-guess per registry entry, since a stock entry can span several backend
/// versions). asic-rs does not expose these at the entry level, so they are
/// duplicated here; a firmware absent from this table defaults to blank.
pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] {
&[
("AntMiner Stock", "root", "root"),
("WhatsMiner Stock", "admin", "admin"),
("Braiins", "root", "root"),
("VNish", "", "admin"),
("LuxOS", "root", "root"),
("UMC OS", "", "letmein"),
("Marathon", "root", "root"),
("VolcMiner Stock", "root", "ltc@dog"),
("Elphapex Stock", "root", "root"),
("FutureBit Stock", "futurebit", "futurebit123"),
("SealMiner Stock", "seal", "seal"),
("Auradine Stock", "admin", "admin"),
("AvalonMiner Stock", "", ""),
("Nerdaxe Stock", "", ""),
("Proto Stock", "", ""),
("Bitaxe Stock", "", ""),
]
}
/// The shipped default login for a firmware, or `("","")` if unknown.
pub fn firmware_default_for(name: &str) -> (String, String) {
firmware_default_creds()
.iter()
.find(|(n, _, _)| *n == name)
.map(|(_, u, p)| (u.to_string(), p.to_string()))
.unwrap_or_default()
}
/// Load the operator's per-firmware credential overrides, keyed by firmware
/// Display name. Malformed lines are skipped.
pub fn load_firmware_credentials() -> HashMap<String, (String, String)> {
let mut map = HashMap::new();
let Ok(s) = std::fs::read_to_string(config_path(FIRMWARE_CREDENTIALS_FILE)) else {
return map;
};
for line in s.lines() {
let mut parts = line.splitn(3, '\t');
let (Some(name), user) = (parts.next(), parts.next()) else {
continue;
};
if name.is_empty() {
continue;
}
let user = user.unwrap_or("").to_string();
let pass = parts.next().unwrap_or("").to_string();
map.insert(name.to_string(), (user, pass));
}
map
}
/// Save the per-firmware credential overrides (0600), sorted by name for a
/// stable file. An empty map clears the file.
pub fn save_firmware_credentials(map: &HashMap<String, (String, String)>) -> std::io::Result<()> {
if map.is_empty() {
return clear_firmware_credentials();
}
let p = config_path(FIRMWARE_CREDENTIALS_FILE);
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&p)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
let mut names: Vec<&String> = map.keys().collect();
names.sort();
for name in names {
let (user, pass) = &map[name];
f.write_all(format!("{name}\t{user}\t{pass}\n").as_bytes())?;
}
Ok(())
}
/// Remove the per-firmware overrides file, if any. Not an error if none exists.
pub fn clear_firmware_credentials() -> std::io::Result<()> {
clear_creds_file(FIRMWARE_CREDENTIALS_FILE)
}
/// Build a `MinerFactory` with saved credentials applied as discovery auth.
/// Precedence per firmware backend: a per-firmware override (round 12 #13) wins;
/// otherwise the single global scan credential (if set) applies to every backend;
/// otherwise the backend falls back to its own default auth. With nothing saved
/// this is plain `MinerFactory::new()`.
pub fn configured_factory() -> MinerFactory {
let mut factory = MinerFactory::new();
if let Some((user, pass)) = load_credentials() {
for fw in asic_rs::factory::default_firmware_registry() {
factory = factory.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(user.clone(), pass.clone()));
let global = load_credentials();
let per_fw = load_firmware_credentials();
if global.is_none() && per_fw.is_empty() {
return factory;
}
for fw in asic_rs::factory::default_firmware_registry() {
let cred = per_fw
.get(&fw.to_string())
.cloned()
.or_else(|| global.clone());
if let Some((user, pass)) = cred {
factory = factory.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(user, pass));
}
}
factory
@@ -149,6 +253,35 @@ mod tests {
assert_eq!(load_credentials(), None, "cleared -> None");
clear_credentials().unwrap(); // idempotent: clearing an already-clear store is not an error
// Per-firmware overrides (round 12 #13). Kept in this same test because
// HOME is process-global: a second #[test] mutating it would race under
// cargo's default parallel runner.
assert!(load_firmware_credentials().is_empty(), "no file -> empty map");
let mut fw = HashMap::new();
fw.insert("WhatsMiner Stock".to_string(), ("super".to_string(), "sup3r".to_string()));
fw.insert("VNish".to_string(), ("".to_string(), "hunter2".to_string()));
save_firmware_credentials(&fw).unwrap();
// 0600, and it round-trips (an empty username survives the tab format).
let fwpath = config_path(FIRMWARE_CREDENTIALS_FILE);
assert_eq!(
std::fs::metadata(&fwpath).unwrap().permissions().mode() & 0o777,
0o600,
"per-firmware creds file must be 0600"
);
let back = load_firmware_credentials();
assert_eq!(back.get("WhatsMiner Stock"), Some(&("super".into(), "sup3r".into())));
assert_eq!(back.get("VNish"), Some(&("".into(), "hunter2".into())));
assert_eq!(back.len(), 2);
// Shipped-default lookup: known firmware resolves, unknown blanks.
assert_eq!(firmware_default_for("AntMiner Stock"), ("root".into(), "root".into()));
assert_eq!(firmware_default_for("nonexistent"), (String::new(), String::new()));
// Overrides + no global still builds a factory.
let _ = configured_factory();
// Saving an empty map clears the file (no stale overrides linger).
save_firmware_credentials(&HashMap::new()).unwrap();
assert!(load_firmware_credentials().is_empty(), "empty save -> cleared");
clear_firmware_credentials().unwrap(); // idempotent
match prev {
Some(v) => std::env::set_var("HOME", v),
None => std::env::remove_var("HOME"),
+264
View File
@@ -0,0 +1,264 @@
//! Fetch a miner's log over its firmware API and regex-scan it for useful
//! signals (round 12 #12). This is the "logs through API" path the operator
//! asked for: where a firmware exposes its log we can read board/PIC lines and
//! other metrics without SSH.
//!
//! Per firmware:
//! - VNish (aftermarket Antminer): POST /api/v1/unlock to get a bearer token,
//! then GET /api/v1/logs/miner -- the full miner log (PSU init, per-chain
//! chip detection, tuning, errors).
//! - Stock Antminer: GET /cgi-bin/log.cgi behind digest auth (older models
//! such as the Z15 do not serve it -> reported as unavailable).
//! - WhatsMiner: the btminer log is not exposed on :4028, but get_error_code
//! (unauthenticated) returns the active fault codes, which we format as the
//! log view.
//!
//! We shell out to `curl` (already a dependency of the access probe) so the
//! offline/vendored build gains no new crate, and cap the fetched text so a huge
//! log never bloats the viewer.
use std::process::Command;
use std::time::Duration;
/// Cap on the log text we keep for display (bytes); the regex summary is still
/// computed over everything fetched.
const MAX_LOG_BYTES: usize = 256 * 1024;
/// A fetched log plus the signals a regex pass pulled out of it.
pub struct LogScan {
/// The (possibly tail-trimmed) log text for the viewer.
pub text: String,
/// One-line-per-finding summary shown above the log.
pub summary: Vec<String>,
}
/// Fetch and scan one miner's log. `brand` is the make ("Antminer"/"Whatsminer"),
/// `firmware` the family ("VNish"/"Stock"/...). `vnish_pass`/`wm` creds are used
/// where that firmware needs auth. Returns `Err` only when no log could be read.
pub fn scan_log(
ip: &str,
brand: &str,
firmware: &str,
vnish_pass: &str,
antminer_user: &str,
antminer_pass: &str,
) -> Result<LogScan, String> {
let raw = if firmware.eq_ignore_ascii_case("vnish") {
fetch_vnish_log(ip, vnish_pass)?
} else if brand.eq_ignore_ascii_case("whatsminer") {
fetch_whatsminer_errors(ip)?
} else {
// Stock / other Antminer-family web firmware.
fetch_antminer_log(ip, antminer_user, antminer_pass)?
};
let summary = summarize_log(&raw);
Ok(LogScan { text: tail(&raw, MAX_LOG_BYTES), summary })
}
/// Keep the last `max` bytes of `s` (a log's tail is the freshest), on a line
/// boundary, with a marker when trimmed.
fn tail(s: &str, max: usize) -> String {
if s.len() <= max {
return s.to_string();
}
let start = s.len() - max;
// advance to the next line boundary so we don't cut a line in half
let start = s[start..]
.find('\n')
.map(|i| start + i + 1)
.unwrap_or(start);
format!("[... earlier log trimmed ...]\n{}", &s[start..])
}
/// Regex-free scan for the high-value signals in a miner log: PIC / hashboard
/// firmware lines, per-chain chip detection, and the most recent errors.
fn summarize_log(log: &str) -> Vec<String> {
let mut out = Vec::new();
let lc_has = |line: &str, needle: &str| line.to_ascii_lowercase().contains(needle);
// PIC / hashboard-controller status from the log. Aftermarket firmwares state
// it explicitly ("no-PIC miner"); stock boot logs print a PIC version. This
// is the log-regex PIC scan the operator asked for (round 12 #12).
let pic_lines: Vec<&str> = log.lines().filter(|l| lc_has(l, "pic")).collect();
if pic_lines.iter().any(|l| lc_has(l, "no-pic") || lc_has(l, "no pic")) {
out.push("PIC: not present (log reports a no-PIC miner)".to_string());
} else if let Some(l) = pic_lines
.iter()
.find(|l| lc_has(l, "version") || lc_has(l, "fw") || lc_has(l, "found"))
{
out.push(format!("PIC: present -- {}", l.trim()));
} else if !pic_lines.is_empty() {
out.push(format!("PIC: {} log line(s) mention PIC", pic_lines.len()));
for l in pic_lines.iter().take(3) {
out.push(format!(" {}", l.trim()));
}
} else {
out.push("PIC: no PIC lines in the log".to_string());
}
// Latest per-chain chip-detection line (the most recent board bring-up).
if let Some(l) = log.lines().rev().find(|l| lc_has(l, "chips detected")) {
out.push(format!("Chains: {}", l.trim()));
}
// Recent errors (log history, beyond asic-rs's current-message snapshot).
// Skip the get_error_code header line (it contains "error" but is not one).
let errors: Vec<&str> = log
.lines()
.rev()
.filter(|l| (lc_has(l, "error") || lc_has(l, "fail")) && !lc_has(l, "get_error_code"))
.take(3)
.collect();
if errors.is_empty() {
out.push("Errors: none in the log".to_string());
} else {
out.push(format!("Errors: {} recent", errors.len()));
for l in errors {
out.push(format!(" {}", l.trim()));
}
}
out
}
/// VNish: unlock -> bearer -> the full miner log.
fn fetch_vnish_log(ip: &str, pass: &str) -> Result<String, String> {
let unlock = curl(&[
"-s",
"--connect-timeout",
"5",
"--max-time",
"9",
"-X",
"POST",
"-H",
"Content-Type: application/json",
"-d",
&format!("{{\"pw\":\"{pass}\"}}"),
&format!("http://{ip}/api/v1/unlock"),
])?;
let token = serde_json::from_str::<serde_json::Value>(&unlock)
.ok()
.and_then(|v| v.get("token").and_then(|t| t.as_str()).map(str::to_string))
.filter(|t| !t.is_empty())
.ok_or_else(|| "VNish unlock rejected (check the VNish password in scan credentials)".to_string())?;
let log = curl(&[
"-s",
"--connect-timeout",
"5",
"--max-time",
"12",
"-H",
&format!("Authorization: Bearer {token}"),
&format!("http://{ip}/api/v1/logs/miner"),
])?;
if log.trim().is_empty() {
return Err("VNish returned an empty log".to_string());
}
Ok(log)
}
/// Stock Antminer web log (digest auth). Absent on older models (404).
fn fetch_antminer_log(ip: &str, user: &str, pass: &str) -> Result<String, String> {
let body = curl(&[
"-s",
"--digest",
"-u",
&format!("{user}:{pass}"),
"--connect-timeout",
"5",
"--max-time",
"12",
&format!("http://{ip}/cgi-bin/log.cgi"),
])?;
if body.contains("404 - Not Found") || body.trim().is_empty() {
return Err("this firmware does not expose a log over its web API".to_string());
}
Ok(body)
}
/// WhatsMiner: format the active error codes (get_error_code, unauthenticated).
fn fetch_whatsminer_errors(ip: &str) -> Result<String, String> {
let resp = crate::access_probe::whatsminer_get_error_code(ip)
.ok_or_else(|| "WhatsMiner did not answer get_error_code on :4028".to_string())?;
Ok(resp)
}
/// Run curl and return stdout, with a hard wall-clock cap. stdout is drained on a
/// separate thread so a large log (hundreds of KB) never deadlocks on a full pipe
/// -- the reason a naive "wait then read" times out on the VNish log.
fn curl(args: &[&str]) -> Result<String, String> {
use std::io::Read;
let mut cmd = Command::new("curl");
cmd.args(args);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::null());
let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?;
let mut stdout = child.stdout.take().ok_or("no curl stdout")?;
let reader = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout.read_to_end(&mut buf);
buf
});
let timeout = Duration::from_secs(20);
let start = std::time::Instant::now();
let mut timed_out = false;
loop {
match child.try_wait().map_err(|e| e.to_string())? {
Some(_) => break,
None => {
if start.elapsed() >= timeout {
let _ = child.kill();
timed_out = true;
break;
}
std::thread::sleep(Duration::from_millis(50));
}
}
}
let buf = reader.join().unwrap_or_default();
if timed_out && buf.is_empty() {
return Err("log fetch timed out".into());
}
Ok(String::from_utf8_lossy(&buf).into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn summarize_finds_pic_chains_and_errors() {
let log = "\
[t] INFO: Initializing PSU
[t] INFO: chain#1 - 126 chips detected
[t] INFO: check PIC on chain 1: version 0x03
[t] ERROR: Failed load miner config
[t] INFO: chain#2 - 126 chips detected";
let s = summarize_log(log);
assert!(s.iter().any(|l| l.contains("PIC: present")), "PIC present: {s:?}");
assert!(s.iter().any(|l| l.contains("chips detected")), "chains: {s:?}");
assert!(s.iter().any(|l| l.contains("Errors: 1")), "errors: {s:?}");
}
#[test]
fn summarize_detects_no_pic_miner() {
let log = "[t] ERROR: This is a no-PIC miner, so all connected chains ...\n[t] INFO: mining";
let s = summarize_log(log);
assert!(s.iter().any(|l| l.contains("PIC: not present")), "{s:?}");
}
#[test]
fn summarize_handles_no_pic_lines() {
let log = "[t] INFO: chain#1 - 126 chips detected\n[t] INFO: mining";
let s = summarize_log(log);
assert!(s.iter().any(|l| l.contains("no PIC lines")), "{s:?}");
}
#[test]
fn tail_trims_on_line_boundary() {
let log = "aaaa\nbbbb\ncccc\n";
let t = tail(log, 6);
assert!(t.starts_with("[... earlier log trimmed ...]"), "{t}");
assert!(t.ends_with("cccc\n"));
}
}
+44
View File
@@ -4,6 +4,7 @@
mod access_probe;
mod credentials;
mod fixtures;
mod log_scan;
mod model;
mod naming;
mod pic_probe;
@@ -21,6 +22,49 @@ fn main() {
std::process::exit(run_selftest());
}
// Headless access-probe check: `ALKANE_ACCESS_PROBE="<ip> <make>"` prints the
// lock state the real access probe computes (no GUI, no wx), so the WhatsMiner
// :4028 token check and the Antminer digest check can be verified directly.
if let Some(spec) = std::env::var_os("ALKANE_ACCESS_PROBE") {
let spec = spec.to_string_lossy();
let mut it = spec.split_whitespace();
let ip = it.next().unwrap_or("");
let make = it.next().unwrap_or("");
let (user, pass) = credentials::load_credentials().unwrap_or_default();
match access_probe::probe_access(ip, make, &user, &pass) {
Ok(Some(true)) => println!("ACCESS {ip} {make}: LOCKED"),
Ok(Some(false)) => println!("ACCESS {ip} {make}: UNLOCKED"),
Ok(None) => println!("ACCESS {ip} {make}: INDETERMINATE"),
Err(e) => println!("ACCESS {ip} {make}: ERROR {e}"),
}
std::process::exit(0);
}
// Headless log-scan check: `ALKANE_LOG_SCAN="<ip> <brand> <firmware>"` fetches
// the miner's log over its firmware API and prints the regex summary (round
// 12 #12), so the VNish/Antminer/WhatsMiner log paths can be verified without
// the GUI.
if let Some(spec) = std::env::var_os("ALKANE_LOG_SCAN") {
let spec = spec.to_string_lossy();
let mut it = spec.split_whitespace();
let ip = it.next().unwrap_or("");
let brand = it.next().unwrap_or("");
let firmware = it.next().unwrap_or("");
let (au, ap) = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
let vp = credentials::firmware_default_for("VNish").1;
let vp = if vp.is_empty() { "admin".to_string() } else { vp };
match log_scan::scan_log(ip, brand, firmware, &vp, &au, &ap) {
Ok(s) => {
println!("LOGSCAN {ip} ({brand}/{firmware}): {} log bytes", s.text.len());
for line in &s.summary {
println!(" {line}");
}
}
Err(e) => println!("LOGSCAN {ip} ({brand}/{firmware}): ERROR {e}"),
}
std::process::exit(0);
}
// Bootstrap the wx app + main frame (upstream bridge).
wx_rs::init_app("alkane-toolkit", 1280, 800);
// Follow the system light/dark appearance.
+1 -1
View File
@@ -546,7 +546,7 @@ impl Column {
Column::Serial => "Serial",
Column::ApiVersion => "API ver",
Column::Cpu => "CPU",
Column::BoardCode => "Board",
Column::BoardCode => "Control Board",
Column::Algorithm => "Algorithm",
Column::Pic => "PIC",
Column::Locked => "Access",
+37 -10
View File
@@ -449,15 +449,19 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.as_ref()
.map(|t| t.as_celsius())
.unwrap_or(0.0);
// Per-hashboard chip temperature (hottest chip per board, falling back to
// the board/PCB temp), for the "77 / 64 / 74" Chip-temp cell.
// Per-hashboard temperature for the "77 / 64 / 74" Chip-temp cell. Prefer the
// board/PCB temperature over the hottest-chip (outlet) reading: WhatsMiner's
// outlet_chip is the max chip temp (~100C on the hottest board), which read
// alarmingly high and didn't match the temperature the miner itself reports;
// the board temperature (~60-79C) is the figure the miner's own UI shows
// (round 12 #3). Falls back to the chip temp when no board temp is reported.
let board_temps: Vec<f64> = data
.hashboards
.iter()
.filter_map(|b| {
b.outlet_chip_temperature
b.board_temperature
.as_ref()
.or(b.board_temperature.as_ref())
.or(b.outlet_chip_temperature.as_ref())
.map(|t| t.as_celsius())
})
.filter(|&t| t > 0.0)
@@ -564,9 +568,17 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
// on-board SSH/I2C probe -- a separate feature).
let pic_present = if model.to_lowercase().contains("nopic") { Some(false) } else { None };
// Access: locked/view-only when the miner exposes no writable control at
// all, otherwise unlocked. Inferred from capabilities (asic-rs has no direct
// lock-state field).
let write_locked = Some(!caps.any_control());
// all, otherwise unlocked. Inferred from asic-rs capabilities (there is no
// direct lock-state field). WhatsMiner is the exception: it is controllable
// over its :4028 token API regardless of which commands the matched asic-rs
// backend implements, so this heuristic falsely marks older units "locked".
// Leave it unknown and let the real access probe (the :4028 token check)
// decide (round 12 #8b).
let write_locked = if brand.eq_ignore_ascii_case("whatsminer") {
None
} else {
Some(!caps.any_control())
};
// Per-hashboard health for the Boards status dots (round 11 #10): green =
// present & hashing, red = present but idle/faulty, grey = expected but not
// detected. Boards keep asic-rs's reported order (board 1 first); any boards
@@ -606,7 +618,22 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
submodel,
mac: data.mac.map(|m| m.to_string()).unwrap_or_default(),
hostname: data.hostname.clone().unwrap_or_default(),
serial: data.serial_number.clone().unwrap_or_default(),
serial: {
// Some miners report a placeholder serial ("N/A", "none", ...); show
// those as an empty cell rather than the literal placeholder (round 12).
let s = data.serial_number.clone().unwrap_or_default();
let t = s.trim();
if t.is_empty()
|| t.eq_ignore_ascii_case("n/a")
|| t.eq_ignore_ascii_case("na")
|| t.eq_ignore_ascii_case("none")
|| t.eq_ignore_ascii_case("null")
{
String::new()
} else {
s
}
},
firmware,
fw_version,
api_version: data.api_version.clone().unwrap_or_default(),
@@ -1127,11 +1154,11 @@ pub fn start_access_probe(
let thread_cancel = cancel.clone();
let err_tx = tx.clone();
let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || {
for (ip, fw) in targets {
for (ip, make) in targets {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) {
let (locked, error) = match crate::access_probe::probe_access(&ip, &make, &user, &pass) {
Ok(v) => (v, None),
Err(e) => (None, Some(e)),
};
+331 -27
View File
@@ -56,6 +56,9 @@ const ID_CTX_POWER: i32 = 728;
const ID_CTX_RESTART: i32 = 729;
const ID_CTX_PIC_PROBE: i32 = 730;
const ID_CTX_ACCESS_PROBE: i32 = 731;
// View a miner's log fetched over its firmware API (round 12 #12).
const ID_CTX_VIEW_LOG: i32 = 734;
const ID_LOGVIEW_CLOSE: i32 = 785;
// SSH PIC-probe credentials dialog.
const ID_PICSSH_OK: i32 = 780;
const ID_PICSSH_CANCEL: i32 = 781;
@@ -72,6 +75,12 @@ const ID_FLASH_CANCEL: i32 = 745;
const ID_CREDS_SAVE: i32 = 746;
const ID_CREDS_CLEAR: i32 = 747;
const ID_CREDS_CANCEL: i32 = 748;
// Per-firmware default-credentials editor (round 12 #13), opened from the scan
// credentials dialog.
const ID_FWCREDS_OPEN: i32 = 749;
const ID_FWCREDS_SAVE: i32 = 750;
const ID_FWCREDS_RESET: i32 = 751;
const ID_FWCREDS_CANCEL: i32 = 752;
// Column-header right-click menu (Excel-style).
const ID_HDR_SORT_ASC: i32 = 760;
const ID_HDR_SORT_DESC: i32 = 761;
@@ -242,6 +251,51 @@ fn encode_flag_cell(plain: &str, color: Option<(u8, u8, u8)>) -> String {
const SHAPE_DOT: &str = "\u{0007}";
const SHAPE_LOCK: &str = "\u{0002}";
const SHAPE_UNLOCK: &str = "\u{0003}";
// Status-column KPI icons (round 12 #11): one sentinel per status, each drawn
// from the same SVG as its dashboard KPI card. Registered with the bridge in
// `register_cell_icons` at startup.
const SHAPE_HASHING: &str = "\u{0004}";
const SHAPE_SLOW: &str = "\u{0005}";
const SHAPE_NOTHASHING: &str = "\u{0006}";
const SHAPE_PAUSED: &str = "\u{0008}";
/// Locate-light dot that fades in and out (round 12 #6); distinct from the static
/// `SHAPE_DOT` so only the flashing light pulses, not the hashboard health dots.
const SHAPE_PULSE_DOT: &str = "\u{000B}";
/// Register every SVG-backed table-cell icon with the bridge (round 12 #9/#11):
/// the access padlocks and the four status KPI icons. Called once at startup;
/// the renderer recolours each per cell. The sentinel code points MUST match the
/// `\u{..}` constants above and the SHAPE_* set in widgets_bridge.cpp.
fn register_cell_icons() {
// (sentinel first char, svg) pairs; the bridge reads the viewBox dims we pass
// to keep each icon's aspect ratio when it rasterises at the cell height.
let icons: [(&str, &str); 6] = [
(SHAPE_LOCK, SVG_LOCK),
(SHAPE_UNLOCK, SVG_UNLOCK),
(SHAPE_HASHING, SVG_RABBIT),
(SHAPE_SLOW, SVG_TURTLE),
(SHAPE_NOTHASHING, SVG_WINE_CRACK),
(SHAPE_PAUSED, SVG_OTTER),
];
for (sentinel, svg) in icons {
let cp = sentinel.chars().next().map(|c| c as u32).unwrap_or(0);
let (vbw, vbh) = svg_viewbox(svg);
wx_rs::register_shape_svg(cp, svg, vbw, vbh);
}
}
/// Parse an SVG's viewBox width/height (round 12 #9/#11), defaulting to a square
/// when absent so the bridge can preserve the icon aspect at any cell height.
fn svg_viewbox(svg: &str) -> (i32, i32) {
svg.split("viewBox=\"")
.nth(1)
.and_then(|s| s.split('"').next())
.and_then(|vb| {
let n: Vec<f64> = vb.split_whitespace().filter_map(|x| x.parse().ok()).collect();
(n.len() == 4 && n[2] > 0.0 && n[3] > 0.0).then(|| (n[2].round() as i32, n[3].round() as i32))
})
.unwrap_or((1, 1))
}
/// Boards column: one status dot per hashboard (round 11 #10). Board 1 is the
/// rightmost dot, so boards render high-position-first (left to right). green =
@@ -277,14 +331,29 @@ fn encode_access_icon(pal: &Palette, write_locked: Option<bool>) -> String {
}
/// Light column: a yellow dot while the miner's locate light is flashing, else
/// blank (round 11 #10).
/// blank (round 11 #10). The dot fades in and out (round 12 #6) via the pulsing
/// sentinel, so a flashing light reads as a live pulse rather than a static dot.
fn encode_light_dot(pal: &Palette, flashing: Option<bool>) -> String {
match flashing {
Some(true) => encode_segments(&[(Some(pal.amber), SHAPE_DOT.to_string())]),
Some(true) => encode_segments(&[(Some(pal.amber), SHAPE_PULSE_DOT.to_string())]),
_ => encode_segments(&[(None, String::new())]),
}
}
/// Status column: the status rendered as its KPI icon in the status colour
/// (round 12 #11) -- rabbit=hashing, turtle=slow, cracked wine glass=not
/// hashing, otter=paused. An unrecognised status falls back to coloured text.
fn encode_status_icon(pal: &Palette, status: &str) -> String {
let shape = match status {
"hashing" => SHAPE_HASHING,
"slow" => SHAPE_SLOW,
"not hashing" => SHAPE_NOTHASHING,
"paused" => SHAPE_PAUSED,
_ => return encode_segments(&[(Some(status_kind_color(pal, status)), status.to_string())]),
};
encode_segments(&[(Some(status_kind_color(pal, status)), shape.to_string())])
}
// KPI card icons (round 11 #15). The animal/wine-glass SVGs are Font Awesome Pro
// (operator-supplied); bolt/hive are matching in-repo SVGs. All use
// fill="currentColor", recoloured per card at render time.
@@ -294,6 +363,21 @@ const SVG_WINE_CRACK: &str = include_str!("../assets/icons/wine-glass-crack.svg"
const SVG_OTTER: &str = include_str!("../assets/icons/otter.svg");
const SVG_HIVE: &str = include_str!("../assets/icons/hive.svg");
const SVG_BOLT: &str = include_str!("../assets/icons/bolt.svg");
// Access-column padlocks (round 12 #9): operator-supplied Font Awesome padlocks
// that replace the hand-drawn vector padlocks in the table.
const SVG_LOCK: &str = include_str!("../assets/icons/lock.svg");
const SVG_UNLOCK: &str = include_str!("../assets/icons/unlock.svg");
/// KPI card minimum widths. The count cards (Total/Hashing/...) are narrow; the
/// two wide cards (SHA-256 Hashrate, Est. power) need more room so their
/// icon + units-bearing value never clips (round 12 #2). The wide floor fits the
/// widest realistic value the card can show -- a ~20px icon + 5px gap + a value
/// text up to "118.0 PH" (~127px at 19pt bold) + the card's 16px side inset --
/// so the units ("kW"/"PH"/...) stay visible instead of being squeezed off; the
/// row collapses the wide cards entirely (see `on_resize`) rather than shrink
/// them below this and clip.
const KPI_MIN: i32 = 116;
const KPI_WIDE_MIN: i32 = 176;
/// Recolour an SVG to the KPI card's colour (round 11 #15). Some Font Awesome
/// exports use fill="currentColor" (replaced here); others omit fill entirely and
@@ -498,11 +582,17 @@ pub struct App {
creds_dialog: Widget,
creds_user_input: Widget,
creds_pass_input: Widget,
// Per-firmware default-credentials editor (round 12 #13): the dialog plus one
// (firmware name, user field, pass field) per registry firmware.
fwcreds_dialog: Widget,
fwcreds_rows: Vec<(String, Widget, Widget)>,
// Background access (lock-state) probe.
access_probe: Option<scan::AccessProbeHandle>,
// Background SSH PIC probe + its credentials dialog.
pic_probe: Option<scan::PicProbeHandle>,
pending_pic_targets: Vec<(String, String)>,
// The API log viewer dialog (round 12 #12).
logview_dialog: Widget,
picssh_dialog: Widget,
picssh_user_input: Widget,
picssh_pass_input: Widget,
@@ -543,6 +633,9 @@ pub struct App {
pub fn build(frame: Widget) -> App {
let pal = palette();
// Register the SVG-backed table-cell icons once (access padlocks + status KPI
// icons, round 12 #9/#11) before any row is rendered.
register_cell_icons();
let panel = Widget::panel(frame);
let root = Widget::box_sizer(true);
@@ -560,7 +653,7 @@ pub fn build(frame: Widget) -> App {
card.set_bg(pal.card_bg.0, pal.card_bg.1, pal.card_bg.2);
// Min-content floor (the widest label/value); cards grow equally past
// this to fill the window (proportion 1 + EXPAND on add).
card.set_min_size(116, 62);
card.set_min_size(KPI_MIN, 62);
let cs = Widget::box_sizer(true);
let value = Widget::static_text(card, "0");
value.set_font_size(19);
@@ -619,9 +712,16 @@ pub fn build(frame: Widget) -> App {
let (card_slow, kpi_slow) = mk_card("Slow", ColorKind::Amber, Some(SVG_TURTLE));
let (card_not, kpi_not) = mk_card("Not hashing", ColorKind::Red, Some(SVG_WINE_CRACK));
let (card_paused, kpi_paused) = mk_card("Paused", ColorKind::Blue, Some(SVG_OTTER));
let (card_hashrate, kpi_hashrate) = mk_card("SHA-256 Hashrate", ColorKind::Accent, Some(SVG_HIVE));
let (_card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral, Some(SVG_BOLT));
// Total-hashrate value renders in the default (black) text colour, not accent
// (round 12 #1); it still dims with focus like the other neutral cards.
let (card_hashrate, kpi_hashrate) = mk_card("SHA-256 Hashrate", ColorKind::Neutral, Some(SVG_HIVE));
let (card_power, kpi_power) = mk_card("Est. power", ColorKind::Neutral, Some(SVG_BOLT));
drop(mk_card);
// The two wide cards carry a units-bearing value (icon + e.g. "685 TH" /
// "21.3 kW"); give them a larger min width so the value never clips, and
// collapse them before the row would squeeze them below it (round 12 #2).
card_hashrate.set_min_size(KPI_WIDE_MIN, 62);
card_power.set_min_size(KPI_WIDE_MIN, 62);
let _ = (card_hashing, card_slow, card_not, card_paused);
// The hashrate card is kpi_cards[5] in build order (Total, Hashing, Slow,
// Not, Paused, Hashrate, Power); its caption is retitled per algorithm.
@@ -759,9 +859,12 @@ pub fn build(frame: Widget) -> App {
creds_dialog: frame,
creds_user_input: frame,
creds_pass_input: frame,
fwcreds_dialog: frame,
fwcreds_rows: Vec::new(),
access_probe: None,
pic_probe: None,
pending_pic_targets: Vec::new(),
logview_dialog: frame,
picssh_dialog: frame,
picssh_user_input: frame,
picssh_pass_input: frame,
@@ -830,23 +933,32 @@ impl App {
/// seven cards at their minimum width, the two wide cards are hidden so the
/// five miner-count cards fill the row; they return when there is room again.
fn on_resize(&mut self, width: i32) {
// Each card is a ~116px min + BORDER_ALL*2 (8px); the row itself is
// inset by the root border. Below the width needed for all seven, drop
// the two wide cards.
const CARD_SLOT: i32 = 116 + 8;
let need_all = CARD_SLOT * 7 + 12;
// Each card occupies its min width + BORDER_ALL*2 (8px); the row itself is
// inset by the root border (~12px). Collapse the two wide cards below the
// width where all seven fit at their mins, so the wide cards' units-bearing
// value never gets squeezed/clipped (round 12 #2) -- they drop out cleanly
// instead.
let need_all = 5 * (KPI_MIN + 8) + 2 * (KPI_WIDE_MIN + 8) + 12;
let want_collapsed = width < need_all;
if want_collapsed == self.kpi_collapsed {
return;
if want_collapsed != self.kpi_collapsed {
self.kpi_collapsed = want_collapsed;
let show = !want_collapsed;
// kpi_cards[5] = Hashrate card, [6] = Est. power card (build order).
let hashrate_card = self.kpi_cards[5].0;
let power_card = self.kpi_cards[6].0;
self.kpi_row.sizer_show(hashrate_card, show);
self.kpi_row.sizer_show(power_card, show);
self.panel.layout();
}
// A nested wxPanel does not re-run its own sizer when the parent resizes
// it, so the value/label centring spacers keep the slot sizes they were
// given at the previous width. Re-layout each card here so the value
// (which may carry a units suffix like "kW"/"PH") stays centred and its
// full text is allocated -- otherwise the suffix reads as clipped when
// the row is squeezed (round 12 #2).
for (card, _, _, _) in &self.kpi_cards {
card.layout();
}
self.kpi_collapsed = want_collapsed;
let show = !want_collapsed;
// kpi_cards[5] = Hashrate card, [6] = Est. power card (build order).
let hashrate_card = self.kpi_cards[5].0;
let power_card = self.kpi_cards[6].0;
self.kpi_row.sizer_show(hashrate_card, show);
self.kpi_row.sizer_show(power_card, show);
self.panel.layout();
}
pub fn rebuild_table(&mut self) {
@@ -952,9 +1064,9 @@ impl App {
}
Column::Firmware => encode_flag_cell(&c.cell(r), firmware_color(&r.firmware)),
Column::Status => {
// Status keeps its status colour on its own cell (the
// row is no longer tinted wholesale).
encode_flag_cell(&c.cell(r), Some(status_kind_color(&self.pal, r.status())))
// The status reads as its KPI icon (round 12 #11), drawn
// in the status colour so it matches the dashboard card.
encode_status_icon(&self.pal, r.status())
}
_ => continue,
};
@@ -979,6 +1091,14 @@ impl App {
if !sel.is_empty() {
t.dvlc_select_rows(&sel);
}
// Run the locate-light fade timer only while a visible row's light is
// actually flashing (round 12 #6), so the table isn't repainted on a timer
// when there is nothing to animate.
let any_flashing = self
.view_idx
.iter()
.any(|&ri| self.rows[ri].light_flashing == Some(true));
wx_rs::set_light_pulse(any_flashing);
self.refresh_kpis();
}
@@ -1141,6 +1261,8 @@ impl App {
// Real access/lock-state check (credentialed digest GET; uses the saved
// scan credentials).
menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)");
// Fetch and scan this miner's log over its firmware API (round 12 #12).
menu.menu_append(ID_CTX_VIEW_LOG, "View log (API)...");
// Config actions common to the whole selection (capability
// intersection): an action is offered only if every selected miner
// supports it.
@@ -1240,6 +1362,59 @@ impl App {
wx_rs::set_status_text(&msg);
}
/// Fetch the selected miner's log over its firmware API and show it in a
/// viewer with a regex summary at the top (round 12 #12). The fetch is a
/// short blocking network call (a manual, single-miner action). Returns the
/// dialog to show, or None after reporting why no log could be read.
fn build_log_view_dialog(&mut self) -> Option<Widget> {
let rows = self.selected_rows();
let r = rows.first()?;
let (ip, brand, firmware) = (r.ip.clone(), r.brand.clone(), r.firmware.clone());
// VNish unlock password + Antminer web login: a per-firmware override
// (round 12 #13) wins, else the shipped default / saved global creds.
let vnish_pass = credentials::load_firmware_credentials()
.get("VNish")
.map(|(_, p)| p.clone())
.filter(|p| !p.is_empty())
.unwrap_or_else(|| credentials::firmware_default_for("VNish").1);
let vnish_pass = if vnish_pass.is_empty() { "admin".to_string() } else { vnish_pass };
let (am_user, am_pass) =
credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
wx_rs::set_status_text(&format!("fetching log from {ip}..."));
let scan = match crate::log_scan::scan_log(&ip, &brand, &firmware, &vnish_pass, &am_user, &am_pass) {
Ok(s) => s,
Err(e) => {
self.set_error_indicator(&format!("log: {e}"));
wx_rs::set_status_text(&format!("log fetch failed for {ip}: {e}"));
return None;
}
};
self.clear_indicator();
wx_rs::set_status_text(&format!("{} miners", self.rows.len()));
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, &format!("Miner log (API) -- {ip}"));
let root = Widget::box_sizer(true);
let summary = if scan.summary.is_empty() {
"(no summary)".to_string()
} else {
scan.summary.join("\n")
};
root.add(Widget::static_text(dlg, &summary), 0, sf::BORDER_ALL, 8);
let text = Widget::text_ctrl(dlg, true);
text.set_min_size(760, 420);
text.set_value(&scan.text);
root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Close", ID_LOGVIEW_CLOSE), 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(800, 540);
dlg.fit(dlg);
self.logview_dialog = dlg;
Some(dlg)
}
/// Build the SSH PIC-probe dialog: captures the selected miners, collects
/// SSH credentials (prefilled from the saved SSH login), and on OK runs the
/// on-board i2c probe. Returns None (no dialog) if nothing is selected or a
@@ -1341,10 +1516,13 @@ impl App {
wx_rs::set_status_text("an access check is already running");
return;
}
// Pass the brand (make), not the firmware family: the access probe picks
// its strategy by make (WhatsMiner :4028 token vs Antminer web digest),
// and "Stock" alone can't tell them apart (round 12 #8b).
let targets: Vec<(String, String)> = self
.selected_rows()
.iter()
.map(|r| (r.ip.clone(), r.firmware.clone()))
.map(|r| (r.ip.clone(), r.brand.clone()))
.collect();
if targets.is_empty() {
return;
@@ -1471,6 +1649,8 @@ impl App {
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(),
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
ID_CTX_VIEW_LOG => return self.build_log_view_dialog(),
ID_LOGVIEW_CLOSE => self.logview_dialog.close(1),
ID_CTX_FLASH => {
// A flash needs exclusive hardware access; don't even prompt if
// any scan / refresh / action is running (re-checked at confirm).
@@ -1724,6 +1904,19 @@ impl App {
pass_input.set_min_size(200, -1);
pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
// The single credential above is applied to every firmware that has no
// per-firmware override; the button below edits those per-firmware default
// logins (round 12 #13).
let fwrow = Widget::box_sizer(false);
fwrow.add(
Widget::static_text(dlg, "Or set a login per firmware:"),
0,
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL,
6,
);
fwrow.add_stretch(1);
fwrow.add(Widget::button(dlg, "Per-firmware defaults...", ID_FWCREDS_OPEN), 0, sf::BORDER_ALL, 6);
root.add_sizer(fwrow, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Save", ID_CREDS_SAVE), 0, sf::BORDER_ALL, 6);
@@ -1731,7 +1924,7 @@ impl App {
btns.add(Widget::button(dlg, "Cancel", ID_CREDS_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(360, 190);
dlg.set_min_size(460, 220);
dlg.fit(dlg);
self.creds_dialog = dlg;
self.creds_user_input = user_input;
@@ -1739,6 +1932,113 @@ impl App {
dlg
}
/// Build (but do not show) the per-firmware default-credentials editor
/// (round 12 #13): one row per firmware in the asic-rs registry, each with a
/// username and password field prefilled from the saved override or, failing
/// that, the firmware's shipped default. Editing a field away from the default
/// makes it an override; setting it back to the default clears the override.
fn build_firmware_creds_dialog(&mut self) -> Widget {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Per-firmware default logins");
let root = Widget::box_sizer(true);
root.add(
Widget::static_text(
dlg,
"Default login used when auto-discovering each firmware. Blank fields mean no login.\nValues left at the firmware's shipped default are not saved as overrides.",
),
0,
sf::BORDER_ALL,
8,
);
// Column headers.
let head = Widget::box_sizer(false);
let h_fw = Widget::static_text(dlg, "Firmware");
h_fw.set_min_size(150, -1);
head.add(h_fw, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let h_user = Widget::static_text(dlg, "Username");
h_user.set_min_size(150, -1);
head.add(h_user, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
head.add(Widget::static_text(dlg, "Password"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
root.add_sizer(head, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6);
let saved = credentials::load_firmware_credentials();
let mut rows: Vec<(String, Widget, Widget)> = Vec::new();
for fw in asic_rs::factory::default_firmware_registry() {
let name = fw.to_string();
let (def_user, def_pass) = credentials::firmware_default_for(&name);
let (user, pass) = saved
.get(&name)
.cloned()
.unwrap_or((def_user, def_pass));
let row = Widget::box_sizer(false);
let label = Widget::static_text(dlg, &name);
label.set_min_size(150, -1);
row.add(label, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let user_ctrl = Widget::text_ctrl(dlg, false);
user_ctrl.set_min_size(150, -1);
user_ctrl.set_value(&user);
row.add(user_ctrl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
let pass_ctrl = Widget::text_ctrl(dlg, false);
pass_ctrl.set_min_size(150, -1);
pass_ctrl.set_value(&pass);
row.add(pass_ctrl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
root.add_sizer(row, 0, sf::EXPAND | sf::BORDER_TOP, 4);
rows.push((name, user_ctrl, pass_ctrl));
}
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
btns.add(Widget::button(dlg, "Save", ID_FWCREDS_SAVE), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Reset to defaults", ID_FWCREDS_RESET), 0, sf::BORDER_ALL, 6);
btns.add(Widget::button(dlg, "Cancel", ID_FWCREDS_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(520, 200);
dlg.fit(dlg);
self.fwcreds_dialog = dlg;
self.fwcreds_rows = rows;
dlg
}
/// Persist the per-firmware editor: a row that differs from the firmware's
/// shipped default becomes an override; a row equal to the default clears it.
fn apply_firmware_creds_save(&mut self) {
let mut map: std::collections::HashMap<String, (String, String)> = std::collections::HashMap::new();
for (name, user_ctrl, pass_ctrl) in &self.fwcreds_rows {
let user = user_ctrl.get_value();
let pass = pass_ctrl.get_value();
let default = credentials::firmware_default_for(name);
if (user.clone(), pass.clone()) != default {
map.insert(name.clone(), (user, pass));
}
}
match credentials::save_firmware_credentials(&map) {
Ok(()) => {
self.fwcreds_dialog.close(1);
let n = map.len();
wx_rs::set_status_text(&format!(
"per-firmware logins saved ({n} override{})",
if n == 1 { "" } else { "s" }
));
}
Err(e) => wx_rs::set_status_text(&format!("failed to save per-firmware logins: {e}")),
}
}
/// Reset every editor row to the firmware's shipped default and clear the
/// saved overrides.
fn apply_firmware_creds_reset(&mut self) {
for (name, user_ctrl, pass_ctrl) in &self.fwcreds_rows {
let (user, pass) = credentials::firmware_default_for(name);
user_ctrl.set_value(&user);
pass_ctrl.set_value(&pass);
}
match credentials::clear_firmware_credentials() {
Ok(()) => wx_rs::set_status_text("per-firmware logins reset to defaults"),
Err(e) => wx_rs::set_status_text(&format!("failed to clear per-firmware logins: {e}")),
}
}
fn apply_creds_save(&mut self) {
let user = self.creds_user_input.get_value();
let mut pass = self.creds_pass_input.get_value();
@@ -2825,6 +3125,10 @@ impl App {
ID_CREDS_SAVE => self.apply_creds_save(),
ID_CREDS_CLEAR => self.apply_creds_clear(),
ID_CREDS_CANCEL => self.creds_dialog.close(0),
ID_FWCREDS_OPEN => return Some(self.build_firmware_creds_dialog()),
ID_FWCREDS_SAVE => self.apply_firmware_creds_save(),
ID_FWCREDS_RESET => self.apply_firmware_creds_reset(),
ID_FWCREDS_CANCEL => self.fwcreds_dialog.close(0),
ID_KPI_HASHING => self.toggle_kpi_filter("hashing"),
ID_KPI_SLOW => self.toggle_kpi_filter("slow"),
ID_KPI_NOT => self.toggle_kpi_filter("not hashing"),
@@ -2933,12 +3237,12 @@ impl App {
// Icon/dot columns (round 11 #10/#13) render shape sentinels, not
// text, so they don't round-trip to c.cell(r); they're verified
// structurally in the icon-column spot-check below.
if matches!(c, Column::Hashboards | Column::Locked | Column::Light) {
if matches!(c, Column::Hashboards | Column::Locked | Column::Light | Column::Status) {
continue;
}
let want = c.cell(r);
let raw = t.dvlc_get_cell(disp_row, j).unwrap_or_default();
let got = if matches!(c, Column::Hashrate | Column::TotalChips | Column::ChipTemp | Column::Cooling | Column::Error | Column::Status | Column::Firmware) {
let got = if matches!(c, Column::Hashrate | Column::TotalChips | Column::ChipTemp | Column::Cooling | Column::Error | Column::Firmware) {
decode_segments_plain(&raw)
} else {
raw
@@ -0,0 +1,243 @@
Subject: [PATCH 0006] antminer: route old models to the right backend + read the Z15 control board
Round-12 #10. Three fixes for stock Antminer Z15/Z15J (fw 2020), all verified
live on 10.5.1.x:
1. Backend routing: the version detector only read summary.cgi, which older
models (Z15) do not serve (404) -> version None -> AntMiner::new defaulted to
the newest backend, which mis-parsed the miner (empty control board, no
expected hashrate/wattage/fans). Fall back to the cgminer :4028 `version`
RPC's CompileTime so the Z15 (2020) routes to the v2020 backend.
2. Control board "read, not guess": the Z15 has no miner_type.cgi, so its
control-board subtype is unreadable there. Read the kernel build string from
get_system_info.cgi instead ("Linux 4.6.0-xilinx-..." -> Xilinx); the
ControlBoardVersion field now carries both the subtype and the kernel, and the
parser prefers the subtype and falls back to the kernel marker.
3. Malformed cgminer stats: the Z15 emits a stats array whose objects are not
comma-separated (`...}{"STATS":0...`), invalid JSON that serde rejected,
dropping the whole stats command and every stats-derived field. Insert the
missing separators before parsing (a no-op on well-formed responses); this
restores expected hashrate, fans, hashboards and uptime. The expected
hashrate also gets the same Equihash Sol/s reinterpretation as the realtime
rate, so both read on one scale (e.g. 144k / 320k) instead of the expected
reading ~1e6x larger.
diff --git a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
index 5b9f77b3..a02bdf9d 100644
--- a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
+++ b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/mod.rs
@@ -434,14 +434,29 @@ impl GetDataLocations for AntMinerV2020 {
tag: None,
},
)],
- DataField::ControlBoardVersion => vec![(
- WEB_MINER_TYPE,
- DataExtractor {
- func: get_by_pointer,
- key: Some("/subtype"),
- tag: None,
- },
- )],
+ // Prefer the explicit control-board subtype from miner_type.cgi, but
+ // carry the kernel build string from get_system_info.cgi too: older
+ // models (e.g. Z15/Z15J) have no miner_type.cgi, and their kernel
+ // string ("...-xilinx-...") names the control board we can actually
+ // read instead of guessing from the model (round 12 #10).
+ DataField::ControlBoardVersion => vec![
+ (
+ WEB_MINER_TYPE,
+ DataExtractor {
+ func: get_by_pointer,
+ key: Some("/subtype"),
+ tag: Some("subtype"),
+ },
+ ),
+ (
+ WEB_SYSTEM_INFO,
+ DataExtractor {
+ func: get_by_pointer,
+ key: Some("/system_kernel_version"),
+ tag: Some("kernel"),
+ },
+ ),
+ ],
// cgminer names its summary keys after the unit they are in —
// `GHS 5s` on SHA-256 models, `MHS 5s` on Scrypt ones — so keep
// the whole entry and let the parse pick the key that is present.
@@ -748,16 +763,33 @@ impl GetExpectedHashrate for AntMinerV2020 {
let value = field?
.pointer("/hashrate")
.and_then(Self::parse_f64_field)?;
+ // Equihash miners (Z15/Z15J) report `total_rateideal` as a Sol/s count in
+ // the same (mislabelled) scale as the realtime "GHS" rate, so reinterpret
+ // it as the base Hash unit -- matching parse_hashrate. Without this,
+ // expected reads ~1e6x larger than realtime and the realtime figure looks
+ // absent next to it (round 12 #10).
+ let is_equihash = self.device_info.algo == HashAlgorithm::Equihash
+ || self
+ .device_info
+ .model
+ .to_string()
+ .to_ascii_uppercase()
+ .contains("Z15");
+ let unit = if is_equihash {
+ HashRateUnit::Hash
+ } else {
+ // `total_rateideal` does not name its own scale, so take it from
+ // STATS' `rate_unit` (`"GH"` / `"MH"`).
+ field
+ .and_then(|v| v.pointer("/unit"))
+ .and_then(|v| v.as_str())
+ .and_then(|s| HashRateUnit::from_str(s).ok())
+ .unwrap_or(HashRateUnit::GigaHash)
+ };
Some(
HashRate {
value,
- // `total_rateideal` does not name its own scale, so take it
- // from STATS' `rate_unit` (`"GH"` / `"MH"`).
- unit: field
- .and_then(|v| v.pointer("/unit"))
- .and_then(|v| v.as_str())
- .and_then(|s| HashRateUnit::from_str(s).ok())
- .unwrap_or(HashRateUnit::GigaHash),
+ unit,
algo: self.device_info.algo,
}
.as_unit(HashRateUnit::default()),
@@ -888,11 +920,34 @@ impl GetControlBoardVersion for AntMinerV2020 {
&self,
data: &HashMap<DataField, Value>,
) -> Option<MinerControlBoard> {
- let cb_type = data.extract::<String>(DataField::ControlBoardVersion)?;
- match cb_type.as_str() {
- s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
- _ => AntMinerControlBoard::parse(cb_type.split("_").collect::<Vec<&str>>()[0])
- .map(|cb| cb.into()),
+ let field = data.get(&DataField::ControlBoardVersion)?;
+ // Explicit control-board subtype (miner_type.cgi) wins when present.
+ let subtype = field
+ .pointer("/subtype")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !subtype.is_empty() {
+ return match subtype {
+ s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
+ _ => AntMinerControlBoard::parse(subtype.split('_').next().unwrap_or(subtype))
+ .map(|cb| cb.into()),
+ };
+ }
+ // No subtype (older models): read the control board from the kernel build
+ // string instead of guessing from the model (round 12 #10). Bitmain names
+ // the SoC in the kernel version, e.g. "Linux 4.6.0-xilinx-..." (Z15) or an
+ // AMLogic/Meson kernel on newer AMLogic boards.
+ let kernel = field
+ .pointer("/kernel")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_ascii_lowercase();
+ if kernel.contains("xilinx") || kernel.contains("zynq") {
+ Some(AntMinerControlBoard::Xilinx.into())
+ } else if kernel.contains("aml") || kernel.contains("meson") {
+ Some(AntMinerControlBoard::AMLogic.into())
+ } else {
+ None
}
}
}
diff --git a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs
index 23962f35..52232c1f 100644
--- a/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs
+++ b/vendor/asic-rs-firmwares-antminer/src/backends/v2020/rpc.rs
@@ -71,7 +71,17 @@ impl AntMinerRPCAPI {
read_stream_response(&mut stream, DEFAULT_RPC_TIMEOUT).await
};
let response = response?;
- self.parse_rpc_result(&response)
+ self.parse_rpc_result(&Self::sanitize_cgminer(&response))
+ }
+
+ /// Antminer's cgminer `stats` sometimes emits an array whose objects are not
+ /// comma-separated (`...}{"STATS":0,...` on the Z15/Z15J), which is invalid
+ /// JSON that serde rejects -- dropping the whole stats command and with it
+ /// every stats-derived field (expected hashrate, wattage, fans, hashboards,
+ /// uptime). Insert the missing separators. Well-formed JSON never contains an
+ /// unseparated `}{`, so this is a no-op on valid responses (round 12 #10).
+ fn sanitize_cgminer(response: &str) -> String {
+ response.replace("}{", "},{")
}
fn parse_rpc_result(&self, response: &str) -> anyhow::Result<Value> {
diff --git a/vendor/asic-rs-firmwares-antminer/src/firmware.rs b/vendor/asic-rs-firmwares-antminer/src/firmware.rs
index fce5e8ff..46abbc9d 100644
--- a/vendor/asic-rs-firmwares-antminer/src/firmware.rs
+++ b/vendor/asic-rs-firmwares-antminer/src/firmware.rs
@@ -142,18 +142,9 @@ async fn get_model_with_auth(
}
}
-/// Fetch the firmware version from a miner using digest auth.
-async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
- let client = build_discovery_client().ok()?;
- let data: Response = client
- .get(format!("http://{ip}/cgi-bin/summary.cgi"))
- .send_digest_auth((auth.username(), auth.password()))
- .await
- .ok()?;
-
- let json_data = data.json::<serde_json::Value>().await.ok()?;
- let fw_version = json_data["INFO"]["CompileTime"].as_str().unwrap_or("");
-
+/// Parse an Antminer cgminer `CompileTime` string ("Mon Dec 14 18:01:42 CST
+/// 2020") into a date-based semver (year.month.day) used to pick the backend.
+fn parse_antminer_compile_time(fw_version: &str) -> Option<semver::Version> {
let cleaned: String = {
let mut parts: Vec<&str> = fw_version.split_whitespace().collect();
if parts.len() > 4 {
@@ -161,9 +152,7 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
}
parts.join(" ")
};
-
let dt = NaiveDateTime::parse_from_str(&cleaned, "%a %b %e %H:%M:%S %Y").ok()?;
-
Some(semver::Version::new(
dt.year() as u64,
dt.month() as u64,
@@ -171,6 +160,34 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
))
}
+/// Fetch the firmware version (as a date-based semver) to pick the backend.
+async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
+ // Newer Antminers expose the firmware CompileTime via summary.cgi.
+ if let Ok(client) = build_discovery_client()
+ && let Ok(data) = client
+ .get(format!("http://{ip}/cgi-bin/summary.cgi"))
+ .send_digest_auth((auth.username(), auth.password()))
+ .await
+ && let Ok(json_data) = data.json::<serde_json::Value>().await
+ && let Some(v) =
+ parse_antminer_compile_time(json_data["INFO"]["CompileTime"].as_str().unwrap_or(""))
+ {
+ return Some(v);
+ }
+
+ // Older models (e.g. Z15/Z15J) have no summary.cgi, so summary-based version
+ // detection returns nothing and the miner would default to the newest
+ // backend and be mis-parsed. Fall back to the cgminer :4028 `version` RPC,
+ // which still reports the CompileTime, so the right (older) backend is picked
+ // (round 12 #10).
+ let rpc = asic_rs_core::util::send_rpc_command(&ip, "version").await?;
+ parse_antminer_compile_time(
+ rpc.pointer("/VERSION/0/CompileTime")
+ .and_then(|v| v.as_str())
+ .unwrap_or(""),
+ )
+}
+
#[async_trait]
impl MinerFirmware for AntMinerStockFirmware {
/// Uses default credentials. For custom credentials, use `build_miner`
+21 -1
View File
@@ -10,7 +10,7 @@
+pub use widgets::*;
--- a/src/widgets.rs
+++ b/src/widgets.rs
@@ -0,0 +1,794 @@
@@ -0,0 +1,814 @@
+// widgets.rs — alkane-toolkit extension: Rust bindings for the widget bridge
+// in cpp_src/widgets_bridge.cpp. Handles are opaque pointers owned by the
+// wxWidgets object tree (parents own children; nothing to free in Rust).
@@ -117,6 +117,8 @@
+ pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
+ pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
+ pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
+ pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
+ pub fn wxbr_set_light_pulse(on: c_int);
+ pub fn wxbr_bind_sys_colour(win: *mut c_void);
+ pub fn wxbr_destroy(win: *mut c_void);
+ pub fn wxbr_destroy_children(win: *mut c_void);
@@ -213,6 +215,24 @@
+ unsafe { notsafe::wxbr_status_indicator_set(c.as_ptr(), r as c_int, g as c_int, b as c_int) }
+}
+
+/// Register a raw SVG for a table-cell shape sentinel (a control-char code point)
+/// so the segment renderer can draw it recoloured to each cell's segment colour.
+/// `vbw`/`vbh` are the SVG viewBox dimensions, used to keep the icon's aspect
+/// ratio when it is rasterised at the cell height (round 12 #9/#11).
+pub fn register_shape_svg(sentinel: u32, svg: &str, vbw: i32, vbh: i32) {
+ let c = CString::new(svg).unwrap_or_default();
+ unsafe {
+ notsafe::wxbr_register_shape_svg(sentinel as c_int, c.as_ptr(), vbw as c_int, vbh as c_int)
+ }
+}
+
+/// Start (or stop) the locate-light dot fade animation. Call with `true` while at
+/// least one miner's locate light is flashing so the table repaint timer only
+/// runs when there is a pulsing dot to animate (round 12 #6).
+pub fn set_light_pulse(on: bool) {
+ unsafe { notsafe::wxbr_set_light_pulse(on as c_int) }
+}
+
+/// Open a URL in the system default browser. Returns true on success.
+pub fn launch_browser(url: &str) -> bool {
+ let c = CString::new(url).unwrap_or_default();
+221 -12
View File
@@ -1,6 +1,6 @@
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -0,0 +1,1413 @@
@@ -0,0 +1,1622 @@
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
+// render-callback bridge (which is kept untouched).
@@ -37,6 +37,7 @@
+#include <wx/statusbr.h>
+#include <cstring>
+#include <cstdio>
+#include <cmath>
+#include <map>
+#include <vector>
+#ifdef __WXGTK__
@@ -159,27 +160,154 @@
+const wxUniChar SHAPE_DOT = 0x07; // filled status dot (hashboards, locate light)
+const wxUniChar SHAPE_LOCK = 0x02; // closed padlock (locked / view-only)
+const wxUniChar SHAPE_UNLOCK = 0x03; // open padlock (unlocked / writable)
+// Status-column KPI icons (round 12 #11): each renders the same Font Awesome
+// glyph as its dashboard KPI card, drawn from an SVG registered by the Rust side
+// (see wxbr_register_shape_svg). No vector fallback -- if unregistered the cell
+// is simply blank.
+const wxUniChar SHAPE_HASHING = 0x04; // rabbit (hashing)
+const wxUniChar SHAPE_SLOW = 0x05; // turtle (slow)
+const wxUniChar SHAPE_NOTHASHING = 0x06; // cracked wine glass (not hashing)
+const wxUniChar SHAPE_PAUSED = 0x08; // otter (paused)
+const wxUniChar SHAPE_PULSE_DOT = 0x0B; // locate-light dot that fades in/out (round 12 #6)
+const int SHAPE_ADVANCE = 15; // horizontal space one shape occupies
+
+// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
+// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
+// the timer can invalidate exactly it.
+double g_pulse_phase = 0.0;
+wxDataViewCtrl* g_pulse_target = nullptr;
+
+bool IsShapeSentinel(const wxString& s, wxUniChar& out) {
+ if (s.length() != 1) return false;
+ wxUniChar c = s[0];
+ if (c == SHAPE_DOT || c == SHAPE_LOCK || c == SHAPE_UNLOCK) {
+ if (c == SHAPE_DOT || c == SHAPE_LOCK || c == SHAPE_UNLOCK ||
+ c == SHAPE_HASHING || c == SHAPE_SLOW || c == SHAPE_NOTHASHING ||
+ c == SHAPE_PAUSED || c == SHAPE_PULSE_DOT) {
+ out = c;
+ return true;
+ }
+ return false;
+}
+
+// Draw one shape sentinel, centred in the SHAPE_ADVANCE-wide slot at x.
+void DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell, const wxColour& colour) {
+// Blend `fg` toward `bg` by alpha (1.0 = fully fg), used to fade the locate dot.
+wxColour BlendColour(const wxColour& bg, const wxColour& fg, double a) {
+ auto mix = [a](unsigned char b, unsigned char f) {
+ double v = (double)b * (1.0 - a) + (double)f * a + 0.5;
+ if (v < 0) v = 0;
+ if (v > 255) v = 255;
+ return (unsigned char)v;
+ };
+ return wxColour(mix(bg.Red(), fg.Red()), mix(bg.Green(), fg.Green()), mix(bg.Blue(), fg.Blue()));
+}
+
+// Drives the locate-light dot's fade (round 12 #6): while running it advances the
+// phase and repaints the treeview so the SHAPE_PULSE_DOT cells re-render at the
+// new opacity. Runs only while at least one locate light is flashing.
+class PulseTimer : public wxTimer {
+ public:
+ void Notify() override {
+ g_pulse_phase += 0.4; // ~1.6 s cycle at the 100 ms tick below
+ if (!g_pulse_target) return;
+ // A plain Refresh() does not re-invoke the custom cell renderer under wxGTK
+ // (GtkTreeView caches rendered cells); emitting a row change does, so the
+ // SHAPE_PULSE_DOT cells re-render at the new phase. The timer only runs while
+ // a light is flashing, so touching every row here is cheap.
+ AttrListStore* store = dynamic_cast<AttrListStore*>(g_pulse_target->GetModel());
+ if (store) {
+ unsigned int n = store->GetItemCount();
+ for (unsigned int r = 0; r < n; r++) store->RowChanged(r);
+ } else {
+ g_pulse_target->Refresh();
+ }
+ }
+};
+PulseTimer* g_pulse_timer = nullptr;
+
+void SetLightPulse(bool on) {
+ if (!g_pulse_timer) g_pulse_timer = new PulseTimer();
+ if (on) {
+ if (!g_pulse_timer->IsRunning()) g_pulse_timer->Start(100);
+ } else {
+ g_pulse_timer->Stop();
+ if (g_pulse_target) g_pulse_target->Refresh();
+ }
+}
+
+// Registry of SVG-backed shape icons (round 12 #9 access padlocks, #11 status
+// icons). The Rust side registers a raw SVG (with its viewBox dims for aspect)
+// per sentinel; DrawShape recolours it to the segment colour, rasterises once
+// per (sentinel, colour, height), caches the bitmap, and draws it. The access
+// padlocks (0x02/0x03) fall back to a hand-drawn vector when unregistered.
+struct ShapeSvg {
+ wxString svg;
+ int vbw;
+ int vbh;
+};
+std::map<int, ShapeSvg> g_shape_svgs;
+std::map<uint64_t, wxBitmap> g_shape_bmp_cache;
+
+const ShapeSvg* LookupShapeSvg(wxUniChar shape) {
+ auto it = g_shape_svgs.find((int)shape.GetValue());
+ return it == g_shape_svgs.end() ? nullptr : &it->second;
+}
+
+// Recolour an SVG to `c`, matching the Rust svg_recolored(): replace
+// fill="currentColor" and inject a root fill so shapes that omit a fill inherit
+// the colour too (e.g. the Font Awesome Free otter).
+wxString RecolorShapeSvg(const wxString& svg, const wxColour& c) {
+ wxString hex = wxString::Format("#%02X%02X%02X", (int)c.Red(), (int)c.Green(), (int)c.Blue());
+ wxString s = svg;
+ s.Replace("currentColor", hex);
+ int pos = s.Find("<svg ");
+ if (pos != wxNOT_FOUND) s.insert((size_t)pos + 5, wxString("fill=\"") + hex + "\" ");
+ return s;
+}
+
+const wxBitmap& ShapeBitmap(wxUniChar shape, const ShapeSvg& sv, const wxColour& col,
+ int w, int h) {
+ uint64_t rgb = ((uint64_t)col.Red() << 16) | ((uint64_t)col.Green() << 8) | (uint64_t)col.Blue();
+ uint64_t key = ((uint64_t)(unsigned)shape.GetValue() << 40) | (rgb << 8) | (uint64_t)(h & 0xFF);
+ auto it = g_shape_bmp_cache.find(key);
+ if (it != g_shape_bmp_cache.end()) return it->second;
+ wxString colored = RecolorShapeSvg(sv.svg, col);
+ wxBitmapBundle bundle = wxBitmapBundle::FromSVG(colored.ToUTF8().data(), wxSize(w, h));
+ wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
+ return g_shape_bmp_cache.emplace(key, bmp).first->second;
+}
+
+// Draw one shape sentinel centred at x; returns the horizontal space it used
+// (SHAPE_ADVANCE for the vector shapes, the icon width for a wider SVG icon).
+// `bg` is the cell background the shape sits on, used to fade the pulsing dot.
+int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
+ const wxColour& colour, const wxColour& bg) {
+ int cy = cell.y + cell.height / 2;
+ // SVG-backed icon (access padlocks #9, status KPI icons #11): recolour to the
+ // segment colour, rasterise (cached), and draw centred in its slot.
+ if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
+ int h = cell.height - 4;
+ if (h > 15) h = 15;
+ if (h < 8) h = 8;
+ int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h;
+ if (w < 1) w = 1;
+ const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, w, h);
+ if (bmp.IsOk()) {
+ int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
+ dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
+ return slot;
+ }
+ }
+ int cx = x + SHAPE_ADVANCE / 2;
+ if (shape == SHAPE_DOT) {
+ if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
+ wxColour fill = colour;
+ if (shape == SHAPE_PULSE_DOT) {
+ // Fade between ~0.3 and 1.0 opacity over a ~1.6 s cycle (round 12 #6).
+ double a = 0.3 + 0.7 * (0.5 + 0.5 * std::sin(g_pulse_phase));
+ fill = BlendColour(bg, colour, a);
+ }
+ dc->SetPen(*wxTRANSPARENT_PEN);
+ dc->SetBrush(wxBrush(colour));
+ dc->SetBrush(wxBrush(fill));
+ dc->DrawCircle(cx, cy, 4);
+ return;
+ return SHAPE_ADVANCE;
+ }
+ // Padlock: a filled body with a staple shackle above. The colour carries the
+ // state (green = unlocked, red = locked); the shackle is drawn ajar when open.
@@ -201,6 +329,7 @@
+ dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
+ else
+ dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
+ return SHAPE_ADVANCE;
+}
+
+} // namespace
@@ -275,8 +404,16 @@
+ // selection highlight (round 11 #10/#13).
+ wxUniChar shape;
+ if (IsShapeSentinel(seg.text, shape)) {
+ DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain);
+ x += SHAPE_ADVANCE;
+ // Background the shape sits on, so the pulsing locate dot fades toward it.
+ wxColour cellbg;
+ if (selected) {
+ cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
+ } else if (GetAttr().HasBackgroundColour()) {
+ cellbg = GetAttr().GetBackgroundColour();
+ } else {
+ cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
+ }
+ x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
+ continue;
+ }
+ if (seg.text.IsEmpty()) continue;
@@ -294,7 +431,13 @@
+ for (const ColorSegment& seg : ParseColorSegments(m_value)) {
+ wxUniChar shape;
+ if (IsShapeSentinel(seg.text, shape)) {
+ w += SHAPE_ADVANCE;
+ int adv = SHAPE_ADVANCE;
+ if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
+ int hh = 15;
+ int ww = (sv->vbh > 0) ? (int)((double)hh * sv->vbw / sv->vbh + 0.5) : hh;
+ if (ww > adv) adv = ww;
+ }
+ w += adv;
+ if (h < 12) h = 12;
+ continue;
+ }
@@ -552,12 +695,31 @@
+// ---- check list box ---------------------------------------------------------
+
+void* wxbr_check_list_box(void* parent) {
+ // wxLB_EXTENDED so several rows can be selected at once (ctrl/shift-click and
+ // rubber-band drag, native to wxListBox); a checkbox toggle on any selected
+ // row then applies to every selected row (see the handler below). This is the
+ // Excel-style batch-check the filter menu needs (round 12 #7).
+ wxCheckListBox* clb = new wxCheckListBox((wxWindow*)parent, wxID_ANY,
+ wxDefaultPosition, wxSize(-1, -1),
+ 0, NULL, wxLB_SINGLE | wxLB_NEEDED_SB);
+ 0, NULL, wxLB_EXTENDED | wxLB_NEEDED_SB);
+ clb->Bind(wxEVT_CHECKLISTBOX, [clb](wxCommandEvent& e) {
+ int idx = e.GetInt();
+ // Batch toggle: if the clicked row is part of a multi-row selection, give
+ // every selected row the clicked row's new state. Check() does not itself
+ // fire wxEVT_CHECKLISTBOX, so there is no recursion.
+ wxArrayInt sel;
+ clb->GetSelections(sel);
+ if (sel.GetCount() > 1) {
+ bool inSel = false;
+ for (size_t i = 0; i < sel.GetCount(); i++)
+ if (sel[i] == idx) { inSel = true; break; }
+ if (inSel) {
+ bool state = clb->IsChecked(idx);
+ for (size_t i = 0; i < sel.GetCount(); i++) clb->Check(sel[i], state);
+ }
+ }
+ if (g_widget_event)
+ g_widget_event(WxEV_CLB_TOGGLED, (long)(intptr_t)clb, e.GetInt());
+ g_widget_event(WxEV_CLB_TOGGLED, (long)(intptr_t)clb, idx);
+ });
+ return (void*)clb;
+}
@@ -675,6 +837,7 @@
+ AttrListStore* store = new AttrListStore();
+ dv->AssociateModel(store);
+ store->DecRef(); // the control owns a reference now
+ g_pulse_target = dv; // the locate-dot pulse timer repaints this control
+ dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
+ if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
+ });
@@ -1155,6 +1318,34 @@
+ lc->SetItemData(row, (long)idx);
+ lc->CheckItem(row, enc >= 0);
+ }
+ // Batch checkbox toggle: checking/unchecking a row that is part of a
+ // multi-row selection applies the same state to every selected row, so the
+ // user can ctrl/shift-click several columns and show/hide them together
+ // (round 12 #7). CheckItem() re-enters this handler, so guard against it.
+ auto batchCheck = [lc](long item, bool state) {
+ static bool busy = false;
+ if (busy) return;
+ if (!(lc->GetItemState(item, wxLIST_STATE_SELECTED) & wxLIST_STATE_SELECTED))
+ return;
+ wxVector<long> sel;
+ long it = -1;
+ for (;;) {
+ it = lc->GetNextItem(it, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
+ if (it == -1) break;
+ sel.push_back(it);
+ }
+ if (sel.size() <= 1) return;
+ busy = true;
+ for (size_t i = 0; i < sel.size(); i++)
+ if (sel[i] != item) lc->CheckItem(sel[i], state);
+ busy = false;
+ };
+ lc->Bind(wxEVT_LIST_ITEM_CHECKED, [batchCheck](wxListEvent& e) {
+ batchCheck(e.GetIndex(), true);
+ });
+ lc->Bind(wxEVT_LIST_ITEM_UNCHECKED, [batchCheck](wxListEvent& e) {
+ batchCheck(e.GetIndex(), false);
+ });
+ lc->Bind(wxEVT_LIST_BEGIN_DRAG, [lc](wxListEvent&) {
+ g_reorder_drag.clear();
+ g_reorder_list = lc;
@@ -1334,6 +1525,24 @@
+ return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
+}
+
+// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
+// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
+// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
+// any prior registration for that sentinel and invalidates the bitmap cache.
+void wxbr_register_shape_svg(int sentinel, const char* svg, int vbw, int vbh) {
+ ShapeSvg s;
+ s.svg = wxString::FromUTF8(svg);
+ s.vbw = vbw;
+ s.vbh = vbh;
+ g_shape_svgs[sentinel] = s;
+ g_shape_bmp_cache.clear();
+}
+
+// Start/stop the locate-light dot fade animation (round 12 #6). The Rust side
+// calls this after each refresh with whether any miner's locate light is
+// flashing, so the repaint timer only runs when there is a dot to animate.
+void wxbr_set_light_pulse(int on) { SetLightPulse(on != 0); }
+
+// ---- live theme changes -----------------------------------------------------
+
+// Emit WxEV_SYS_COLOUR when the OS light/dark theme changes so the app can
@@ -34,6 +34,7 @@
#include <wx/statusbr.h>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <map>
#include <vector>
#ifdef __WXGTK__
@@ -156,27 +157,154 @@ std::vector<ColorSegment> ParseColorSegments(const wxString& value) {
const wxUniChar SHAPE_DOT = 0x07; // filled status dot (hashboards, locate light)
const wxUniChar SHAPE_LOCK = 0x02; // closed padlock (locked / view-only)
const wxUniChar SHAPE_UNLOCK = 0x03; // open padlock (unlocked / writable)
// Status-column KPI icons (round 12 #11): each renders the same Font Awesome
// glyph as its dashboard KPI card, drawn from an SVG registered by the Rust side
// (see wxbr_register_shape_svg). No vector fallback -- if unregistered the cell
// is simply blank.
const wxUniChar SHAPE_HASHING = 0x04; // rabbit (hashing)
const wxUniChar SHAPE_SLOW = 0x05; // turtle (slow)
const wxUniChar SHAPE_NOTHASHING = 0x06; // cracked wine glass (not hashing)
const wxUniChar SHAPE_PAUSED = 0x08; // otter (paused)
const wxUniChar SHAPE_PULSE_DOT = 0x0B; // locate-light dot that fades in/out (round 12 #6)
const int SHAPE_ADVANCE = 15; // horizontal space one shape occupies
// Animation phase for the pulsing locate-light dot (round 12 #6), advanced by a
// wxTimer while any such dot is on screen; the treeview it repaints is tracked so
// the timer can invalidate exactly it.
double g_pulse_phase = 0.0;
wxDataViewCtrl* g_pulse_target = nullptr;
bool IsShapeSentinel(const wxString& s, wxUniChar& out) {
if (s.length() != 1) return false;
wxUniChar c = s[0];
if (c == SHAPE_DOT || c == SHAPE_LOCK || c == SHAPE_UNLOCK) {
if (c == SHAPE_DOT || c == SHAPE_LOCK || c == SHAPE_UNLOCK ||
c == SHAPE_HASHING || c == SHAPE_SLOW || c == SHAPE_NOTHASHING ||
c == SHAPE_PAUSED || c == SHAPE_PULSE_DOT) {
out = c;
return true;
}
return false;
}
// Draw one shape sentinel, centred in the SHAPE_ADVANCE-wide slot at x.
void DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell, const wxColour& colour) {
// Blend `fg` toward `bg` by alpha (1.0 = fully fg), used to fade the locate dot.
wxColour BlendColour(const wxColour& bg, const wxColour& fg, double a) {
auto mix = [a](unsigned char b, unsigned char f) {
double v = (double)b * (1.0 - a) + (double)f * a + 0.5;
if (v < 0) v = 0;
if (v > 255) v = 255;
return (unsigned char)v;
};
return wxColour(mix(bg.Red(), fg.Red()), mix(bg.Green(), fg.Green()), mix(bg.Blue(), fg.Blue()));
}
// Drives the locate-light dot's fade (round 12 #6): while running it advances the
// phase and repaints the treeview so the SHAPE_PULSE_DOT cells re-render at the
// new opacity. Runs only while at least one locate light is flashing.
class PulseTimer : public wxTimer {
public:
void Notify() override {
g_pulse_phase += 0.4; // ~1.6 s cycle at the 100 ms tick below
if (!g_pulse_target) return;
// A plain Refresh() does not re-invoke the custom cell renderer under wxGTK
// (GtkTreeView caches rendered cells); emitting a row change does, so the
// SHAPE_PULSE_DOT cells re-render at the new phase. The timer only runs while
// a light is flashing, so touching every row here is cheap.
AttrListStore* store = dynamic_cast<AttrListStore*>(g_pulse_target->GetModel());
if (store) {
unsigned int n = store->GetItemCount();
for (unsigned int r = 0; r < n; r++) store->RowChanged(r);
} else {
g_pulse_target->Refresh();
}
}
};
PulseTimer* g_pulse_timer = nullptr;
void SetLightPulse(bool on) {
if (!g_pulse_timer) g_pulse_timer = new PulseTimer();
if (on) {
if (!g_pulse_timer->IsRunning()) g_pulse_timer->Start(100);
} else {
g_pulse_timer->Stop();
if (g_pulse_target) g_pulse_target->Refresh();
}
}
// Registry of SVG-backed shape icons (round 12 #9 access padlocks, #11 status
// icons). The Rust side registers a raw SVG (with its viewBox dims for aspect)
// per sentinel; DrawShape recolours it to the segment colour, rasterises once
// per (sentinel, colour, height), caches the bitmap, and draws it. The access
// padlocks (0x02/0x03) fall back to a hand-drawn vector when unregistered.
struct ShapeSvg {
wxString svg;
int vbw;
int vbh;
};
std::map<int, ShapeSvg> g_shape_svgs;
std::map<uint64_t, wxBitmap> g_shape_bmp_cache;
const ShapeSvg* LookupShapeSvg(wxUniChar shape) {
auto it = g_shape_svgs.find((int)shape.GetValue());
return it == g_shape_svgs.end() ? nullptr : &it->second;
}
// Recolour an SVG to `c`, matching the Rust svg_recolored(): replace
// fill="currentColor" and inject a root fill so shapes that omit a fill inherit
// the colour too (e.g. the Font Awesome Free otter).
wxString RecolorShapeSvg(const wxString& svg, const wxColour& c) {
wxString hex = wxString::Format("#%02X%02X%02X", (int)c.Red(), (int)c.Green(), (int)c.Blue());
wxString s = svg;
s.Replace("currentColor", hex);
int pos = s.Find("<svg ");
if (pos != wxNOT_FOUND) s.insert((size_t)pos + 5, wxString("fill=\"") + hex + "\" ");
return s;
}
const wxBitmap& ShapeBitmap(wxUniChar shape, const ShapeSvg& sv, const wxColour& col,
int w, int h) {
uint64_t rgb = ((uint64_t)col.Red() << 16) | ((uint64_t)col.Green() << 8) | (uint64_t)col.Blue();
uint64_t key = ((uint64_t)(unsigned)shape.GetValue() << 40) | (rgb << 8) | (uint64_t)(h & 0xFF);
auto it = g_shape_bmp_cache.find(key);
if (it != g_shape_bmp_cache.end()) return it->second;
wxString colored = RecolorShapeSvg(sv.svg, col);
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(colored.ToUTF8().data(), wxSize(w, h));
wxBitmap bmp = bundle.GetBitmap(wxSize(w, h));
return g_shape_bmp_cache.emplace(key, bmp).first->second;
}
// Draw one shape sentinel centred at x; returns the horizontal space it used
// (SHAPE_ADVANCE for the vector shapes, the icon width for a wider SVG icon).
// `bg` is the cell background the shape sits on, used to fade the pulsing dot.
int DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell,
const wxColour& colour, const wxColour& bg) {
int cy = cell.y + cell.height / 2;
// SVG-backed icon (access padlocks #9, status KPI icons #11): recolour to the
// segment colour, rasterise (cached), and draw centred in its slot.
if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
int h = cell.height - 4;
if (h > 15) h = 15;
if (h < 8) h = 8;
int w = (sv->vbh > 0) ? (int)((double)h * sv->vbw / sv->vbh + 0.5) : h;
if (w < 1) w = 1;
const wxBitmap& bmp = ShapeBitmap(shape, *sv, colour, w, h);
if (bmp.IsOk()) {
int slot = (w > SHAPE_ADVANCE) ? w : SHAPE_ADVANCE;
dc->DrawBitmap(bmp, x + (slot - w) / 2, cy - h / 2, true);
return slot;
}
}
int cx = x + SHAPE_ADVANCE / 2;
if (shape == SHAPE_DOT) {
if (shape == SHAPE_DOT || shape == SHAPE_PULSE_DOT) {
wxColour fill = colour;
if (shape == SHAPE_PULSE_DOT) {
// Fade between ~0.3 and 1.0 opacity over a ~1.6 s cycle (round 12 #6).
double a = 0.3 + 0.7 * (0.5 + 0.5 * std::sin(g_pulse_phase));
fill = BlendColour(bg, colour, a);
}
dc->SetPen(*wxTRANSPARENT_PEN);
dc->SetBrush(wxBrush(colour));
dc->SetBrush(wxBrush(fill));
dc->DrawCircle(cx, cy, 4);
return;
return SHAPE_ADVANCE;
}
// Padlock: a filled body with a staple shackle above. The colour carries the
// state (green = unlocked, red = locked); the shackle is drawn ajar when open.
@@ -198,6 +326,7 @@ void DrawShape(wxDC* dc, wxUniChar shape, wxCoord x, const wxRect& cell, const w
dc->DrawLine(rx, legTop, rx, legTop + sr); // ajar: right leg lifted
else
dc->DrawLine(rx, legTop, rx, by); // closed: right leg to body
return SHAPE_ADVANCE;
}
} // namespace
@@ -272,8 +401,16 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
// selection highlight (round 11 #10/#13).
wxUniChar shape;
if (IsShapeSentinel(seg.text, shape)) {
DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain);
x += SHAPE_ADVANCE;
// Background the shape sits on, so the pulsing locate dot fades toward it.
wxColour cellbg;
if (selected) {
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
} else if (GetAttr().HasBackgroundColour()) {
cellbg = GetAttr().GetBackgroundColour();
} else {
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
}
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
continue;
}
if (seg.text.IsEmpty()) continue;
@@ -291,7 +428,13 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
for (const ColorSegment& seg : ParseColorSegments(m_value)) {
wxUniChar shape;
if (IsShapeSentinel(seg.text, shape)) {
w += SHAPE_ADVANCE;
int adv = SHAPE_ADVANCE;
if (const ShapeSvg* sv = LookupShapeSvg(shape)) {
int hh = 15;
int ww = (sv->vbh > 0) ? (int)((double)hh * sv->vbw / sv->vbh + 0.5) : hh;
if (ww > adv) adv = ww;
}
w += adv;
if (h < 12) h = 12;
continue;
}
@@ -549,12 +692,31 @@ void wxbr_check_box_set(void* win, int v) {
// ---- check list box ---------------------------------------------------------
void* wxbr_check_list_box(void* parent) {
// wxLB_EXTENDED so several rows can be selected at once (ctrl/shift-click and
// rubber-band drag, native to wxListBox); a checkbox toggle on any selected
// row then applies to every selected row (see the handler below). This is the
// Excel-style batch-check the filter menu needs (round 12 #7).
wxCheckListBox* clb = new wxCheckListBox((wxWindow*)parent, wxID_ANY,
wxDefaultPosition, wxSize(-1, -1),
0, NULL, wxLB_SINGLE | wxLB_NEEDED_SB);
0, NULL, wxLB_EXTENDED | wxLB_NEEDED_SB);
clb->Bind(wxEVT_CHECKLISTBOX, [clb](wxCommandEvent& e) {
int idx = e.GetInt();
// Batch toggle: if the clicked row is part of a multi-row selection, give
// every selected row the clicked row's new state. Check() does not itself
// fire wxEVT_CHECKLISTBOX, so there is no recursion.
wxArrayInt sel;
clb->GetSelections(sel);
if (sel.GetCount() > 1) {
bool inSel = false;
for (size_t i = 0; i < sel.GetCount(); i++)
if (sel[i] == idx) { inSel = true; break; }
if (inSel) {
bool state = clb->IsChecked(idx);
for (size_t i = 0; i < sel.GetCount(); i++) clb->Check(sel[i], state);
}
}
if (g_widget_event)
g_widget_event(WxEV_CLB_TOGGLED, (long)(intptr_t)clb, e.GetInt());
g_widget_event(WxEV_CLB_TOGGLED, (long)(intptr_t)clb, idx);
});
return (void*)clb;
}
@@ -672,6 +834,7 @@ void* wxbr_dvlc(void* parent) {
AttrListStore* store = new AttrListStore();
dv->AssociateModel(store);
store->DecRef(); // the control owns a reference now
g_pulse_target = dv; // the locate-dot pulse timer repaints this control
dv->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [](wxDataViewEvent&) {
if (g_widget_event) g_widget_event(WxEV_DVLC_SELECTION_CHANGED, 0, 0);
});
@@ -1152,6 +1315,34 @@ void* wxbr_reorder_list(void* parent, int n, const int* order, const char** item
lc->SetItemData(row, (long)idx);
lc->CheckItem(row, enc >= 0);
}
// Batch checkbox toggle: checking/unchecking a row that is part of a
// multi-row selection applies the same state to every selected row, so the
// user can ctrl/shift-click several columns and show/hide them together
// (round 12 #7). CheckItem() re-enters this handler, so guard against it.
auto batchCheck = [lc](long item, bool state) {
static bool busy = false;
if (busy) return;
if (!(lc->GetItemState(item, wxLIST_STATE_SELECTED) & wxLIST_STATE_SELECTED))
return;
wxVector<long> sel;
long it = -1;
for (;;) {
it = lc->GetNextItem(it, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (it == -1) break;
sel.push_back(it);
}
if (sel.size() <= 1) return;
busy = true;
for (size_t i = 0; i < sel.size(); i++)
if (sel[i] != item) lc->CheckItem(sel[i], state);
busy = false;
};
lc->Bind(wxEVT_LIST_ITEM_CHECKED, [batchCheck](wxListEvent& e) {
batchCheck(e.GetIndex(), true);
});
lc->Bind(wxEVT_LIST_ITEM_UNCHECKED, [batchCheck](wxListEvent& e) {
batchCheck(e.GetIndex(), false);
});
lc->Bind(wxEVT_LIST_BEGIN_DRAG, [lc](wxListEvent&) {
g_reorder_drag.clear();
g_reorder_list = lc;
@@ -1331,6 +1522,24 @@ void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bmp);
}
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
// any prior registration for that sentinel and invalidates the bitmap cache.
void wxbr_register_shape_svg(int sentinel, const char* svg, int vbw, int vbh) {
ShapeSvg s;
s.svg = wxString::FromUTF8(svg);
s.vbw = vbw;
s.vbh = vbh;
g_shape_svgs[sentinel] = s;
g_shape_bmp_cache.clear();
}
// Start/stop the locate-light dot fade animation (round 12 #6). The Rust side
// calls this after each refresh with whether any miner's locate light is
// flashing, so the repaint timer only runs when there is a dot to animate.
void wxbr_set_light_pulse(int on) { SetLightPulse(on != 0); }
// ---- live theme changes -----------------------------------------------------
// Emit WxEV_SYS_COLOUR when the OS light/dark theme changes so the app can
+20
View File
@@ -104,6 +104,8 @@ mod notsafe {
pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
pub fn wxbr_set_light_pulse(on: c_int);
pub fn wxbr_bind_sys_colour(win: *mut c_void);
pub fn wxbr_destroy(win: *mut c_void);
pub fn wxbr_destroy_children(win: *mut c_void);
@@ -200,6 +202,24 @@ pub fn status_indicator_set(text: &str, r: u8, g: u8, b: u8) {
unsafe { notsafe::wxbr_status_indicator_set(c.as_ptr(), r as c_int, g as c_int, b as c_int) }
}
/// Register a raw SVG for a table-cell shape sentinel (a control-char code point)
/// so the segment renderer can draw it recoloured to each cell's segment colour.
/// `vbw`/`vbh` are the SVG viewBox dimensions, used to keep the icon's aspect
/// ratio when it is rasterised at the cell height (round 12 #9/#11).
pub fn register_shape_svg(sentinel: u32, svg: &str, vbw: i32, vbh: i32) {
let c = CString::new(svg).unwrap_or_default();
unsafe {
notsafe::wxbr_register_shape_svg(sentinel as c_int, c.as_ptr(), vbw as c_int, vbh as c_int)
}
}
/// Start (or stop) the locate-light dot fade animation. Call with `true` while at
/// least one miner's locate light is flashing so the table repaint timer only
/// runs when there is a pulsing dot to animate (round 12 #6).
pub fn set_light_pulse(on: bool) {
unsafe { notsafe::wxbr_set_light_pulse(on as c_int) }
}
/// Open a URL in the system default browser. Returns true on success.
pub fn launch_browser(url: &str) -> bool {
let c = CString::new(url).unwrap_or_default();
+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":"6e42d50107b1a43fd7cf4a4c4f538468a337ed219ad8d6b23bd9abdabd123bd5","Cargo.lock":"7f984c7231c91f2def8f3e2e923a85c2e0b3239492f5ce23400881ea4de1aa16","Cargo.toml":"8a447efc18cd97d019a9771fb258b06f694499500561564eec75480e46bcc554","Cargo.toml.orig":"6c9e7b86804255debe03545c6358eb975d3d470810a19e6c40c680299a686b1f","src/backends/mod.rs":"65cdc60cdf38968f5a7e197338f4cf6173406ce69a4f0aaa96a9e29f4f581b6e","src/backends/v2020/firmware.rs":"5a41bfb8f42f17523e68f8702e87d75bcdb268bd4950bb66227f6966ef3576a9","src/backends/v2020/mod.rs":"f1972769a1b4811d5772e96b2e6c45b461cdcb4175355dba2b586b9df776fc1d","src/backends/v2020/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2020/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/backends/v2023_07/firmware.rs":"c07668e351d48dab3e24511b1aa9ab5e408bbcb5a438fdb0542a1377f94b9bbb","src/backends/v2023_07/mod.rs":"278e4dd04a753858e12df96ead3522aef0616ebf6f27b3da4f1a12b064c19ee6","src/backends/v2023_07/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2023_07/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/firmware.rs":"55d5b722632c0a5cfcf1f8c8252a88c5a1ece887173bb513cca0b22b874d628f","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"a3ef4d6805bb4f8ea087e3a9b875e5a1664580e1ff3e3cd2015bb0c5c18ae7bb","src/test/json/v2020/devs.json":"df17cdfc9522e23450702b93f70ff701892db54c6ce6d986300453ad5e0d22db","src/test/json/v2020/mod.rs":"4c2512d36af834d400a865a94c2e8b1919f9d8dcbf54ab2530c73861c51af67d","src/test/json/v2020/pools.json":"4c4d19ad3ef0de84bfb18daaa48428b5f7917d23287c0196eacf3a6e389e7634","src/test/json/v2020/stats.json":"6d3cb463abb7539ae77aa44ef38e62a5dc0db54670aeacf3bbd01e83f49aa1fd","src/test/json/v2020/summary.json":"2f18c81f989b7c5f70dcb0ddac0520e56ec98b6da25c24e59354a6126c965dae","src/test/json/v2020/system_info.json":"51d1ce922e39a254518a24be56ca86ef1b5843582fb26c1ff0ec4ff6f8f91ccf","src/test/json/v2020/version.json":"ae898c4c9ea3462c3e79f9de755f1fccb4ef122b94a4a512e61aa74491c1a8e9","src/test/json/v2023_07/l11_stats.json":"2eab324f253ced9a0ea4e46466691e0e71fc6fde7558fec86bd5acf6bb9c717d","src/test/json/v2023_07/l11_summary.json":"1e0fdb61b968005d0ec5393d9dc889b09efb1398ffa427629bcc0a98d1b67c22","src/test/json/v2023_07/l11_version.json":"d116921a71731c6e492aed109731c39561e34a24c7df2a88d11ac52b80f6100a","src/test/json/v2023_07/l9_stats.json":"731ee545f16dafd356d22703248b91a37f74585ad73cc27441eb3461ce53dca0","src/test/json/v2023_07/l9_summary.json":"b32b5131ad46859b270d2dbb6bdba3c4e5d7301298daee4ce56332c98faaf81d","src/test/json/v2023_07/l9_version.json":"82f03ca6ea8873f12c4d9455f21b98c547801b58fbff1dcd83c837c0f337a129","src/test/json/v2023_07/mod.rs":"1360a8b155b120f2e755ede0736bcc0d76a9d1d693b984a1b51a16e6c0413791","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"0c06e3ecbf95ae3fe5e30aacae55cf6e7ad3d965f4a93b2f85c7b64f61fc75e2"}
{"$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":"6e42d50107b1a43fd7cf4a4c4f538468a337ed219ad8d6b23bd9abdabd123bd5","Cargo.lock":"7f984c7231c91f2def8f3e2e923a85c2e0b3239492f5ce23400881ea4de1aa16","Cargo.toml":"8a447efc18cd97d019a9771fb258b06f694499500561564eec75480e46bcc554","Cargo.toml.orig":"6c9e7b86804255debe03545c6358eb975d3d470810a19e6c40c680299a686b1f","src/backends/mod.rs":"65cdc60cdf38968f5a7e197338f4cf6173406ce69a4f0aaa96a9e29f4f581b6e","src/backends/v2020/firmware.rs":"5a41bfb8f42f17523e68f8702e87d75bcdb268bd4950bb66227f6966ef3576a9","src/backends/v2020/mod.rs":"4018fbe6d907231746b1eb44c8027688b64e9cdb4ba722e0d54c2467786b9afd","src/backends/v2020/rpc.rs":"b517f88b9125fe1d8a20d5167f5d0d105b1339fce3d1a9fad5592e00470f46fb","src/backends/v2020/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/backends/v2023_07/firmware.rs":"c07668e351d48dab3e24511b1aa9ab5e408bbcb5a438fdb0542a1377f94b9bbb","src/backends/v2023_07/mod.rs":"278e4dd04a753858e12df96ead3522aef0616ebf6f27b3da4f1a12b064c19ee6","src/backends/v2023_07/rpc.rs":"2b24bbb432b302dd15f7a354054fc96c6a75cac2c8e75b8bcc11da37255a05a3","src/backends/v2023_07/web.rs":"d39b67ed83781b2c4fa84a445b9ffe785ae3001941f800ad9860e050c61c6506","src/firmware.rs":"e75c21d63218204b61bfab067599402e5c0b20452beaf0b16bfa79bf8afb6b35","src/lib.rs":"53f7acddeff8f7d82f80d09e0a9f91962011f9ccf2e441c4ca05cd7fc4eb292e","src/test/json/mod.rs":"a3ef4d6805bb4f8ea087e3a9b875e5a1664580e1ff3e3cd2015bb0c5c18ae7bb","src/test/json/v2020/devs.json":"df17cdfc9522e23450702b93f70ff701892db54c6ce6d986300453ad5e0d22db","src/test/json/v2020/mod.rs":"4c2512d36af834d400a865a94c2e8b1919f9d8dcbf54ab2530c73861c51af67d","src/test/json/v2020/pools.json":"4c4d19ad3ef0de84bfb18daaa48428b5f7917d23287c0196eacf3a6e389e7634","src/test/json/v2020/stats.json":"6d3cb463abb7539ae77aa44ef38e62a5dc0db54670aeacf3bbd01e83f49aa1fd","src/test/json/v2020/summary.json":"2f18c81f989b7c5f70dcb0ddac0520e56ec98b6da25c24e59354a6126c965dae","src/test/json/v2020/system_info.json":"51d1ce922e39a254518a24be56ca86ef1b5843582fb26c1ff0ec4ff6f8f91ccf","src/test/json/v2020/version.json":"ae898c4c9ea3462c3e79f9de755f1fccb4ef122b94a4a512e61aa74491c1a8e9","src/test/json/v2023_07/l11_stats.json":"2eab324f253ced9a0ea4e46466691e0e71fc6fde7558fec86bd5acf6bb9c717d","src/test/json/v2023_07/l11_summary.json":"1e0fdb61b968005d0ec5393d9dc889b09efb1398ffa427629bcc0a98d1b67c22","src/test/json/v2023_07/l11_version.json":"d116921a71731c6e492aed109731c39561e34a24c7df2a88d11ac52b80f6100a","src/test/json/v2023_07/l9_stats.json":"731ee545f16dafd356d22703248b91a37f74585ad73cc27441eb3461ce53dca0","src/test/json/v2023_07/l9_summary.json":"b32b5131ad46859b270d2dbb6bdba3c4e5d7301298daee4ce56332c98faaf81d","src/test/json/v2023_07/l9_version.json":"82f03ca6ea8873f12c4d9455f21b98c547801b58fbff1dcd83c837c0f337a129","src/test/json/v2023_07/mod.rs":"1360a8b155b120f2e755ede0736bcc0d76a9d1d693b984a1b51a16e6c0413791","src/test/mod.rs":"ed52c3d613eabc4a0346bb38bcfdf7a94933d61e368d3c9094821edeab92f81b"},"package":"0c06e3ecbf95ae3fe5e30aacae55cf6e7ad3d965f4a93b2f85c7b64f61fc75e2"}
+75 -20
View File
@@ -434,14 +434,29 @@ impl GetDataLocations for AntMinerV2020 {
tag: None,
},
)],
DataField::ControlBoardVersion => vec![(
WEB_MINER_TYPE,
DataExtractor {
func: get_by_pointer,
key: Some("/subtype"),
tag: None,
},
)],
// Prefer the explicit control-board subtype from miner_type.cgi, but
// carry the kernel build string from get_system_info.cgi too: older
// models (e.g. Z15/Z15J) have no miner_type.cgi, and their kernel
// string ("...-xilinx-...") names the control board we can actually
// read instead of guessing from the model (round 12 #10).
DataField::ControlBoardVersion => vec![
(
WEB_MINER_TYPE,
DataExtractor {
func: get_by_pointer,
key: Some("/subtype"),
tag: Some("subtype"),
},
),
(
WEB_SYSTEM_INFO,
DataExtractor {
func: get_by_pointer,
key: Some("/system_kernel_version"),
tag: Some("kernel"),
},
),
],
// cgminer names its summary keys after the unit they are in —
// `GHS 5s` on SHA-256 models, `MHS 5s` on Scrypt ones — so keep
// the whole entry and let the parse pick the key that is present.
@@ -748,16 +763,33 @@ impl GetExpectedHashrate for AntMinerV2020 {
let value = field?
.pointer("/hashrate")
.and_then(Self::parse_f64_field)?;
// Equihash miners (Z15/Z15J) report `total_rateideal` as a Sol/s count in
// the same (mislabelled) scale as the realtime "GHS" rate, so reinterpret
// it as the base Hash unit -- matching parse_hashrate. Without this,
// expected reads ~1e6x larger than realtime and the realtime figure looks
// absent next to it (round 12 #10).
let is_equihash = self.device_info.algo == HashAlgorithm::Equihash
|| self
.device_info
.model
.to_string()
.to_ascii_uppercase()
.contains("Z15");
let unit = if is_equihash {
HashRateUnit::Hash
} else {
// `total_rateideal` does not name its own scale, so take it from
// STATS' `rate_unit` (`"GH"` / `"MH"`).
field
.and_then(|v| v.pointer("/unit"))
.and_then(|v| v.as_str())
.and_then(|s| HashRateUnit::from_str(s).ok())
.unwrap_or(HashRateUnit::GigaHash)
};
Some(
HashRate {
value,
// `total_rateideal` does not name its own scale, so take it
// from STATS' `rate_unit` (`"GH"` / `"MH"`).
unit: field
.and_then(|v| v.pointer("/unit"))
.and_then(|v| v.as_str())
.and_then(|s| HashRateUnit::from_str(s).ok())
.unwrap_or(HashRateUnit::GigaHash),
unit,
algo: self.device_info.algo,
}
.as_unit(HashRateUnit::default()),
@@ -888,11 +920,34 @@ impl GetControlBoardVersion for AntMinerV2020 {
&self,
data: &HashMap<DataField, Value>,
) -> Option<MinerControlBoard> {
let cb_type = data.extract::<String>(DataField::ControlBoardVersion)?;
match cb_type.as_str() {
s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
_ => AntMinerControlBoard::parse(cb_type.split("_").collect::<Vec<&str>>()[0])
.map(|cb| cb.into()),
let field = data.get(&DataField::ControlBoardVersion)?;
// Explicit control-board subtype (miner_type.cgi) wins when present.
let subtype = field
.pointer("/subtype")
.and_then(|v| v.as_str())
.unwrap_or("");
if !subtype.is_empty() {
return match subtype {
s if s.to_uppercase().contains("AML") => Some(AntMinerControlBoard::AMLogic.into()),
_ => AntMinerControlBoard::parse(subtype.split('_').next().unwrap_or(subtype))
.map(|cb| cb.into()),
};
}
// No subtype (older models): read the control board from the kernel build
// string instead of guessing from the model (round 12 #10). Bitmain names
// the SoC in the kernel version, e.g. "Linux 4.6.0-xilinx-..." (Z15) or an
// AMLogic/Meson kernel on newer AMLogic boards.
let kernel = field
.pointer("/kernel")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_ascii_lowercase();
if kernel.contains("xilinx") || kernel.contains("zynq") {
Some(AntMinerControlBoard::Xilinx.into())
} else if kernel.contains("aml") || kernel.contains("meson") {
Some(AntMinerControlBoard::AMLogic.into())
} else {
None
}
}
}
+11 -1
View File
@@ -71,7 +71,17 @@ impl AntMinerRPCAPI {
read_stream_response(&mut stream, DEFAULT_RPC_TIMEOUT).await
};
let response = response?;
self.parse_rpc_result(&response)
self.parse_rpc_result(&Self::sanitize_cgminer(&response))
}
/// Antminer's cgminer `stats` sometimes emits an array whose objects are not
/// comma-separated (`...}{"STATS":0,...` on the Z15/Z15J), which is invalid
/// JSON that serde rejects -- dropping the whole stats command and with it
/// every stats-derived field (expected hashrate, wattage, fans, hashboards,
/// uptime). Insert the missing separators. Well-formed JSON never contains an
/// unseparated `}{`, so this is a no-op on valid responses (round 12 #10).
fn sanitize_cgminer(response: &str) -> String {
response.replace("}{", "},{")
}
fn parse_rpc_result(&self, response: &str) -> anyhow::Result<Value> {
+31 -14
View File
@@ -142,18 +142,9 @@ async fn get_model_with_auth(
}
}
/// Fetch the firmware version from a miner using digest auth.
async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
let client = build_discovery_client().ok()?;
let data: Response = client
.get(format!("http://{ip}/cgi-bin/summary.cgi"))
.send_digest_auth((auth.username(), auth.password()))
.await
.ok()?;
let json_data = data.json::<serde_json::Value>().await.ok()?;
let fw_version = json_data["INFO"]["CompileTime"].as_str().unwrap_or("");
/// Parse an Antminer cgminer `CompileTime` string ("Mon Dec 14 18:01:42 CST
/// 2020") into a date-based semver (year.month.day) used to pick the backend.
fn parse_antminer_compile_time(fw_version: &str) -> Option<semver::Version> {
let cleaned: String = {
let mut parts: Vec<&str> = fw_version.split_whitespace().collect();
if parts.len() > 4 {
@@ -161,9 +152,7 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
}
parts.join(" ")
};
let dt = NaiveDateTime::parse_from_str(&cleaned, "%a %b %e %H:%M:%S %Y").ok()?;
Some(semver::Version::new(
dt.year() as u64,
dt.month() as u64,
@@ -171,6 +160,34 @@ async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::V
))
}
/// Fetch the firmware version (as a date-based semver) to pick the backend.
async fn get_version_with_auth(ip: IpAddr, auth: &MinerAuth) -> Option<semver::Version> {
// Newer Antminers expose the firmware CompileTime via summary.cgi.
if let Ok(client) = build_discovery_client()
&& let Ok(data) = client
.get(format!("http://{ip}/cgi-bin/summary.cgi"))
.send_digest_auth((auth.username(), auth.password()))
.await
&& let Ok(json_data) = data.json::<serde_json::Value>().await
&& let Some(v) =
parse_antminer_compile_time(json_data["INFO"]["CompileTime"].as_str().unwrap_or(""))
{
return Some(v);
}
// Older models (e.g. Z15/Z15J) have no summary.cgi, so summary-based version
// detection returns nothing and the miner would default to the newest
// backend and be mis-parsed. Fall back to the cgminer :4028 `version` RPC,
// which still reports the CompileTime, so the right (older) backend is picked
// (round 12 #10).
let rpc = asic_rs_core::util::send_rpc_command(&ip, "version").await?;
parse_antminer_compile_time(
rpc.pointer("/VERSION/0/CompileTime")
.and_then(|v| v.as_str())
.unwrap_or(""),
)
}
#[async_trait]
impl MinerFirmware for AntMinerStockFirmware {
/// Uses default credentials. For custom credentials, use `build_miner`