use std::collections::HashMap;
use std::io::ErrorKind;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use serde_json::json;
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::time::{Instant, timeout_at};
use crate::bulb::{Bulb, PORT};
use crate::error::Result;
use crate::protocol::{Request, Response};
use crate::transport::RetryPolicy;
pub const BROADCAST: SocketAddr =
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)), PORT);
pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(1);
pub const DEFAULT_WAIT: Duration = Duration::from_secs(5);
const UNKNOWN_PHONE_IP: &str = "1.2.3.4";
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Discovered {
pub addr: SocketAddr,
pub mac: String,
pub system_config: Option<Response>,
}
impl Discovered {
pub fn ip(&self) -> IpAddr {
self.addr.ip()
}
pub async fn connect(&self) -> Result<Bulb> {
Bulb::connect_to(self.addr).await
}
}
#[derive(Clone, Debug)]
pub struct Discovery {
targets: Vec<SocketAddr>,
interval: Duration,
system_config: bool,
policy: RetryPolicy,
}
impl Default for Discovery {
fn default() -> Self {
Self::new()
}
}
impl Discovery {
pub fn new() -> Self {
Self {
targets: Vec::new(),
interval: DEFAULT_INTERVAL,
system_config: false,
policy: RetryPolicy::default(),
}
}
#[must_use]
pub fn target(mut self, addr: SocketAddr) -> Self {
self.targets.push(addr);
self
}
#[must_use]
pub fn interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
#[must_use]
pub fn system_config(mut self, yes: bool) -> Self {
self.system_config = yes;
self
}
#[must_use]
pub fn policy(mut self, policy: RetryPolicy) -> Self {
self.policy = policy;
self
}
pub async fn stream(&self) -> Result<DiscoveryStream> {
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?;
socket.set_broadcast(true)?;
let targets = self.targets();
let payload = registration(local_ip_towards(targets[0]))?;
for target in &targets {
socket.send_to(&payload, target).await?;
}
let (tx, rx) = mpsc::channel(64);
let run = Run {
socket,
targets,
payload,
interval: self.interval,
system_config: self.system_config,
policy: self.policy.clone(),
tx,
};
Ok(DiscoveryStream {
rx,
task: tokio::spawn(run.drive()),
})
}
pub async fn collect(&self, wait: Duration) -> Result<Vec<Discovered>> {
let mut stream = self.stream().await?;
let mut found: Vec<Discovered> = Vec::new();
let deadline = Instant::now() + wait;
while let Ok(Some(bulb)) = tokio::time::timeout_at(deadline, stream.recv()).await {
match found.iter_mut().find(|seen| seen.mac == bulb.mac) {
Some(seen) => *seen = bulb,
None => found.push(bulb),
}
}
Ok(found)
}
fn targets(&self) -> Vec<SocketAddr> {
match self.targets.is_empty() {
true => vec![BROADCAST],
false => self.targets.clone(),
}
}
}
#[derive(Debug)]
pub struct DiscoveryStream {
rx: mpsc::Receiver<Discovered>,
task: JoinHandle<()>,
}
impl DiscoveryStream {
pub async fn recv(&mut self) -> Option<Discovered> {
self.rx.recv().await
}
}
impl Drop for DiscoveryStream {
fn drop(&mut self) {
self.task.abort();
}
}
impl futures_core::Stream for DiscoveryStream {
type Item = Discovered;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.rx.poll_recv(cx)
}
}
struct Run {
socket: UdpSocket,
targets: Vec<SocketAddr>,
payload: Vec<u8>,
interval: Duration,
system_config: bool,
policy: RetryPolicy,
tx: mpsc::Sender<Discovered>,
}
impl Run {
async fn drive(self) {
let mut seen: HashMap<String, SocketAddr> = HashMap::new();
let mut buf = vec![0u8; 4096];
let mut next_broadcast = Instant::now() + self.interval;
loop {
let received = match timeout_at(next_broadcast, self.socket.recv_from(&mut buf)).await {
Ok(received) => received,
Err(_elapsed) => {
self.broadcast().await;
next_broadcast = Instant::now() + self.interval;
continue;
}
};
let (n, from) = match received {
Ok(datagram) => datagram,
Err(e) if e.kind() == ErrorKind::ConnectionReset => continue,
Err(_) => return,
};
let Some(mac) = mac_of(&buf[..n]) else {
continue;
};
if seen.insert(mac.clone(), from) == Some(from) {
continue;
}
if !self.report(mac, from).await {
return;
}
}
}
async fn broadcast(&self) {
for target in &self.targets {
let _ = self.socket.send_to(&self.payload, target).await;
}
}
async fn report(&self, mac: String, addr: SocketAddr) -> bool {
let bulb = Discovered {
addr,
mac,
system_config: None,
};
if !self.system_config {
return self.tx.send(bulb).await.is_ok();
}
let tx = self.tx.clone();
let policy = self.policy.clone();
tokio::spawn(async move {
let _ = tx.send(with_system_config(bulb, policy).await).await;
});
true
}
}
async fn with_system_config(mut bulb: Discovered, policy: RetryPolicy) -> Discovered {
let request = Request::new("getSystemConfig");
if let Ok(handle) = Bulb::connect_to(bulb.addr).await {
bulb.system_config = handle.with_policy(policy).request(&request).await.ok();
}
bulb
}
fn mac_of(datagram: &[u8]) -> Option<String> {
let response: Response = serde_json::from_slice(datagram).ok()?;
let result = response.result?;
let mac = result.get("mac")?.as_str()?;
Some(mac.to_ascii_lowercase())
}
fn registration(phone_ip: Option<IpAddr>) -> Result<Vec<u8>> {
let phone_ip = phone_ip.map_or_else(|| UNKNOWN_PHONE_IP.to_owned(), |ip| ip.to_string());
let request = Request::with_params(
"registration",
&json!({
"phoneMac": "AAAAAAAAAAAA",
"register": false,
"phoneIp": phone_ip,
"id": "1",
}),
)?;
Ok(serde_json::to_vec(&request)?)
}
pub(crate) fn local_ip_towards(target: SocketAddr) -> Option<IpAddr> {
let bind_addr = match target {
SocketAddr::V4(_) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
SocketAddr::V6(_) => SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0),
};
let socket = std::net::UdpSocket::bind(bind_addr).ok()?;
if target.is_ipv4() {
socket.set_broadcast(true).ok()?;
}
socket.connect(target).ok()?;
match socket.local_addr().ok()?.ip() {
IpAddr::V4(ip) if ip.is_unspecified() => None,
IpAddr::V6(ip) if ip.is_unspecified() => None,
ip => Some(ip),
}
}