//! 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}; /// A compact UTC timestamp "YYYYMMDD-HHMMSS" for a default export filename /// (round 19 #5). UTC keeps this dependency-free (no chrono) and unambiguous. pub fn timestamp_utc() -> String { let secs = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let sod = secs % 86_400; let (h, mi, s) = (sod / 3600, (sod % 3600) / 60, sod % 60); // Civil date from days since 1970-01-01 (Howard Hinnant's civil_from_days). let z = (secs / 86_400) as i64 + 719_468; let era = if z >= 0 { z } else { z - 146_096 } / 146_097; let doe = z - era * 146_097; // [0, 146096] let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399] let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] let mp = (5 * doy + 2) / 153; // [0, 11] let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31] let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12] let y = yoe + era * 400 + i64::from(m <= 2); format!("{y:04}{m:02}{d:02}-{h:02}{mi:02}{s:02}") } /// Escape one CSV field: neutralise spreadsheet formula injection, then quote it /// when it contains a comma, quote, CR or LF (doubling any embedded quotes). /// /// Miner-supplied fields (hostname, worker, serial, ...) can start with a formula /// trigger; prefixing a single quote makes Excel/Sheets treat the cell as text so /// opening the export can't execute an injected formula (round 18 #12). fn esc(s: &str) -> String { let mut val = s.to_string(); if val.starts_with(['=', '+', '-', '@', '\t', '\r']) { val.insert(0, '\''); } if val.contains([',', '"', '\n', '\r']) { format!("\"{}\"", val.replace('"', "\"\"")) } else { val } } 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("; ")), ] } // Group keys for the four variable-length field families (each expands to // per-index columns). Shown as single checkboxes in the export picker (round 19 #6). pub const GROUP_BOARD_TEMPS: &str = "board temps"; pub const GROUP_FANS: &str = "fan rpms"; pub const GROUP_BOARD_STATUS: &str = "board status"; pub const GROUP_POOLS: &str = "pools"; /// Every selectable export field, in output order: each scalar column header, /// then the four variable-length group keys. pub fn export_field_names() -> Vec { let mut v: Vec = scalar_columns().iter().map(|(h, _)| (*h).to_string()).collect(); v.push(GROUP_BOARD_TEMPS.to_string()); v.push(GROUP_FANS.to_string()); v.push(GROUP_BOARD_STATUS.to_string()); v.push(GROUP_POOLS.to_string()); v } /// Build the CSV for `rows` including only the selected fields (scalar column /// headers and/or the group keys above), in the fixed output order (round 19 #6). /// Empty rows still emit a header line. pub fn rows_to_csv_selected( rows: &[MinerRow], selected: &std::collections::HashSet, ) -> String { let cols: Vec = scalar_columns().into_iter().filter(|(h, _)| selected.contains(*h)).collect(); // A group's columns appear only when it is selected; an unselected group's // width stays 0, so the header/value loops below emit nothing for it. let width = |want: bool, f: &dyn Fn(&MinerRow) -> usize| -> usize { if want { rows.iter().map(f).max().unwrap_or(0) } else { 0 } }; let max_board_temps = width(selected.contains(GROUP_BOARD_TEMPS), &|r| r.board_temps.len()); let max_fans = width(selected.contains(GROUP_FANS), &|r| r.fan_rpms.len()); let max_boards = width(selected.contains(GROUP_BOARD_STATUS), &|r| r.board_status.len()); let max_pools = width(selected.contains(GROUP_POOLS), &|r| r.pools.len()); // 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 all: std::collections::HashSet = export_field_names().into_iter().collect(); let csv = rows_to_csv_selected(&rows, &all); 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"); } }