use std::time::Duration;
use serde_json::{Value, json};
use super::Outcome;
use crate::{Discovered, Discovery, SystemConfig};
pub async fn run(discovery: &Discovery, wait: Duration) -> anyhow::Result<Outcome> {
let found = discovery.collect(wait).await?;
tracing::info!(bulbs = found.len(), ?wait, "scan finished");
Ok(Outcome::new(payload(&found), listing(&found, wait)))
}
fn payload(found: &[Discovered]) -> Value {
Value::Array(
found
.iter()
.map(|bulb| {
let config = system_config(bulb);
json!({
"mac": bulb.mac,
"ip": bulb.ip().to_string(),
"port": bulb.addr.port(),
"model": config.as_ref().and_then(|c| c.module_name.clone()),
"firmware": config.as_ref().and_then(|c| c.fw_version.clone()),
})
})
.collect(),
)
}
fn listing(found: &[Discovered], wait: Duration) -> String {
if found.is_empty() {
return format!("no bulbs answered in {:.1}s", wait.as_secs_f32());
}
let rows: Vec<[String; 4]> = found
.iter()
.map(|bulb| {
let config = system_config(bulb);
[
bulb.mac.clone(),
bulb.ip().to_string(),
field(config.as_ref().and_then(|c| c.module_name.as_deref())),
field(config.as_ref().and_then(|c| c.fw_version.as_deref())),
]
})
.collect();
let widths: [usize; 4] = std::array::from_fn(|column| {
rows.iter()
.map(|row| row[column].chars().count())
.max()
.unwrap_or_default()
});
rows.iter()
.map(|row| {
let line = row
.iter()
.zip(widths)
.map(|(cell, width)| format!("{cell:<width$}"))
.collect::<Vec<_>>()
.join(" ");
line.trim_end().to_owned()
})
.collect::<Vec<_>>()
.join("\n")
}
fn system_config(bulb: &Discovered) -> Option<SystemConfig> {
bulb.system_config
.as_ref()?
.parse_result::<SystemConfig>()
.ok()
}
fn field(value: Option<&str>) -> String {
value.unwrap_or("-").to_owned()
}