1use std::time::Duration;
16
17use tokio::io::{AsyncRead, AsyncWrite};
18use zigbee_ash::Config as AshConfig;
19use zigbee_ezsp::client::{unpack_stack_version, ClientConfig, Ezsp, EzspError};
20use zigbee_ezsp::{ids, Command, Response};
21use zigbee_primitives::Ieee;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25#[non_exhaustive]
26pub enum NcpKind {
27 Ezsp,
29 Znp,
31 Deconz,
33}
34
35impl NcpKind {
36 pub const ALL: [NcpKind; 3] = [NcpKind::Ezsp, NcpKind::Znp, NcpKind::Deconz];
38
39 pub fn name(self) -> &'static str {
41 match self {
42 NcpKind::Ezsp => "ezsp",
43 NcpKind::Znp => "znp",
44 NcpKind::Deconz => "deconz",
45 }
46 }
47}
48
49impl std::str::FromStr for NcpKind {
50 type Err = String;
51 fn from_str(s: &str) -> Result<Self, Self::Err> {
52 NcpKind::ALL
53 .into_iter()
54 .find(|k| k.name() == s)
55 .ok_or_else(|| format!("unknown coordinator family {s:?} (ezsp, znp or deconz)"))
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct NcpIdentity {
62 pub kind: NcpKind,
64 pub firmware: String,
67 pub protocol: u8,
69 pub supported: bool,
71 pub reset_code: u8,
73 pub ieee: Option<Ieee>,
75 pub manufacturer: Option<String>,
78 pub board: Option<String>,
81 pub product: Option<String>,
85}
86
87#[derive(Debug, thiserror::Error)]
89pub enum ProbeError {
90 #[error("port I/O: {0}")]
92 Io(#[from] std::io::Error),
93}
94
95pub const PROBE_TIMEOUT: Duration = Duration::from_secs(4);
97
98fn probe_config() -> ClientConfig {
99 ClientConfig {
100 ash: AshConfig {
104 rst_attempts: 1,
105 ..AshConfig::default()
106 },
107 response_timeout: Duration::from_millis(600),
108 }
109}
110
111fn token_string(bytes: &[u8]) -> Option<String> {
112 let text: String = bytes
113 .iter()
114 .take_while(|b| **b != 0x00 && **b != 0xFF)
115 .map(|b| *b as char)
116 .filter(|c| c.is_ascii_graphic() || *c == ' ')
117 .collect();
118 let text = text.trim().to_string();
119 (!text.is_empty()).then_some(text)
120}
121
122async fn mfg_string(ezsp: &Ezsp, token_id: u8) -> Option<String> {
123 match ezsp.call(Command::GetMfgToken { token_id }).await {
124 Ok(Response::GetMfgToken { data }) => token_string(&data),
125 _ => None,
126 }
127}
128
129pub async fn probe_ezsp<T>(io: T) -> Result<Option<NcpIdentity>, ProbeError>
132where
133 T: AsyncRead + AsyncWrite + Send + 'static,
134{
135 let result = tokio::time::timeout(PROBE_TIMEOUT, Ezsp::start(io, probe_config())).await;
136 let (ezsp, info, _events) = match result {
137 Err(_) => return Ok(None),
138 Ok(Ok(started)) => started,
139 Ok(Err(EzspError::Unsupported {
140 protocol,
141 stack_version,
142 })) => {
143 let (a, b, c, d) = unpack_stack_version(stack_version);
144 return Ok(Some(NcpIdentity {
145 kind: NcpKind::Ezsp,
146 firmware: format!("{a}.{b}.{c}.{d}"),
147 protocol,
148 supported: false,
149 reset_code: 0,
150 ieee: None,
151 manufacturer: None,
152 board: None,
153 product: None,
154 }));
155 }
156 Ok(Err(EzspError::Down(why)))
157 if why.contains("read failed") || why.contains("write failed") =>
158 {
159 return Err(ProbeError::Io(std::io::Error::other(why)));
160 }
161 Ok(Err(_)) => return Ok(None),
162 };
163 let v = info.stack_version;
164 let ieee = match ezsp.call(Command::GetEui64).await {
165 Ok(Response::GetEui64 { ieee }) => Some(ieee),
166 _ => None,
167 };
168 let manufacturer = mfg_string(&ezsp, ids::mfg_token::STRING).await;
169 let board = mfg_string(&ezsp, ids::mfg_token::BOARD_NAME).await;
170 Ok(Some(NcpIdentity {
171 kind: NcpKind::Ezsp,
172 firmware: format!("{}.{}.{}.{}", v.major, v.minor, v.patch, v.special),
173 protocol: info.protocol.0,
174 supported: true,
175 reset_code: info.reset_code,
176 ieee,
177 manufacturer,
178 board,
179 product: None,
180 }))
181}
182
183pub async fn probe_znp<T>(io: T) -> Result<Option<NcpIdentity>, ProbeError>
186where
187 T: AsyncRead + AsyncWrite + Send + 'static,
188{
189 use zigbee_znp::client::{ClientConfig as ZnpConfig, Znp, ZnpError};
190 use zigbee_znp::ids::product;
191 let config = ZnpConfig {
192 response_timeout: Duration::from_millis(500),
193 ping_attempts: 2,
194 skip_bootloader: true,
195 bootloader_delay: Duration::from_millis(300),
196 };
197 let (znp, _events) = match tokio::time::timeout(PROBE_TIMEOUT, Znp::open(io, config)).await {
198 Err(_) => return Ok(None),
199 Ok(Ok(opened)) => opened,
200 Ok(Err(ZnpError::Down(why))) if why.starts_with("read:") => {
201 return Err(ProbeError::Io(std::io::Error::other(why)))
202 }
203 Ok(Err(_)) => return Ok(None),
204 };
205 let v = znp.version();
206 let ieee = if v.is_supported() {
207 match znp.request_ok(zigbee_znp::Request::UtilGetDeviceInfo).await {
208 Ok(data) => zigbee_primitives::wire::Reader::new(data.get(1..).unwrap_or(&[]))
209 .ieee()
210 .ok(),
211 Err(_) => None,
212 }
213 } else {
214 None
215 };
216 let name = match v.product {
217 product::ZSTACK_3X0 => "Z-Stack 3.x.0",
218 product::ZSTACK_30X => "Z-Stack 3.0.x",
219 product::ZSTACK_12 => "Z-Stack 1.2",
220 _ => "Z-Stack",
221 };
222 Ok(Some(NcpIdentity {
223 kind: NcpKind::Znp,
224 firmware: v.firmware(),
225 protocol: v.transport,
226 supported: v.is_supported(),
227 reset_code: 0,
228 ieee,
229 manufacturer: None,
230 board: None,
231 product: Some(name.into()),
232 }))
233}
234
235pub async fn probe_deconz<T>(io: T) -> Result<Option<NcpIdentity>, ProbeError>
238where
239 T: AsyncRead + AsyncWrite + Send + 'static,
240{
241 use zigbee_deconz::client::{ClientConfig as DeconzConfig, Deconz, DeconzError};
242 let config = DeconzConfig {
243 response_timeout: Duration::from_millis(600),
244 version_attempts: 2,
245 };
246 let (deconz, _events) =
247 match tokio::time::timeout(PROBE_TIMEOUT, Deconz::open(io, config)).await {
248 Err(_) => return Ok(None),
249 Ok(Ok(opened)) => opened,
250 Ok(Err(DeconzError::Down(why))) if why.starts_with("read:") => {
251 return Err(ProbeError::Io(std::io::Error::other(why)))
252 }
253 Ok(Err(_)) => return Ok(None),
254 };
255 let v = deconz.version();
256 let ieee = deconz
257 .read_parameter(zigbee_deconz::ids::param::MAC_ADDRESS, &[])
258 .await
259 .ok()
260 .and_then(|b| <[u8; 8]>::try_from(b.as_slice()).ok())
261 .map(Ieee::from_le_bytes);
262 Ok(Some(NcpIdentity {
263 kind: NcpKind::Deconz,
264 firmware: v.text(),
265 protocol: 0,
266 supported: v.is_supported(),
267 reset_code: 0,
268 ieee,
269 manufacturer: Some("dresden elektronik".into()),
270 board: None,
271 product: Some(v.product().into()),
272 }))
273}
274
275pub async fn probe_stream<T>(io: T, kind: NcpKind) -> Result<Option<NcpIdentity>, ProbeError>
277where
278 T: AsyncRead + AsyncWrite + Send + 'static,
279{
280 match kind {
281 NcpKind::Ezsp => probe_ezsp(io).await,
282 NcpKind::Znp => probe_znp(io).await,
283 NcpKind::Deconz => probe_deconz(io).await,
284 }
285}
286
287#[cfg(feature = "serial")]
290pub async fn probe(
291 port: &str,
292 kind: NcpKind,
293 baud: u32,
294) -> Result<Option<NcpIdentity>, ProbeError> {
295 let io = crate::port::open(port, baud, crate::port::FlowControl::None).await?;
296 probe_stream(io, kind).await
297}
298
299#[cfg(feature = "serial")]
302pub async fn probe_any(port: &str, baud: u32) -> Result<Option<NcpIdentity>, ProbeError> {
303 for kind in NcpKind::ALL {
304 if let Some(found) = probe(port, kind, baud).await? {
305 return Ok(Some(found));
306 }
307 }
308 Ok(None)
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 #[test]
316 fn tokens_become_text() {
317 assert_eq!(
318 token_string(b"Nabu Casa\0\xff\xff"),
319 Some("Nabu Casa".into())
320 );
321 assert_eq!(token_string(&[0xFF; 16]), None);
322 }
323
324 #[tokio::test(start_paused = true)]
325 async fn silence_is_no_reply_not_an_error() {
326 let (a, _b) = tokio::io::duplex(64);
327 let started = tokio::time::Instant::now();
328 assert!(probe_ezsp(a).await.unwrap().is_none());
329 assert!(started.elapsed() <= PROBE_TIMEOUT);
330 }
331}