use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::SocketAddr;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Device {
pub id: String,
pub name: String,
pub info: DeviceInfo,
pub endpoints: HashMap<String, String>,
#[serde(skip, default = "std::time::Instant::now")]
pub discovered_at: std::time::Instant,
#[serde(skip, default = "std::time::Instant::now")]
pub last_seen: std::time::Instant,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceInfo {
pub version: u8,
pub features: Vec<String>,
pub bridge: bool,
pub bridge_protocol: Option<String>,
#[serde(default)]
pub meta: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub entity_id: Option<String>,
}
impl Device {
pub fn new(id: String, name: String) -> Self {
let now = std::time::Instant::now();
Self {
id,
name,
info: DeviceInfo::default(),
endpoints: HashMap::new(),
discovered_at: now,
last_seen: now,
}
}
pub fn with_ws_endpoint(mut self, url: &str) -> Self {
self.endpoints.insert("ws".to_string(), url.to_string());
self
}
pub fn with_udp_endpoint(mut self, addr: SocketAddr) -> Self {
self.endpoints.insert("udp".to_string(), addr.to_string());
self
}
pub fn ws_url(&self) -> Option<&str> {
self.endpoints.get("ws").map(|s| s.as_str())
}
pub fn udp_addr(&self) -> Option<SocketAddr> {
self.endpoints.get("udp").and_then(|s| s.parse().ok())
}
pub fn touch(&mut self) {
self.last_seen = std::time::Instant::now();
}
pub fn is_stale(&self, timeout: std::time::Duration) -> bool {
self.last_seen.elapsed() > timeout
}
}
impl Default for DeviceInfo {
fn default() -> Self {
Self {
version: clasp_core::PROTOCOL_VERSION,
features: vec![
"param".to_string(),
"event".to_string(),
"stream".to_string(),
],
bridge: false,
bridge_protocol: None,
meta: HashMap::new(),
entity_id: None,
}
}
}
impl DeviceInfo {
pub fn with_features(mut self, features: Vec<String>) -> Self {
self.features = features;
self
}
pub fn as_bridge(mut self, protocol: &str) -> Self {
self.bridge = true;
self.bridge_protocol = Some(protocol.to_string());
self
}
}