use std::fmt;
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;
use std::time::Duration;
use tokio::time::{Instant, timeout_at};
use crate::{Bulb, Discovery, Result, RetryPolicy};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TargetSpec {
raw: String,
kind: Kind,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Kind {
Address(SocketAddr),
Mac(String),
}
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
#[error("`{0}` is neither an IP address nor a MAC")]
pub struct BadTarget(pub String);
impl TargetSpec {
#[must_use]
pub fn raw(&self) -> &str {
&self.raw
}
#[must_use]
pub fn address(&self) -> Option<SocketAddr> {
match &self.kind {
Kind::Address(addr) => Some(*addr),
Kind::Mac(_) => None,
}
}
#[must_use]
pub fn mac(&self) -> Option<&str> {
match &self.kind {
Kind::Mac(mac) => Some(mac),
Kind::Address(_) => None,
}
}
}
impl fmt::Display for TargetSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.raw)
}
}
impl FromStr for TargetSpec {
type Err = BadTarget;
fn from_str(input: &str) -> std::result::Result<Self, Self::Err> {
let kind = if let Ok(addr) = input.parse::<SocketAddr>() {
Kind::Address(addr)
} else if let Ok(ip) = input.parse::<IpAddr>() {
Kind::Address(SocketAddr::new(ip, crate::PORT))
} else {
Kind::Mac(normalise_mac(input).ok_or_else(|| BadTarget(input.to_owned()))?)
};
Ok(Self {
raw: input.to_owned(),
kind,
})
}
}
fn normalise_mac(input: &str) -> Option<String> {
let digits: String = input.chars().filter(|c| !matches!(c, ':' | '-')).collect();
(digits.len() == 12 && digits.chars().all(|c| c.is_ascii_hexdigit()))
.then(|| digits.to_ascii_lowercase())
}
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum NotFound {
#[error("no bulb with MAC {mac} answered in {}s — it may be powered off, or on another subnet", .wait.as_secs_f32())]
Mac {
mac: String,
wait: Duration,
},
#[error("no bulbs answered in {}s, so there was nothing to act on", .wait.as_secs_f32())]
Nothing {
wait: Duration,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Resolved {
pub addr: SocketAddr,
pub mac: Option<String>,
}
impl Resolved {
#[must_use]
pub fn label(&self) -> String {
match &self.mac {
Some(mac) => mac.clone(),
None => self.addr.ip().to_string(),
}
}
pub async fn connect(&self, policy: &RetryPolicy) -> Result<Bulb> {
Ok(Bulb::connect_to(self.addr)
.await?
.with_policy(policy.clone()))
}
}
pub async fn resolve(
spec: &TargetSpec,
discovery: &Discovery,
wait: Duration,
) -> anyhow::Result<Resolved> {
if let Some(addr) = spec.address() {
return Ok(Resolved { addr, mac: None });
}
let mac = spec.mac().expect("a target is an address or a MAC");
let mut stream = discovery.stream().await?;
let deadline = Instant::now() + wait;
while let Ok(Some(bulb)) = timeout_at(deadline, stream.recv()).await {
if bulb.mac == mac {
tracing::debug!(%mac, addr = %bulb.addr, "resolved");
return Ok(Resolved {
addr: bulb.addr,
mac: Some(bulb.mac),
});
}
}
Err(NotFound::Mac {
mac: mac.to_owned(),
wait,
}
.into())
}
pub async fn resolve_all(discovery: &Discovery, wait: Duration) -> anyhow::Result<Vec<Resolved>> {
let found = discovery.collect(wait).await?;
if found.is_empty() {
return Err(NotFound::Nothing { wait }.into());
}
let mut bulbs: Vec<Resolved> = found
.into_iter()
.map(|bulb| Resolved {
addr: bulb.addr,
mac: Some(bulb.mac),
})
.collect();
bulbs.sort_by(|a, b| a.mac.cmp(&b.mac));
Ok(bulbs)
}