1use crate::driver::{Config, SerialApi, SerialError};
13use crate::frame::DataFrame;
14use crate::function::FunctionId as F;
15use crate::message::{
16 setup, ControllerId, ControllerVersion, InitData, RfRegion, SerialApiCapabilities,
17};
18use crate::port::Port;
19use crate::NodeId;
20use std::time::Duration;
21
22pub const PROBE_TIMEOUT: Duration = Duration::from_millis(2900);
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Series {
28 S500,
30 S700,
32 S800,
34}
35
36impl Series {
37 pub fn from_chip_type(chip: u8) -> Option<Series> {
39 match chip {
40 0x05 => Some(Series::S500),
41 0x07 => Some(Series::S700),
42 0x08 => Some(Series::S800),
43 _ => None,
44 }
45 }
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct ControllerIdentity {
51 pub firmware: String,
53 pub manufacturer_id: u16,
55 pub product_type: u16,
57 pub product_id: u16,
59 pub capabilities: SerialApiCapabilities,
61 pub library_version: Option<String>,
63 pub api_version: Option<u8>,
65 pub chip: Option<(u8, u8)>,
67 pub series: Option<Series>,
69 pub home_id: Option<u32>,
71 pub node_id: Option<NodeId>,
73 pub primary: Option<bool>,
75 pub sis: Option<bool>,
77 pub node_count: Option<usize>,
79 pub region: Option<RfRegion>,
81}
82
83impl ControllerIdentity {
84 pub fn known_name(&self) -> Option<&'static str> {
86 known_name(self.manufacturer_id, self.product_type, self.product_id)
87 }
88}
89
90pub fn known_name(manufacturer: u16, product_type: u16, product_id: u16) -> Option<&'static str> {
92 Some(match (manufacturer, product_type, product_id) {
93 (0x0000, 0x0004, 0x0004) => {
94 "Silicon Labs 800 series controller (e.g. Zooz ZST39 LR, HomeSeer SmartStick G8)"
95 }
96 (0x0000, 0x0004, 0x0001) | (0x0000, 0x0004, 0x0002) => "Silicon Labs 700 series controller",
97 (0x0086, 0x0001, 0x005a) => "Aeotec Z-Stick Gen5",
98 (0x0086, 0x0001, 0x005d) => "Aeotec Z-Stick 7",
99 (0x0115, 0x0400, 0x0001) => "Z-Wave.Me UZB",
100 _ => return None,
101 })
102}
103
104const STEP: Duration = Duration::from_millis(400);
105
106async fn details(api: &SerialApi, id: &mut ControllerIdentity) {
107 let c = &id.capabilities;
108 if c.supports(F::GET_CONTROLLER_VERSION) {
109 if let Ok(r) = api
110 .request(DataFrame::request(F::GET_CONTROLLER_VERSION, vec![]), STEP)
111 .await
112 {
113 id.library_version = ControllerVersion::parse(&r.payload).ok().map(|v| v.version);
114 }
115 }
116 if c.supports(F::GET_CONTROLLER_ID) {
117 if let Ok(r) = api
118 .request(DataFrame::request(F::GET_CONTROLLER_ID, vec![]), STEP)
119 .await
120 {
121 if let Ok(cid) = ControllerId::parse(&r.payload, 1) {
122 id.home_id = Some(cid.home_id);
123 id.node_id = Some(cid.node_id);
124 }
125 }
126 }
127 if c.supports(F::GET_INIT_DATA) {
128 if let Ok(r) = api
129 .request(DataFrame::request(F::GET_INIT_DATA, vec![]), STEP)
130 .await
131 {
132 if let Ok(init) = InitData::parse(&r.payload) {
133 id.api_version = Some(init.api_version);
134 id.chip = init.chip_type.zip(init.chip_version);
135 id.series = init.chip_type.and_then(Series::from_chip_type);
136 id.sis = Some(init.is_sis());
137 let own = id.node_id.unwrap_or(1);
138 id.node_count = Some(init.nodes.iter().filter(|&&n| n != own).count());
139 }
140 }
141 }
142 if c.supports(F::GET_CONTROLLER_CAPABILITIES) {
143 if let Ok(r) = api
144 .request(
145 DataFrame::request(F::GET_CONTROLLER_CAPABILITIES, vec![]),
146 STEP,
147 )
148 .await
149 {
150 id.primary = r.payload.first().map(|b| b & 0x01 == 0);
151 }
152 }
153 if c.supports(F::SERIAL_API_SETUP) {
154 if let Ok(r) = api
155 .request(
156 DataFrame::request(F::SERIAL_API_SETUP, vec![setup::GET_RF_REGION]),
157 STEP,
158 )
159 .await
160 {
161 if r.payload.first() == Some(&setup::GET_RF_REGION) {
162 id.region = r
163 .payload
164 .get(1)
165 .map(|&b| RfRegion::from_u8(b))
166 .filter(|r| !matches!(r, RfRegion::Other(_)));
167 }
168 }
169 }
170}
171
172pub async fn identify(api: &SerialApi) -> Option<ControllerIdentity> {
176 let resp = api
177 .request(
178 DataFrame::request(F::GET_SERIAL_API_CAPABILITIES, vec![]),
179 Duration::from_millis(800),
180 )
181 .await
182 .ok()?;
183 let c = SerialApiCapabilities::parse(&resp.payload).ok()?;
184 let mut id = ControllerIdentity {
185 firmware: format!("{}.{}", c.firmware_major, c.firmware_minor),
186 manufacturer_id: c.manufacturer_id,
187 product_type: c.product_type,
188 product_id: c.product_id,
189 capabilities: c,
190 library_version: None,
191 api_version: None,
192 chip: None,
193 series: None,
194 home_id: None,
195 node_id: None,
196 primary: None,
197 sis: None,
198 node_count: None,
199 region: None,
200 };
201 let _ = tokio::time::timeout(Duration::from_millis(2000), details(api, &mut id)).await;
202 Some(id)
203}
204
205pub async fn probe_port<P: Port>(port: P) -> Result<Option<ControllerIdentity>, SerialError> {
208 let config = Config {
209 max_attempts: 1,
210 ack_timeout: Duration::from_millis(500),
211 ..Config::default()
212 };
213 let (api, _unsolicited) = SerialApi::start(port, config);
214 let run = async {
215 let frame = DataFrame::request(F::GET_SERIAL_API_CAPABILITIES, vec![]);
216 let resp = match api.request(frame, Duration::from_millis(800)).await {
217 Ok(r) => r,
218 Err(
219 SerialError::NoAck(_) | SerialError::Rejected(_) | SerialError::ResponseTimeout,
220 ) => return Ok(None),
221 Err(e) => return Err(e),
222 };
223 let Ok(c) = SerialApiCapabilities::parse(&resp.payload) else {
224 return Ok(None);
225 };
226 let mut id = ControllerIdentity {
227 firmware: format!("{}.{}", c.firmware_major, c.firmware_minor),
228 manufacturer_id: c.manufacturer_id,
229 product_type: c.product_type,
230 product_id: c.product_id,
231 capabilities: c,
232 library_version: None,
233 api_version: None,
234 chip: None,
235 series: None,
236 home_id: None,
237 node_id: None,
238 primary: None,
239 sis: None,
240 node_count: None,
241 region: None,
242 };
243 let _ = tokio::time::timeout(
245 PROBE_TIMEOUT.saturating_sub(Duration::from_millis(1400)),
246 details(&api, &mut id),
247 )
248 .await;
249 Ok(Some(id))
250 };
251 let r = tokio::time::timeout(PROBE_TIMEOUT, run)
252 .await
253 .unwrap_or(Ok(None));
254 drop(api);
256 tokio::task::yield_now().await;
257 r
258}
259
260pub async fn probe(path: &str) -> Result<Option<ControllerIdentity>, SerialError> {
262 let port = crate::port::open(path)
263 .await
264 .map_err(|e| SerialError::Closed(e.to_string()))?;
265 probe_port(port).await
266}
267
268pub fn probe_blocking(path: &str) -> Result<Option<ControllerIdentity>, SerialError> {
271 let rt = tokio::runtime::Builder::new_current_thread()
272 .enable_io()
273 .enable_time()
274 .build()
275 .map_err(|e| SerialError::Closed(e.to_string()))?;
276 let r = rt.block_on(probe(path));
277 drop(rt);
278 r
279}