Skip to main content

zwave_serial/
probe.rs

1//! Probing a port: is there a Z-Wave controller, and which?
2//!
3//! The probe writes a NAK (harmless; it only asks a controller to drop a
4//! partial frame) and `GET_SERIAL_API_CAPABILITIES`, which only reads. Only
5//! if that is answered like a Z-Wave controller does it ask a few more
6//! read-only questions (version, controller id, init data, controller
7//! capabilities, RF region). Nothing writes the controller's memory, changes
8//! its state or resets it. The whole probe is bounded by [`PROBE_TIMEOUT`]
9//! and the port is closed when it returns, so a device that is not a Z-Wave
10//! controller sees a handful of bytes and nothing more.
11
12use 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
22/// Upper bound on a whole probe.
23pub const PROBE_TIMEOUT: Duration = Duration::from_millis(2900);
24
25/// The controller chip's series.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Series {
28    /// 500 series (ZW050x).
29    S500,
30    /// 700 series (EFR32ZG14 / ZGM130).
31    S700,
32    /// 800 series (EFR32ZG23 / ZGM230).
33    S800,
34}
35
36impl Series {
37    /// From the chip type in the init data.
38    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/// What answered on the port.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct ControllerIdentity {
51    /// Serial API firmware version, `major.minor`.
52    pub firmware: String,
53    /// Z-Wave manufacturer id of the stick.
54    pub manufacturer_id: u16,
55    /// Product type.
56    pub product_type: u16,
57    /// Product id.
58    pub product_id: u16,
59    /// The full capability response.
60    pub capabilities: SerialApiCapabilities,
61    /// Library version string, e.g. `Z-Wave 7.21`.
62    pub library_version: Option<String>,
63    /// Serial API version from the init data.
64    pub api_version: Option<u8>,
65    /// Chip type and version from the init data.
66    pub chip: Option<(u8, u8)>,
67    /// Chip series, when the chip type is known.
68    pub series: Option<Series>,
69    /// Home id of the network the controller is in.
70    pub home_id: Option<u32>,
71    /// The controller's own node id.
72    pub node_id: Option<NodeId>,
73    /// Whether it is the primary controller of its network (not a secondary).
74    pub primary: Option<bool>,
75    /// Whether it is the SUC/SIS.
76    pub sis: Option<bool>,
77    /// Nodes in its network, the controller excluded.
78    pub node_count: Option<usize>,
79    /// RF region, if the controller reports it.
80    pub region: Option<RfRegion>,
81}
82
83impl ControllerIdentity {
84    /// A best-effort name for well-known sticks.
85    pub fn known_name(&self) -> Option<&'static str> {
86        known_name(self.manufacturer_id, self.product_type, self.product_id)
87    }
88}
89
90/// Names of a few common sticks, by (manufacturer, product type, product id).
91pub 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
172/// Identifies the controller behind a running link with read-only
173/// requests (capabilities, version, controller id, init data, controller
174/// capabilities, RF region); `None` if it does not answer like one.
175pub 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
205/// Probes an open port. `Ok(None)` means nothing answered like a Z-Wave
206/// controller; `Err` is an I/O failure. The port is closed on return.
207pub 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        // Best effort: whatever the time bound leaves room for.
244        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    // Dropping the last handle stops the link task, which closes the port.
255    drop(api);
256    tokio::task::yield_now().await;
257    r
258}
259
260/// Opens `path` (a device or `tcp://host:port`) and probes it.
261pub 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
268/// [`probe`] for callers without an async runtime: runs on a private
269/// current-thread runtime, which is dropped (closing the port) before it returns.
270pub 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}