use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::connect::proto::Role;
use crate::connect::proto::dnssd::ServiceRecord;
pub const SERVICE_FQDN: &str = "_s2connect._tcp.local.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Discovered {
pub instance: String,
pub host: String,
pub port: u16,
pub addresses: Vec<core::net::IpAddr>,
pub record: ServiceRecord,
}
impl Discovered {
#[must_use]
pub fn pairing_url(&self) -> Option<&str> {
self.record.pairing_url.as_deref()
}
#[must_use]
pub fn longpolling_url(&self) -> Option<&str> {
self.record.longpolling_url.as_deref()
}
#[must_use]
pub fn hosts(&self, role: Role) -> Option<bool> {
if self.record.roles.is_empty() {
None
} else {
Some(self.record.roles.contains(&role))
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("mDNS: {0}")]
Mdns(String),
#[error("the service record is not a usable S2 Connect record")]
Record,
}
impl From<mdns_sd::Error> for Error {
fn from(e: mdns_sd::Error) -> Self {
Error::Mdns(e.to_string())
}
}
#[derive(Clone)]
pub struct Discovery {
daemon: mdns_sd::ServiceDaemon,
}
impl core::fmt::Debug for Discovery {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Discovery { .. }")
}
}
impl Discovery {
pub fn new() -> Result<Self, Error> {
Ok(Self {
daemon: mdns_sd::ServiceDaemon::new()?,
})
}
pub fn advertise(
&self,
instance: &str,
host: &str,
port: u16,
record: &ServiceRecord,
) -> Result<(), Error> {
if record.pairing_url.is_none() && record.longpolling_url.is_none() {
return Err(Error::Record);
}
let properties: std::collections::HashMap<String, String> = record
.txt_pairs()
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
let subtypes = record.subtypes();
let ty = match subtypes.as_slice() {
[] => SERVICE_FQDN.to_string(),
[only] => alloc::format!("{only}._sub.{SERVICE_FQDN}"),
_ => {
crate::trace::event!(
warn,
instance = instance,
"an endpoint hosting both roles is advertised on the plain service \
type: mdns-sd cannot put one instance under two DNS-SD subtypes"
);
SERVICE_FQDN.to_string()
}
};
let info = mdns_sd::ServiceInfo::new(
&ty,
instance,
&alloc::format!("{}.", host.trim_end_matches('.')),
"",
port,
properties,
)?
.enable_addr_auto();
self.daemon.register(info)?;
Ok(())
}
pub fn withdraw(&self, instance: &str) -> Result<(), Error> {
self.daemon
.unregister(&alloc::format!("{instance}.{SERVICE_FQDN}"))?;
Ok(())
}
pub fn browse(&self, role: Option<Role>) -> Result<Browse, Error> {
let ty = match role {
Some(role) => alloc::format!("{}._sub.{SERVICE_FQDN}", role.service_subtype()),
None => SERVICE_FQDN.to_string(),
};
Ok(Browse {
events: self.daemon.browse(&ty)?,
})
}
pub fn shutdown(&self) -> Result<(), Error> {
self.daemon.shutdown()?;
Ok(())
}
#[must_use]
pub fn daemon(&self) -> &mdns_sd::ServiceDaemon {
&self.daemon
}
}
pub struct Browse {
events: mdns_sd::Receiver<mdns_sd::ServiceEvent>,
}
impl core::fmt::Debug for Browse {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Browse { .. }")
}
}
impl Browse {
pub async fn next(&self) -> Option<Discovered> {
loop {
let event = self.events.recv_async().await.ok()?;
if let Some(found) = resolve(event) {
return Some(found);
}
}
}
pub fn try_next(&self) -> Option<Discovered> {
loop {
let event = self.events.try_recv().ok()?;
if let Some(found) = resolve(event) {
return Some(found);
}
}
}
}
fn resolve(event: mdns_sd::ServiceEvent) -> Option<Discovered> {
let mdns_sd::ServiceEvent::ServiceResolved(service) = event else {
return None;
};
let pairs: Vec<(String, String)> = service
.txt_properties
.iter()
.map(|p| (p.key().to_string(), p.val_str().to_string()))
.collect();
let borrowed: Vec<(&str, &str)> = pairs
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let mut record = ServiceRecord::from_txt(borrowed)?;
if let Some(sub) = &service.sub_ty_domain {
if sub.starts_with("_cem.") {
record.roles = alloc::vec![Role::Cem];
} else if sub.starts_with("_rm.") {
record.roles = alloc::vec![Role::Rm];
}
}
Some(Discovered {
instance: service
.fullname
.split_once('.')
.map_or_else(|| service.fullname.clone(), |(name, _)| name.to_string()),
host: service.host.trim_end_matches('.').to_string(),
port: service.port,
addresses: service
.addresses
.iter()
.map(mdns_sd::ScopedIp::to_ip_addr)
.collect(),
record,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn two_subtypes_cannot_share_one_instance_and_that_is_why_we_do_not_try() {
let of = |sub: &str| {
mdns_sd::ServiceInfo::new(
&alloc::format!("{sub}._sub.{SERVICE_FQDN}"),
"EVSE1038",
"EVSE1038.local.",
"127.0.0.1",
443,
None,
)
.expect("a legal service info")
};
let cem = of("_cem");
let rm = of("_rm");
assert_ne!(
cem.get_subtype(),
rm.get_subtype(),
"two different subtypes"
);
assert_eq!(
cem.get_fullname(),
rm.get_fullname(),
"…that collide on the key the daemon stores them under"
);
}
fn record() -> ServiceRecord {
ServiceRecord {
endpoint_name: Some("Acme charger".into()),
endpoint_logo_url: None,
pairing_url: Some("https://EVSE1038.local/".into()),
longpolling_url: None,
roles: alloc::vec![Role::Rm],
}
}
#[test]
fn the_service_type_is_the_one_the_specification_registers() {
use crate::connect::proto::dnssd::{PROTOCOL, SERVICE_TYPE};
assert_eq!(
SERVICE_FQDN,
alloc::format!("{SERVICE_TYPE}.{PROTOCOL}.local.")
);
assert_eq!(Role::Cem.service_subtype(), "_cem");
assert_eq!(Role::Rm.service_subtype(), "_rm");
}
#[test]
fn a_record_with_no_url_is_refused_before_it_reaches_the_network() {
let Ok(discovery) = Discovery::new() else {
return;
};
let useless = ServiceRecord {
roles: alloc::vec![Role::Rm],
..ServiceRecord::default()
};
assert!(matches!(
discovery.advertise("EVSE1038", "EVSE1038.local", 443, &useless),
Err(Error::Record)
));
let _ = discovery.shutdown();
}
#[test]
fn a_discovered_endpoint_reports_what_it_can_and_admits_what_it_cannot() {
let found = Discovered {
instance: "EVSE1038".into(),
host: "EVSE1038.local".into(),
port: 443,
addresses: Vec::new(),
record: record(),
};
assert_eq!(found.pairing_url(), Some("https://EVSE1038.local/"));
assert_eq!(found.longpolling_url(), None);
assert_eq!(found.hosts(Role::Rm), Some(true));
assert_eq!(found.hosts(Role::Cem), Some(false));
let unknown = Discovered {
record: ServiceRecord {
roles: Vec::new(),
..record()
},
..found
};
assert_eq!(unknown.hosts(Role::Rm), None);
}
#[test]
fn the_txt_record_carries_what_a_client_needs() {
let pairs = record().txt_pairs();
assert_eq!(pairs[0], ("txtver", "1".to_string()));
let keys: Vec<&str> = pairs.iter().map(|(k, _)| *k).collect();
assert!(keys.contains(&"pairingUrl"));
assert!(keys.contains(&"e_name"));
}
}