diff --git a/src/detect.rs b/src/detect.rs index 6defe17..25fc795 100644 --- a/src/detect.rs +++ b/src/detect.rs @@ -19,6 +19,20 @@ pub enum ChipModel { Unknown, } +impl ChipModel { + /// Stable wire/API name for this chip family. + pub fn name(self) -> &'static str { + match self { + Self::Bm1362 => "bm1362", + Self::Bm1366 => "bm1366", + Self::Bm1368 => "bm1368", + Self::Bm1370 => "bm1370", + Self::Bm1398 => "bm1398", + Self::Unknown => "unknown", + } + } +} + /// How a chain reports temperature. PIC boards proxy telemetry through the power MCU. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SensorTopology { diff --git a/src/management.rs b/src/management.rs index a98edd2..9563ea4 100644 --- a/src/management.rs +++ b/src/management.rs @@ -1,23 +1,39 @@ // SPDX-License-Identifier: MIT //! Bounded, read-only cgminer-style status for a local management client. +use crate::detect::{EepromState, HardwarePlan}; use serde_json::{json, Value}; use std::io::{self, Read, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Arc; +use std::sync::Mutex; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; const MAX_REQUEST_BYTES: usize = 2048; const CLIENT_TIMEOUT: Duration = Duration::from_millis(500); const REQUEST_DEADLINE: Duration = Duration::from_secs(2); +/// Everything the extended API exposes beyond share counters. +#[derive(Clone, Debug, PartialEq)] +pub struct HardwareSnapshot { + pub plan: HardwarePlan, + /// Chains the supervisor still allows work on. + pub active_chains: Vec, + /// `None` while hashing; otherwise why the machine stopped. + pub stopped: Option<&'static str>, + pub frequency_mhz: u16, + /// Operator target in the form `power:3000`, `hashrate:200`, `ambient:20000`, `fan:100`. + pub target: String, +} + #[derive(Debug)] pub struct MiningStatus { started: Instant, running: AtomicBool, accepted: AtomicU64, rejected: AtomicU64, + hardware: Mutex>, } impl Default for MiningStatus { @@ -33,9 +49,21 @@ impl MiningStatus { running: AtomicBool::new(false), accepted: AtomicU64::new(0), rejected: AtomicU64::new(0), + hardware: Mutex::new(None), } } + /// Publish the current hardware view for the API. + pub fn set_hardware(&self, snapshot: HardwareSnapshot) { + if let Ok(mut slot) = self.hardware.lock() { + *slot = Some(snapshot); + } + } + + fn hardware(&self) -> Option { + self.hardware.lock().ok().and_then(|slot| slot.clone()) + } + pub fn set_running(&self, running: bool) { self.running.store(running, Ordering::Relaxed); } @@ -72,6 +100,16 @@ impl MiningStatus { "API": "1.0" }]}), ), + "hardware" => ( + "S", + "Hardware", + json!({"HARDWARE": [hardware_json(self.hardware())]}), + ), + "stats" => ( + "S", + "Stats", + json!({"STATS": [stats_json(self.hardware())]}), + ), _ => ("E", "Unknown command", json!({})), }; let mut response = json!({"STATUS": [{ @@ -89,6 +127,69 @@ impl MiningStatus { } } +fn eeprom_json(state: &EepromState) -> Value { + match state { + EepromState::Present { model } => json!({"state": "present", "model": model}), + EepromState::Absent => json!({"state": "absent"}), + EepromState::Invalid => json!({"state": "invalid"}), + } +} + +fn hardware_json(snapshot: Option) -> Value { + let Some(snapshot) = snapshot else { + return json!({"available": false}); + }; + let plan = &snapshot.plan; + json!({ + "available": true, + "profile": plan.profile, + "chip": plan.chip.name(), + "psu": plan.psu, + "envelope": { + "v_min_mv": plan.envelope.v_min_mv, + "v_max_mv": plan.envelope.v_max_mv, + "f_min_mhz": plan.envelope.f_min_mhz, + "f_max_mhz": plan.envelope.f_max_mhz, + }, + "operating_point": { + "voltage_mv": plan.operating_point.voltage_mv, + "frequency_mhz": plan.operating_point.frequency_mhz, + "confirmed": plan.operating_point.confirmed, + }, + "chains": plan.chains.iter().map(|chain| json!({ + "index": chain.index, + "chip": chain.chip.name(), + "chips_found": chain.chips_found, + "eeprom": eeprom_json(&chain.eeprom), + "response_per_mille": chain.response_per_mille, + })).collect::>(), + "fan_zones": plan.fan_zones.iter().map(|zone| json!({ + "fan": zone.fan, + "zones": zone.zones, + })).collect::>(), + "active_chains": snapshot.active_chains, + "stopped": snapshot.stopped, + "target": snapshot.target, + "frequency_mhz": snapshot.frequency_mhz, + }) +} + +fn stats_json(snapshot: Option) -> Value { + let Some(snapshot) = snapshot else { + return json!({"available": false}); + }; + json!({ + "Profile": snapshot.plan.profile, + "Chip": snapshot.plan.chip.name(), + "PSU": snapshot.plan.psu, + "FrequencyMHz": snapshot.frequency_mhz, + "VoltageMV": snapshot.plan.operating_point.voltage_mv, + "Target": snapshot.target, + "ActiveChains": snapshot.active_chains.len(), + "Stopped": snapshot.stopped, + }) +} + fn request_command(bytes: &[u8]) -> Option<&str> { let request = std::str::from_utf8(bytes).ok()?.trim(); if request.starts_with('{') { @@ -97,12 +198,16 @@ fn request_command(bytes: &[u8]) -> Option<&str> { match command { "summary" => Some("summary"), "version" => Some("version"), + "hardware" => Some("hardware"), + "stats" => Some("stats"), _ => Some("unknown"), } } else { match request { "summary" => Some("summary"), "version" => Some("version"), + "hardware" => Some("hardware"), + "stats" => Some("stats"), _ => Some("unknown"), } } @@ -246,4 +351,85 @@ mod tests { assert!(parsed.get("SUMMARY").is_some()); worker.join().unwrap(); } + + fn snapshot() -> HardwareSnapshot { + HardwareSnapshot { + plan: HardwarePlan { + profile: "s19jpro-bm1362-pic".into(), + chip: crate::detect::ChipModel::Bm1362, + chains: vec![crate::detect::ChainReport { + index: 0, + chip: crate::detect::ChipModel::Bm1362, + chips_found: 126, + eeprom: EepromState::Absent, + response_per_mille: Some(950), + }], + envelope: crate::detect::Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }, + operating_point: crate::detect::OperatingPoint { + voltage_mv: 1200, + frequency_mhz: 500, + confirmed: false, + }, + psu: "APW12".into(), + fan_zones: vec![crate::detect::FanZone { + fan: 0, + zones: vec![0, 1], + }], + }, + active_chains: vec![0], + stopped: None, + frequency_mhz: 512, + target: "power:3000".into(), + } + } + + #[test] + fn hardware_is_unavailable_until_published() { + let status = MiningStatus::new(); + let reply = status.response("hardware"); + assert_eq!(reply["HARDWARE"][0]["available"], false); + } + + #[test] + fn hardware_command_exposes_detection_and_fault_state() { + let status = MiningStatus::new(); + status.set_hardware(snapshot()); + let reply = status.response("hardware"); + let hardware = &reply["HARDWARE"][0]; + assert_eq!(hardware["available"], true); + assert_eq!(hardware["profile"], "s19jpro-bm1362-pic"); + assert_eq!(hardware["chip"], "bm1362"); + assert_eq!(hardware["psu"], "APW12"); + assert_eq!(hardware["chains"][0]["chips_found"], 126); + assert_eq!(hardware["chains"][0]["eeprom"]["state"], "absent"); + assert_eq!(hardware["operating_point"]["confirmed"], false); + assert_eq!(hardware["active_chains"][0], 0); + assert_eq!(hardware["target"], "power:3000"); + assert_eq!(hardware["fan_zones"][0]["zones"][1], 1); + } + + #[test] + fn stats_command_keeps_cgminer_shape() { + let status = MiningStatus::new(); + status.set_hardware(snapshot()); + let reply = status.response("stats"); + let stats = &reply["STATS"][0]; + assert_eq!(stats["Profile"], "s19jpro-bm1362-pic"); + assert_eq!(stats["FrequencyMHz"], 512); + assert_eq!(stats["VoltageMV"], 1200); + assert_eq!(stats["ActiveChains"], 1); + assert!(stats["Stopped"].is_null()); + } + + #[test] + fn unknown_commands_still_refuse() { + let status = MiningStatus::new(); + let reply = status.response("reboot"); + assert_eq!(reply["STATUS"][0]["STATUS"], "E"); + } }