//! CSV export of the full scan data (round 15 #14). //! //! Unlike the on-screen table (which packs several values into one cell, e.g. //! "95T/96T" or a row of health icons), the export is one value per cell and //! covers every scanned data point, so it is complete and machine-readable. //! Variable-length fields (per-board temps, per-fan RPMs, per-board health, the //! pool list) are expanded into indexed columns out to the widest miner in the //! set, so every row has the same columns. use crate::model::{BoardHealth, MinerRow}; /// Escape one CSV field: quote it when it contains a comma, quote, CR or LF, and /// double any embedded quotes. fn esc(s: &str) -> String { if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } } fn num(v: f64) -> String { if v == 0.0 { String::new() } else if v.fract() == 0.0 { format!("{v:.0}") } else { format!("{v:.3}") } } fn opt_bool(v: Option, yes: &str, no: &str) -> String { match v { Some(true) => yes.to_string(), Some(false) => no.to_string(), None => String::new(), } } fn board_health_str(h: &BoardHealth) -> &'static str { match h { BoardHealth::Ok => "ok", BoardHealth::Fault => "fault", BoardHealth::Missing => "missing", } } /// The fixed scalar columns, in order: (header, extractor). type Col = (&'static str, fn(&MinerRow) -> String); fn scalar_columns() -> Vec { vec![ ("ip", |r| r.ip.clone()), ("model", |r| r.model.clone()), ("brand", |r| r.brand.clone()), ("submodel", |r| r.submodel.clone()), ("mac", |r| r.mac.clone()), ("hostname", |r| r.hostname.clone()), ("serial", |r| r.serial.clone()), ("firmware", |r| r.firmware.clone()), ("fw_version", |r| r.fw_version.clone()), ("api_version", |r| r.api_version.clone()), ("control_board", |r| r.control_board.clone()), ("cpu", |r| r.cpu.clone()), ("board_code", |r| r.board_code.clone()), ("algorithm", |r| r.algorithm.clone()), ("status", |r| r.status().to_string()), ("operating_state", |r| r.operating_state.clone()), ("is_mining", |r| r.is_mining.to_string()), ("slow", |r| r.slow.to_string()), ("paused", |r| r.paused.to_string()), ("pic", |r| opt_bool(r.pic_present, "PIC", "noPIC")), ("write_locked", |r| opt_bool(r.write_locked, "locked", "unlocked")), ("light_flashing", |r| opt_bool(r.light_flashing, "on", "off")), ("hashrate_ths", |r| num(r.hashrate_ths)), ("expected_ths", |r| num(r.expected_ths)), ("efficiency_j_th", |r| num(r.efficiency)), ("power_w", |r| num(r.power_w)), ("tuning_percent", |r| r.tuning_percent.map(|v| v.to_string()).unwrap_or_default()), ("chip_temp_c", |r| num(r.chip_temp_c)), ("fluid_temp_c", |r| num(r.fluid_temp_c)), ("env_temp_c", |r| num(r.env_temp_c)), ("outlet_temp_c", |r| num(r.outlet_temp_c)), ("psu_fan_rpm", |r| num(r.psu_fan_rpm)), ("fan_count", |r| r.fan_count.map(|v| v.to_string()).unwrap_or_default()), ("expected_fans", |r| r.expected_fans.map(|v| v.to_string()).unwrap_or_default()), ("total_chips", |r| r.total_chips.map(|v| v.to_string()).unwrap_or_default()), ("expected_chips", |r| r.expected_chips.map(|v| v.to_string()).unwrap_or_default()), ("hashboards", |r| r.hashboards.map(|v| v.to_string()).unwrap_or_default()), ("expected_hashboards", |r| r.expected_hashboards.map(|v| v.to_string()).unwrap_or_default()), ("uptime_secs", |r| if r.uptime_secs > 0 { r.uptime_secs.to_string() } else { String::new() }), ("best_share", |r| r.best_share.map(num).unwrap_or_default()), ("session_best_share", |r| r.session_best_share.map(num).unwrap_or_default()), ("pool_account", |r| r.worker.split_once('.').map(|(a, _)| a).unwrap_or(&r.worker).to_string()), ("pool_url", |r| r.pool_url.clone()), ("errors", |r| r.errors.join("; ")), ] } /// Build the full CSV for `rows`. Empty rows still emit a header line. pub fn rows_to_csv(rows: &[MinerRow]) -> String { let cols = scalar_columns(); // Widest variable-length fields across the set. let max_board_temps = rows.iter().map(|r| r.board_temps.len()).max().unwrap_or(0); let max_fans = rows.iter().map(|r| r.fan_rpms.len()).max().unwrap_or(0); let max_boards = rows.iter().map(|r| r.board_status.len()).max().unwrap_or(0); let max_pools = rows.iter().map(|r| r.pools.len()).max().unwrap_or(0); // Header. let mut headers: Vec = cols.iter().map(|(h, _)| (*h).to_string()).collect(); for i in 1..=max_board_temps { headers.push(format!("board_temp_{i}_c")); } for i in 1..=max_fans { headers.push(format!("fan_{i}_rpm")); } for i in 1..=max_boards { headers.push(format!("board_{i}_status")); } for i in 1..=max_pools { headers.push(format!("pool_{i}_url")); headers.push(format!("pool_{i}_worker")); } let mut out = String::new(); out.push_str(&headers.iter().map(|h| esc(h)).collect::>().join(",")); out.push('\n'); for r in rows { let mut vals: Vec = cols.iter().map(|(_, f)| f(r)).collect(); for i in 0..max_board_temps { vals.push(r.board_temps.get(i).map(|&t| num(t)).unwrap_or_default()); } for i in 0..max_fans { vals.push(r.fan_rpms.get(i).map(|&t| num(t)).unwrap_or_default()); } for i in 0..max_boards { vals.push(r.board_status.get(i).map(board_health_str).unwrap_or("").to_string()); } for i in 0..max_pools { let (u, w) = r.pools.get(i).cloned().unwrap_or_default(); vals.push(u); vals.push(w); } out.push_str(&vals.iter().map(|v| esc(v)).collect::>().join(",")); out.push('\n'); } out } #[cfg(test)] mod tests { use super::*; #[test] fn csv_has_header_and_one_row_per_miner() { let rows = vec![ MinerRow { ip: "10.0.0.1".into(), model: "S19".into(), hashrate_ths: 95.0, expected_ths: 96.0, board_temps: vec![77.0, 64.0, 74.0], fan_rpms: vec![6000.0, 6100.0], ..Default::default() }, MinerRow { ip: "10.0.0.2".into(), model: "M30S".into(), ..Default::default() }, ]; let csv = rows_to_csv(&rows); let lines: Vec<&str> = csv.lines().collect(); assert_eq!(lines.len(), 3, "header + 2 rows"); assert!(lines[0].starts_with("ip,model,brand,")); // Expanded columns out to the widest miner (3 board temps, 2 fans). assert!(lines[0].contains("board_temp_3_c")); assert!(lines[0].contains("fan_2_rpm")); assert!(lines[1].starts_with("10.0.0.1,S19,")); // One value per cell: hashrate and expected are separate columns. assert!(lines[1].contains(",95,96,") || lines[1].contains("95,96")); } #[test] fn csv_escapes_commas_and_quotes() { assert_eq!(esc("a,b"), "\"a,b\""); assert_eq!(esc("he said \"hi\""), "\"he said \"\"hi\"\"\""); assert_eq!(esc("plain"), "plain"); } }