|
| 1 | +//! Web of Things Discovery |
| 2 | +//! |
| 3 | +//! Discover [Web Of Things](https://www.w3.org/WoT/) that advertise themselves in the network. |
| 4 | +//! |
| 5 | +//! ## Supported Introduction Mechanisms |
| 6 | +//! |
| 7 | +//! - [x] [mDNS-SD (HTTP)](https://www.w3.org/TR/wot-discovery/#introduction-dns-sd-sec) |
| 8 | +
|
| 9 | +use futures_core::Stream; |
| 10 | +use futures_util::StreamExt; |
| 11 | +use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo}; |
| 12 | +use tracing::debug; |
| 13 | + |
| 14 | +use wot_td::thing::Thing; |
| 15 | + |
| 16 | +/// The error type for Discovery operation |
| 17 | +#[derive(thiserror::Error, Debug)] |
| 18 | +#[non_exhaustive] |
| 19 | +pub enum Error { |
| 20 | + #[error("mdns cannot be accessed {0}")] |
| 21 | + Mdns(#[from] mdns_sd::Error), |
| 22 | + #[error("reqwest error {0}")] |
| 23 | + Reqwest(#[from] reqwest::Error), |
| 24 | + #[error("Missing address")] |
| 25 | + NoAddress, |
| 26 | +} |
| 27 | + |
| 28 | +/// A specialized [`Result`] type |
| 29 | +pub type Result<T> = std::result::Result<T, Error>; |
| 30 | + |
| 31 | +const WELL_KNOWN: &str = "/.well-known/wot"; |
| 32 | + |
| 33 | +/// Discover [Web Of Things](https://www.w3.org/WoT/) via a supported Introduction Mechanism. |
| 34 | +pub struct Discoverer { |
| 35 | + mdns: ServiceDaemon, |
| 36 | + service_type: String, |
| 37 | +} |
| 38 | + |
| 39 | +async fn get_thing(info: ServiceInfo) -> Result<Thing> { |
| 40 | + let host = info.get_addresses().iter().next().ok_or(Error::NoAddress)?; |
| 41 | + let port = info.get_port(); |
| 42 | + let props = info.get_properties(); |
| 43 | + let path = props.get_property_val_str("td").unwrap_or(WELL_KNOWN); |
| 44 | + let proto = match props.get_property_val_str("tls") { |
| 45 | + Some(x) if x == "1" => "https", |
| 46 | + _ => "http", |
| 47 | + }; |
| 48 | + |
| 49 | + debug!("Got {proto} {host} {port} {path}"); |
| 50 | + |
| 51 | + let r = reqwest::get(format!("{proto}://{host}:{port}{path}")).await?; |
| 52 | + |
| 53 | + let t = r.json().await?; |
| 54 | + |
| 55 | + Ok(t) |
| 56 | +} |
| 57 | + |
| 58 | +impl Discoverer { |
| 59 | + /// Creates a new Discoverer |
| 60 | + pub fn new() -> Result<Self> { |
| 61 | + let mdns = ServiceDaemon::new()?; |
| 62 | + let service_type = "_wot._tcp.local.".to_owned(); |
| 63 | + Ok(Self { mdns, service_type }) |
| 64 | + } |
| 65 | + |
| 66 | + /// Returns an Stream of discovered things |
| 67 | + pub fn stream(&self) -> Result<impl Stream<Item = Result<Thing>>> { |
| 68 | + let receiver = self.mdns.browse(&self.service_type)?; |
| 69 | + |
| 70 | + let s = receiver.into_stream().filter_map(|v| async move { |
| 71 | + if let ServiceEvent::ServiceResolved(info) = v { |
| 72 | + let t = get_thing(info).await; |
| 73 | + Some(t) |
| 74 | + } else { |
| 75 | + None |
| 76 | + } |
| 77 | + }); |
| 78 | + |
| 79 | + Ok(s) |
| 80 | + } |
| 81 | +} |
0 commit comments