main
John Lauer software/: Pico firmware (500 ksps two-channel ADC over DMA, SYNC on GPIO15, framed delta-packed USB stream), smi-dash… e09b832
// SPDX-License-Identifier: MIT
//! Settings, instance registry, snapshots and serial port discovery.

use crate::dsp::DetectParams;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::path::{Path, PathBuf};

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
    /// Idle hours before the server saves its state and exits.
    pub ttl_hours: f64,
    pub keep_alive: bool,
    /// Where `smi-dash show` opens the page: wv (Hydrogen webview) or pup.
    pub surface: String,
    /// Display frames per second pushed to the page.
    pub fps: f64,
    pub record_dir: String,
    pub record_format: String,
    /// Displacement units: auto switches from nm to um above 10 um.
    pub units: String,
    pub detect: DetectParams,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            ttl_hours: 24.0,
            keep_alive: false,
            surface: "wv".into(),
            fps: 30.0,
            record_dir: "~/smi-recordings".into(),
            record_format: "csv".into(),
            units: "auto".into(),
            detect: DetectParams::default(),
        }
    }
}

pub fn home() -> PathBuf {
    std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))
}

pub fn expand(p: &str) -> PathBuf {
    if let Some(rest) = p.strip_prefix("~/") {
        home().join(rest)
    } else {
        PathBuf::from(p)
    }
}

pub fn base_dir() -> PathBuf {
    home().join(".adom").join("instances").join("smi-dash")
}

pub fn settings_path() -> PathBuf {
    base_dir().join("settings.json")
}

pub fn slug(thread: &str) -> String {
    let s: String = thread.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
    let s = s.trim_matches('-').to_string();
    if s.is_empty() { "default".into() } else { s }
}

pub fn snapshot_path(thread: &str) -> PathBuf {
    base_dir().join("snapshots").join(format!("{}.json", slug(thread)))
}

pub fn registry_path(thread: &str) -> PathBuf {
    base_dir().join("registry").join(format!("{}.json", slug(thread)))
}

pub fn write_json<T: Serialize>(p: &Path, v: &T) -> std::io::Result<()> {
    if let Some(d) = p.parent() {
        std::fs::create_dir_all(d)?;
    }
    let tmp = p.with_extension("tmp");
    std::fs::write(&tmp, serde_json::to_vec_pretty(v)?)?;
    std::fs::rename(tmp, p)
}

pub fn read_json(p: &Path) -> Option<Value> {
    serde_json::from_slice(&std::fs::read(p).ok()?).ok()
}

pub fn load_settings() -> Settings {
    read_json(&settings_path()).and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default()
}

pub fn register(thread: &str, port: u16) {
    let v = json!({
        "pid": std::process::id(), "port": port, "thread": thread,
        "version": env!("CARGO_PKG_VERSION"), "startedAt": chrono::Local::now().to_rfc3339(),
    });
    let _ = write_json(&registry_path(thread), &v);
}

pub fn deregister(thread: &str) {
    let _ = std::fs::remove_file(registry_path(thread));
}

/// Live registry entries (dead ones are pruned by checking /health).
pub fn instances() -> Vec<Value> {
    let mut out = vec![];
    let Ok(rd) = std::fs::read_dir(base_dir().join("registry")) else { return out };
    for e in rd.flatten() {
        let p = e.path();
        if p.extension().and_then(|x| x.to_str()) != Some("json") {
            continue;
        }
        let Some(v) = read_json(&p) else { continue };
        let port = v["port"].as_u64().unwrap_or(0);
        // Prune only when nothing listens on the port any more. A slow reply
        // (a busy machine) is not death.
        let alive = match ureq::get(&format!("http://127.0.0.1:{port}/health")).timeout(std::time::Duration::from_millis(3000)).call() {
            Ok(_) | Err(ureq::Error::Status(..)) => true,
            Err(ureq::Error::Transport(t)) => t.kind() != ureq::ErrorKind::ConnectionFailed,
        };
        if alive {
            out.push(v);
        } else {
            let _ = std::fs::remove_file(&p);
        }
    }
    out
}

pub fn list_ports() -> Vec<Value> {
    let mut out = vec![];
    if let Ok(ports) = serialport::available_ports() {
        for p in ports {
            let (vid, pid, product, serial) = match &p.port_type {
                serialport::SerialPortType::UsbPort(u) => (Some(u.vid), Some(u.pid), u.product.clone(), u.serial_number.clone()),
                _ => (None, None, None, None),
            };
            out.push(json!({
                "port": p.port_name, "vid": vid.map(|v| format!("{v:04x}")), "pid": pid.map(|v| format!("{v:04x}")),
                "product": product, "serial": serial,
                "is_pico": vid == Some(0x2E8A),
            }));
        }
    }
    out
}

pub fn guess_pico_port() -> Option<String> {
    list_ports().into_iter().find(|p| p["is_pico"].as_bool() == Some(true)).and_then(|p| p["port"].as_str().map(String::from))
}