diff --git a/src/hal_wire.rs b/src/hal_wire.rs index 1f90d3d..58755de 100644 --- a/src/hal_wire.rs +++ b/src/hal_wire.rs @@ -31,11 +31,13 @@ const CAPABILITIES: u8 = 7; const PROBE_CHAIN: u8 = 8; const READ_EEPROM: u8 = 9; const IDENTIFY_PSU: u8 = 10; +const SET_CHAIN_FREQUENCY: u8 = 11; /// Backend feature bits reported by `CAPABILITIES`. pub const CAP_CHAIN_PROBE: u32 = 1 << 0; pub const CAP_EEPROM: u32 = 1 << 1; pub const CAP_PSU_IDENTITY: u32 = 1 << 2; +pub const CAP_FREQUENCY: u32 = 1 << 3; const PROBE_IDENTIFIED: u8 = 0; const PROBE_SILENT: u8 = 1; @@ -420,6 +422,15 @@ impl HalClient { } } + /// Apply a chain frequency in MHz. The backend owns the PLL write; the OS owns the decision. + pub fn set_chain_frequency(&mut self, chain: u8, mhz: u16) -> Result<(), HalError> { + self.require(CAP_FREQUENCY)?; + let mut payload = [0_u8; 3]; + payload[0] = chain; + payload[1..].copy_from_slice(&mhz.to_le_bytes()); + self.empty_reply(SET_CHAIN_FREQUENCY, &payload) + } + pub fn identify_psu(&mut self) -> Result { self.require(CAP_PSU_IDENTITY)?; let body = self.exchange(IDENTIFY_PSU, &[])?; @@ -577,7 +588,8 @@ mod tests { CAPABILITIES => { let mut body = vec![0_u8]; body.extend_from_slice( - &(CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY).to_le_bytes(), + &(CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY) + .to_le_bytes(), ); body } @@ -597,7 +609,7 @@ mod tests { } body } - SET_FAN_TARGET => vec![0], + SET_FAN_TARGET | SET_CHAIN_FREQUENCY => vec![0], READ_TEMPERATURE => { let mut body = vec![0_u8]; body.extend_from_slice(&42_000_i32.to_le_bytes()); @@ -626,7 +638,7 @@ mod tests { assert_eq!( client.capabilities().expect("capabilities"), - CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY + CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY | CAP_FREQUENCY ); match client.probe_chain(0, 0).expect("probe") { ProbeOutcome::Identified { chip, chips } => { @@ -647,6 +659,7 @@ mod tests { assert_eq!(psu.envelope.v_max_mv, 1600); assert_eq!(psu.max_dc_watts, 3600); + client.set_chain_frequency(2, 512).expect("set frequency"); client.set_fan(1, 60).expect("set fan"); assert_eq!(client.read_zone(2).expect("read zone"), 42_000); diff --git a/src/main.rs b/src/main.rs index 25ef8f7..e28e555 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,10 +7,11 @@ use alkane_os::detect::{ use alkane_os::hal_wire::HalClient; use alkane_os::management::MiningStatus; use alkane_os::miner::{Bm1366Miner, ChipModel}; -use alkane_os::runtime::Tick; +use alkane_os::runtime::{Tick, TickOutcome}; use alkane_os::stratum_client::{PoolConnection, PoolEvent}; use alkane_os::target_matrix; use alkane_os::tuning::{PidConfig, TuningTarget}; +use alkane_os::HardwareBackend; use std::error::Error; use std::io; use std::net::SocketAddr; @@ -172,6 +173,112 @@ fn self_check() -> Result<(), Box> { Ok(()) } +fn parse_target(text: &str) -> Result> { + let (kind, value) = text + .split_once(':') + .ok_or("target must look like power:2400")?; + let value: f32 = value.parse()?; + Ok(match kind { + "power" => TuningTarget::PowerW(value), + "hashrate" => TuningTarget::HashrateThs(value), + "ambient" => TuningTarget::AmbientC { + margin_mc: value as i32, + }, + "fan" => TuningTarget::MaxFan { + max_pwm: value as u8, + }, + _ => return Err("target must be power, hashrate, ambient or fan".into()), + }) +} + +/// Boot a real board through the HAL socket, then run a bounded tuning loop. +fn boot_hal(mut args: impl Iterator) -> Result<(), Box> { + let socket = args.next().ok_or("missing HAL socket")?; + let profiles = args.next().ok_or("missing profile database path")?; + let target = parse_target(&args.next().ok_or("missing target")?)?; + let sensor = match args.next().as_deref() { + Some("nopic") => SensorTopology::NoPic, + Some("pic") | None => SensorTopology::Pic, + Some(_) => return Err("sensor must be pic or nopic".into()), + }; + let ticks: usize = args + .next() + .map(|value| value.parse()) + .transpose()? + .unwrap_or(30); + let profile_db_json = std::fs::read_to_string(&profiles)?; + let status = Arc::new(MiningStatus::new()); + let api = std::env::var("ALKANE_API_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let web = std::env::var("ALKANE_WEB_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let servers = app::start(Arc::clone(&status), api, web)?; + + let config = app::BootConfig { + profile_db_json, + chain_ports: vec![0, 1, 2], + sensor, + budget: ProbeBudget::default(), + fan_zones: Vec::new(), + target, + pid: PidConfig::default(), + ceiling_mc: 95_000, + fault_policy: Default::default(), + }; + let map_path = std::path::PathBuf::from( + std::env::var("ALKANE_FANMAP").unwrap_or_else(|_| "/var/lib/alkane/fanmap.json".into()), + ); + let settings = app::HalBoot { + config: &config, + sweep: Default::default(), + thresholds: Default::default(), + map_path: &map_path, + }; + let (mut runtime, _map) = + app::boot_from_hal(std::path::Path::new(&socket), &settings, &status)?; + println!( + "detected {} with {} active chains", + runtime.plan().profile, + runtime.active_chains().len() + ); + + let mut client = HalClient::connect(std::path::Path::new(&socket))?; + for _ in 0..ticks { + let hottest = client.read_temperature_mc(0).ok(); + let outcome = runtime.tick(&Tick { + power_w: None, + hashrate_ths: None, + hottest_mc: hottest, + ambient_mc: None, + dt_s: 5.0, + }); + if let TickOutcome::Run(command) = outcome { + for chain in runtime.active_chains() { + client.set_chain_frequency(chain, command.frequency_mhz)?; + } + if let Some(pwm) = command.fan_pwm { + client.set_fan_target(0, pwm)?; + } + } + if let Some(reason) = runtime.stop_reason() { + println!("stopped: {reason:?}"); + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target))); + println!( + "{}", + serde_json::to_string_pretty(&status.hardware_document())? + ); + let _ = servers; + Ok(()) +} + fn main() { let mut args = std::env::args().skip(1); match args.next().as_deref() { @@ -185,6 +292,12 @@ fn main() { } } Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")), + Some("--boot") => { + if let Err(error) = boot_hal(args) { + eprintln!("boot failed: {error}"); + std::process::exit(1); + } + } Some("--self-check") => { if let Err(error) = self_check() { eprintln!("self-check failed: {error}"); @@ -198,7 +311,7 @@ fn main() { } } _ => { - eprintln!("usage: alkane-os --list-targets | --version | --self-check | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]"); + eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]"); eprintln!( "env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..." );