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(3);
97
98fn probe_config() -> ClientConfig {
99 ClientConfig {
100 ash: AshConfig {
101 rst_timeout: Duration::from_millis(1100),
102 rst_attempts: 2,
103 ..AshConfig::default()
104 },
105 response_timeout: Duration::from_millis(600),
106 }
107}
108
109fn token_string(bytes: &[u8]) -> Option<String> {
110 let text: String = bytes
111 .iter()
112 .take_while(|b| **b != 0x00 && **b != 0xFF)
113 .map(|b| *b as char)
114 .filter(|c| c.is_ascii_graphic() || *c == ' ')
115 .collect();
116 let text = text.trim().to_string();
117 (!text.is_empty()).then_some(text)
118}
119
120async fn mfg_string(ezsp: &Ezsp, token_id: u8) -> Option<String> {
121 match ezsp.call(Command::GetMfgToken { token_id }).await {
122 Ok(Response::GetMfgToken { data }) => token_string(&data),
123 _ => None,
124 }
125}
126
127pub async fn probe_ezsp<T>(io: T) -> Result<Option<NcpIdentity>, ProbeError>
130where
131 T: AsyncRead + AsyncWrite + Send + 'static,
132{
133 let result = tokio::time::timeout(PROBE_TIMEOUT, Ezsp::start(io, probe_config())).await;
134 let (ezsp, info, _events) = match result {
135 Err(_) => return Ok(None),
136 Ok(Ok(started)) => started,
137 Ok(Err(EzspError::Unsupported {
138 protocol,
139 stack_version,
140 })) => {
141 let (a, b, c, d) = unpack_stack_version(stack_version);
142 return Ok(Some(NcpIdentity {
143 kind: NcpKind::Ezsp,
144 firmware: format!("{a}.{b}.{c}.{d}"),
145 protocol,
146 supported: false,
147 reset_code: 0,
148 ieee: None,
149 manufacturer: None,
150 board: None,
151 product: None,
152 }));
153 }
154 Ok(Err(EzspError::Down(why)))
155 if why.contains("read failed") || why.contains("write failed") =>
156 {
157 return Err(ProbeError::Io(std::io::Error::other(why)));
158 }
159 Ok(Err(_)) => return Ok(None),
160 };
161 let v = info.stack_version;
162 let ieee = match ezsp.call(Command::GetEui64).await {
163 Ok(Response::GetEui64 { ieee }) => Some(ieee),
164 _ => None,
165 };
166 let manufacturer = mfg_string(&ezsp, ids::mfg_token::STRING).await;
167 let board = mfg_string(&ezsp, ids::mfg_token::BOARD_NAME).await;
168 Ok(Some(NcpIdentity {
169 kind: NcpKind::Ezsp,
170 firmware: format!("{}.{}.{}.{}", v.major, v.minor, v.patch, v.special),
171 protocol: info.protocol.0,
172 supported: true,
173 reset_code: info.reset_code,
174 ieee,
175 manufacturer,
176 board,
177 product: None,
178 }))
179}
180
181pub async fn probe_znp<T>(io: T) -> Result<Option<NcpIdentity>, ProbeError>
184where
185 T: AsyncRead + AsyncWrite + Send + 'static,
186{
187 use zigbee_znp::client::{ClientConfig as ZnpConfig, Znp, ZnpError};
188 use zigbee_znp::ids::product;
189 let config = ZnpConfig {
190 response_timeout: Duration::from_millis(500),
191 ping_attempts: 2,
192 skip_bootloader: true,
193 bootloader_delay: Duration::from_millis(300),
194 };
195 let (znp, _events) = match tokio::time::timeout(PROBE_TIMEOUT, Znp::open(io, config)).await {
196 Err(_) => return Ok(None),
197 Ok(Ok(opened)) => opened,
198 Ok(Err(ZnpError::Down(why))) if why.starts_with("read:") => {
199 return Err(ProbeError::Io(std::io::Error::other(why)))
200 }
201 Ok(Err(_)) => return Ok(None),
202 };
203 let v = znp.version();
204 let ieee = if v.is_supported() {
205 match znp.request_ok(zigbee_znp::Request::UtilGetDeviceInfo).await {
206 Ok(data) => zigbee_primitives::wire::Reader::new(data.get(1..).unwrap_or(&[]))
207 .ieee()
208 .ok(),
209 Err(_) => None,
210 }
211 } else {
212 None
213 };
214 let name = match v.product {
215 product::ZSTACK_3X0 => "Z-Stack 3.x.0",
216 product::ZSTACK_30X => "Z-Stack 3.0.x",
217 product::ZSTACK_12 => "Z-Stack 1.2",
218 _ => "Z-Stack",
219 };
220 Ok(Some(NcpIdentity {
221 kind: NcpKind::Znp,
222 firmware: v.firmware(),
223 protocol: v.transport,
224 supported: v.is_supported(),
225 reset_code: 0,
226 ieee,
227 manufacturer: None,
228 board: None,
229 product: Some(name.into()),
230 }))
231}
232
233pub async fn probe_deconz<T>(io: T) -> Result<Option<NcpIdentity>, ProbeError>
236where
237 T: AsyncRead + AsyncWrite + Send + 'static,
238{
239 use zigbee_deconz::client::{ClientConfig as DeconzConfig, Deconz, DeconzError};
240 let config = DeconzConfig {
241 response_timeout: Duration::from_millis(600),
242 version_attempts: 2,
243 };
244 let (deconz, _events) =
245 match tokio::time::timeout(PROBE_TIMEOUT, Deconz::open(io, config)).await {
246 Err(_) => return Ok(None),
247 Ok(Ok(opened)) => opened,
248 Ok(Err(DeconzError::Down(why))) if why.starts_with("read:") => {
249 return Err(ProbeError::Io(std::io::Error::other(why)))
250 }
251 Ok(Err(_)) => return Ok(None),
252 };
253 let v = deconz.version();
254 let ieee = deconz
255 .read_parameter(zigbee_deconz::ids::param::MAC_ADDRESS, &[])
256 .await
257 .ok()
258 .and_then(|b| <[u8; 8]>::try_from(b.as_slice()).ok())
259 .map(Ieee::from_le_bytes);
260 Ok(Some(NcpIdentity {
261 kind: NcpKind::Deconz,
262 firmware: v.text(),
263 protocol: 0,
264 supported: v.is_supported(),
265 reset_code: 0,
266 ieee,
267 manufacturer: Some("dresden elektronik".into()),
268 board: None,
269 product: Some(v.product().into()),
270 }))
271}
272
273pub async fn probe_stream<T>(io: T, kind: NcpKind) -> Result<Option<NcpIdentity>, ProbeError>
275where
276 T: AsyncRead + AsyncWrite + Send + 'static,
277{
278 match kind {
279 NcpKind::Ezsp => probe_ezsp(io).await,
280 NcpKind::Znp => probe_znp(io).await,
281 NcpKind::Deconz => probe_deconz(io).await,
282 }
283}
284
285#[cfg(feature = "serial")]
288pub async fn probe(
289 port: &str,
290 kind: NcpKind,
291 baud: u32,
292) -> Result<Option<NcpIdentity>, ProbeError> {
293 let io = crate::port::open(port, baud, crate::port::FlowControl::None).await?;
294 probe_stream(io, kind).await
295}
296
297#[cfg(feature = "serial")]
300pub async fn probe_any(port: &str, baud: u32) -> Result<Option<NcpIdentity>, ProbeError> {
301 for kind in NcpKind::ALL {
302 if let Some(found) = probe(port, kind, baud).await? {
303 return Ok(Some(found));
304 }
305 }
306 Ok(None)
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 #[test]
314 fn tokens_become_text() {
315 assert_eq!(
316 token_string(b"Nabu Casa\0\xff\xff"),
317 Some("Nabu Casa".into())
318 );
319 assert_eq!(token_string(&[0xFF; 16]), None);
320 }
321
322 #[tokio::test(start_paused = true)]
323 async fn silence_is_no_reply_not_an_error() {
324 let (a, _b) = tokio::io::duplex(64);
325 let started = tokio::time::Instant::now();
326 assert!(probe_ezsp(a).await.unwrap().is_none());
327 assert!(started.elapsed() <= PROBE_TIMEOUT);
328 }
329}