clasp_discovery/
device.rs1use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::net::SocketAddr;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct Device {
10 pub id: String,
12 pub name: String,
14 pub info: DeviceInfo,
16 pub endpoints: HashMap<String, String>,
18 #[serde(skip, default = "std::time::Instant::now")]
20 pub discovered_at: std::time::Instant,
21 #[serde(skip, default = "std::time::Instant::now")]
23 pub last_seen: std::time::Instant,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct DeviceInfo {
29 pub version: u8,
31 pub features: Vec<String>,
33 pub bridge: bool,
35 pub bridge_protocol: Option<String>,
37 #[serde(default)]
39 pub meta: HashMap<String, String>,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub entity_id: Option<String>,
43}
44
45impl Device {
46 pub fn new(id: String, name: String) -> Self {
48 let now = std::time::Instant::now();
49 Self {
50 id,
51 name,
52 info: DeviceInfo::default(),
53 endpoints: HashMap::new(),
54 discovered_at: now,
55 last_seen: now,
56 }
57 }
58
59 pub fn with_ws_endpoint(mut self, url: &str) -> Self {
61 self.endpoints.insert("ws".to_string(), url.to_string());
62 self
63 }
64
65 pub fn with_udp_endpoint(mut self, addr: SocketAddr) -> Self {
67 self.endpoints.insert("udp".to_string(), addr.to_string());
68 self
69 }
70
71 pub fn ws_url(&self) -> Option<&str> {
73 self.endpoints.get("ws").map(|s| s.as_str())
74 }
75
76 pub fn udp_addr(&self) -> Option<SocketAddr> {
78 self.endpoints.get("udp").and_then(|s| s.parse().ok())
79 }
80
81 pub fn touch(&mut self) {
83 self.last_seen = std::time::Instant::now();
84 }
85
86 pub fn is_stale(&self, timeout: std::time::Duration) -> bool {
88 self.last_seen.elapsed() > timeout
89 }
90}
91
92impl Default for DeviceInfo {
93 fn default() -> Self {
94 Self {
95 version: clasp_core::PROTOCOL_VERSION,
96 features: vec![
97 "param".to_string(),
98 "event".to_string(),
99 "stream".to_string(),
100 ],
101 bridge: false,
102 bridge_protocol: None,
103 meta: HashMap::new(),
104 entity_id: None,
105 }
106 }
107}
108
109impl DeviceInfo {
110 pub fn with_features(mut self, features: Vec<String>) -> Self {
111 self.features = features;
112 self
113 }
114
115 pub fn as_bridge(mut self, protocol: &str) -> Self {
116 self.bridge = true;
117 self.bridge_protocol = Some(protocol.to_string());
118 self
119 }
120}