1use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
4use std::sync::{Arc, Mutex};
5use std::time::Duration;
6
7use tokio::io::{AsyncRead, AsyncWrite};
8use tokio::sync::{mpsc, oneshot};
9use zigbee_ash::{Config as AshConfig, Event as AshEvent, Link, LinkError, LinkEvent, Role};
10use zigbee_primitives::wire::Reader;
11
12use crate::callback::Callback;
13use crate::command::{Command, DecodeError, Response};
14use crate::frame::{self, Format, HeaderError};
15use crate::ids;
16use crate::types::{
17 ProtocolVersion, StackVersion, Status, MAX_PROTOCOL_VERSION, MIN_PROTOCOL_VERSION,
18 SEC_MAN_PROTOCOL_VERSION,
19};
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct NcpInfo {
24 pub protocol: ProtocolVersion,
26 pub stack_type: u8,
28 pub stack_version_packed: u16,
30 pub stack_version: StackVersion,
32 pub reset_code: u8,
34}
35
36pub fn unpack_stack_version(packed: u16) -> (u8, u8, u8, u8) {
38 (
39 (packed >> 12) as u8,
40 ((packed >> 8) & 0xF) as u8,
41 ((packed >> 4) & 0xF) as u8,
42 (packed & 0xF) as u8,
43 )
44}
45
46#[derive(Debug, Clone, thiserror::Error)]
48pub enum EzspError {
49 #[error("ASH link: {0}")]
51 Link(#[from] LinkError),
52 #[error("NCP link down: {0}")]
54 Down(String),
55 #[error("no ASH reply (is this an EZSP adapter at the right baud rate?)")]
57 NoReply,
58 #[error("no response to frame {0:#06x}")]
60 Timeout(u16),
61 #[error("bad EZSP header: {0}")]
63 Header(#[from] HeaderError),
64 #[error("bad EZSP response: {0}")]
66 Decode(#[from] DecodeError),
67 #[error("NCP rejected frame {frame_id:#06x} as invalid (reason {reason:#04x})")]
69 InvalidCommand {
70 frame_id: u16,
72 reason: u8,
74 },
75 #[error("frame {frame_id:#06x} failed: {status}")]
77 Status {
78 frame_id: u16,
80 status: Status,
82 },
83 #[error("unexpected response {0:?}")]
85 Unexpected(Box<Response>),
86 #[error(
88 "EZSP protocol {protocol} (EmberZNet {}.{}.{}) is not supported: need {MIN_PROTOCOL_VERSION} (EmberZNet 6.7 to 6.10) or {SEC_MAN_PROTOCOL_VERSION} to {MAX_PROTOCOL_VERSION} (EmberZNet 7.4 or newer)",
89 unpack_stack_version(*stack_version).0, unpack_stack_version(*stack_version).1, unpack_stack_version(*stack_version).2
90 )]
91 Unsupported {
92 protocol: u8,
94 stack_version: u16,
96 },
97 #[error("stack type {0} is not a Zigbee mesh stack")]
99 StackType(u8),
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum EzspEvent {
105 Callback(Callback),
107 Down(String),
109}
110
111#[derive(Debug, Clone)]
113pub struct ClientConfig {
114 pub ash: AshConfig,
116 pub response_timeout: Duration,
118}
119
120impl Default for ClientConfig {
121 fn default() -> Self {
122 ClientConfig {
123 ash: AshConfig::default(),
124 response_timeout: Duration::from_secs(12),
125 }
126 }
127}
128
129struct Pending {
130 seq: u8,
131 frame_id: u16,
132 reply: oneshot::Sender<Result<Response, EzspError>>,
133}
134
135struct Inner {
136 link: Link,
137 version: AtomicU8,
138 extended: AtomicBool,
139 down: Mutex<Option<String>>,
140 seq: tokio::sync::Mutex<u8>,
141 pending: Mutex<Option<Pending>>,
142 timeout: Duration,
143}
144
145#[derive(Clone)]
148pub struct Ezsp {
149 inner: Arc<Inner>,
150}
151
152impl std::fmt::Debug for Ezsp {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.debug_struct("Ezsp")
155 .field("version", &self.version())
156 .finish_non_exhaustive()
157 }
158}
159
160async fn connect_link(
162 link: &Link,
163 events: &mut mpsc::Receiver<LinkEvent>,
164 config: &AshConfig,
165) -> Result<u8, EzspError> {
166 link.reset().await?;
167 let wait = config.rst_timeout * config.rst_attempts + Duration::from_millis(500);
168 let deadline = tokio::time::Instant::now() + wait;
169 loop {
170 match tokio::time::timeout_at(deadline, events.recv()).await {
171 Err(_) => return Err(EzspError::NoReply),
172 Ok(None) => return Err(EzspError::Down("link task stopped".into())),
173 Ok(Some(LinkEvent::Ash(AshEvent::Connected { reset_code }))) => return Ok(reset_code),
174 Ok(Some(LinkEvent::Ash(AshEvent::Down(zigbee_ash::DownReason::ResetTimeout)))) => {
175 return Err(EzspError::NoReply)
176 }
177 Ok(Some(LinkEvent::Ash(AshEvent::Down(reason)))) => {
178 return Err(EzspError::Down(format!("{reason:?}")))
179 }
180 Ok(Some(LinkEvent::Closed(why))) => return Err(EzspError::Down(why)),
181 Ok(Some(LinkEvent::Ash(AshEvent::Data(_)))) => {}
182 }
183 }
184}
185
186pub async fn ash_reset<T>(io: T, config: &AshConfig) -> Result<u8, EzspError>
190where
191 T: AsyncRead + AsyncWrite + Send + 'static,
192{
193 let (link, mut events) = Link::spawn(io, Role::Host, config.clone());
194 connect_link(&link, &mut events, config).await
195}
196
197impl Ezsp {
198 pub async fn start<T>(
202 io: T,
203 config: ClientConfig,
204 ) -> Result<(Ezsp, NcpInfo, mpsc::UnboundedReceiver<EzspEvent>), EzspError>
205 where
206 T: AsyncRead + AsyncWrite + Send + 'static,
207 {
208 let (link, mut link_events) = Link::spawn(io, Role::Host, config.ash.clone());
209 let reset_code = connect_link(&link, &mut link_events, &config.ash).await?;
210 let inner = Arc::new(Inner {
211 link,
212 version: AtomicU8::new(MAX_PROTOCOL_VERSION),
213 extended: AtomicBool::new(false),
214 down: Mutex::new(None),
215 seq: tokio::sync::Mutex::new(0),
216 pending: Mutex::new(None),
217 timeout: config.response_timeout,
218 });
219 let (event_tx, event_rx) = mpsc::unbounded_channel();
220 tokio::spawn(reader(Arc::downgrade(&inner), link_events, event_tx));
223 let ezsp = Ezsp { inner };
224
225 let (protocol, stack_type, packed) = ezsp.version_command(MAX_PROTOCOL_VERSION).await?;
227 if stack_type != ids::STACK_TYPE_MESH {
228 return Err(EzspError::StackType(stack_type));
229 }
230 if !ProtocolVersion(protocol).is_supported() {
231 return Err(EzspError::Unsupported {
232 protocol,
233 stack_version: packed,
234 });
235 }
236 ezsp.inner.version.store(protocol, Ordering::SeqCst);
237 ezsp.inner.extended.store(true, Ordering::SeqCst);
238 let (agreed, _, packed) = ezsp.version_command(protocol).await?;
240 if agreed != protocol {
241 return Err(EzspError::Unsupported {
242 protocol: agreed,
243 stack_version: packed,
244 });
245 }
246 let stack_version = ezsp
247 .get_value(ids::value::VERSION_INFO)
248 .await
249 .and_then(|bytes| {
250 StackVersion::read(&mut Reader::new(&bytes))
251 .map_err(|e| EzspError::Decode(DecodeError::Truncated(e)))
252 })?;
253 let info = NcpInfo {
254 protocol: ProtocolVersion(protocol),
255 stack_type,
256 stack_version_packed: packed,
257 stack_version,
258 reset_code,
259 };
260 Ok((ezsp, info, event_rx))
261 }
262
263 async fn version_command(&self, desired: u8) -> Result<(u8, u8, u16), EzspError> {
264 match self.call(Command::Version { desired }).await? {
265 Response::Version {
266 protocol_version,
267 stack_type,
268 stack_version,
269 } => Ok((protocol_version, stack_type, stack_version)),
270 other => Err(EzspError::Unexpected(Box::new(other))),
271 }
272 }
273
274 pub fn version(&self) -> ProtocolVersion {
276 ProtocolVersion(self.inner.version.load(Ordering::SeqCst))
277 }
278
279 pub async fn call(&self, command: Command) -> Result<Response, EzspError> {
281 let frame_id = command.frame_id();
282 let mut seq = self.inner.seq.lock().await;
283 if let Some(why) = self.inner.down.lock().ok().and_then(|d| d.clone()) {
284 return Err(EzspError::Down(why));
285 }
286 let this_seq = *seq;
287 *seq = seq.wrapping_add(1);
288 let format = if self.inner.extended.load(Ordering::SeqCst) {
289 Format::Extended
290 } else {
291 Format::Legacy
292 };
293 let bytes = frame::encode(
294 format,
295 this_seq,
296 0x00,
297 frame_id,
298 &command.encode(self.version()),
299 );
300 let (tx, rx) = oneshot::channel();
301 if let Ok(mut pending) = self.inner.pending.lock() {
302 *pending = Some(Pending {
303 seq: this_seq,
304 frame_id,
305 reply: tx,
306 });
307 }
308 tracing::trace!(frame_id, seq = this_seq, "ezsp tx");
309 self.inner.link.send(bytes).await?;
310 let result = match tokio::time::timeout(self.inner.timeout, rx).await {
311 Ok(Ok(result)) => result,
312 Ok(Err(_)) => Err(EzspError::Down(self.down_reason())),
313 Err(_) => Err(EzspError::Timeout(frame_id)),
314 };
315 if let Ok(mut pending) = self.inner.pending.lock() {
316 *pending = None;
317 }
318 drop(seq);
319 match result? {
320 Response::InvalidCommand { reason } => {
321 Err(EzspError::InvalidCommand { frame_id, reason })
322 }
323 response => Ok(response),
324 }
325 }
326
327 fn down_reason(&self) -> String {
328 self.inner
329 .down
330 .lock()
331 .ok()
332 .and_then(|d| d.clone())
333 .unwrap_or_else(|| "link closed".into())
334 }
335
336 pub async fn call_ok(&self, command: Command) -> Result<(), EzspError> {
338 let frame_id = command.frame_id();
339 let response = self.call(command).await?;
340 match response.status() {
341 Some(status) if status.is_ok() => Ok(()),
342 Some(status) => Err(EzspError::Status { frame_id, status }),
343 None => Ok(()),
344 }
345 }
346
347 pub async fn get_value(&self, value_id: u8) -> Result<Vec<u8>, EzspError> {
349 match self.call(Command::GetValue { value_id }).await? {
350 Response::GetValue { status, value } if status.is_ok() => Ok(value),
351 Response::GetValue { status, .. } => Err(EzspError::Status {
352 frame_id: ids::frame::GET_VALUE,
353 status,
354 }),
355 other => Err(EzspError::Unexpected(Box::new(other))),
356 }
357 }
358
359 pub async fn set_value(&self, value_id: u8, value: Vec<u8>) -> Result<(), EzspError> {
361 self.call_ok(Command::SetValue { value_id, value }).await
362 }
363
364 pub async fn set_config(&self, config_id: u8, value: u16) -> Result<(), EzspError> {
366 self.call_ok(Command::SetConfigurationValue { config_id, value })
367 .await
368 }
369
370 pub async fn get_config(&self, config_id: u8) -> Result<u16, EzspError> {
372 match self
373 .call(Command::GetConfigurationValue { config_id })
374 .await?
375 {
376 Response::GetConfigurationValue { status, value } if status.is_ok() => Ok(value),
377 Response::GetConfigurationValue { status, .. } => Err(EzspError::Status {
378 frame_id: ids::frame::GET_CONFIGURATION_VALUE,
379 status,
380 }),
381 other => Err(EzspError::Unexpected(Box::new(other))),
382 }
383 }
384
385 pub async fn set_policy(&self, policy_id: u8, decision: u8) -> Result<(), EzspError> {
387 self.call_ok(Command::SetPolicy {
388 policy_id,
389 decision,
390 })
391 .await
392 }
393}
394
395async fn reader(
396 weak: std::sync::Weak<Inner>,
397 mut link_events: mpsc::Receiver<LinkEvent>,
398 events: mpsc::UnboundedSender<EzspEvent>,
399) {
400 let reason = loop {
401 let Some(event) = link_events.recv().await else {
402 break "link task stopped".to_string();
403 };
404 let Some(inner) = weak.upgrade() else { return };
405 let data = match event {
406 LinkEvent::Ash(AshEvent::Data(data)) => data,
407 LinkEvent::Ash(AshEvent::Connected { .. }) => continue,
408 LinkEvent::Ash(AshEvent::Down(reason)) => break format!("{reason:?}"),
409 LinkEvent::Closed(why) => break why,
410 };
411 let format = if inner.extended.load(Ordering::SeqCst) {
412 Format::Extended
413 } else {
414 Format::Legacy
415 };
416 let version = ProtocolVersion(inner.version.load(Ordering::SeqCst));
417 let header = match frame::parse(&data, format) {
418 Ok(h) => h,
419 Err(e) => {
420 tracing::warn!(error = %e, "dropping malformed EZSP frame");
421 continue;
422 }
423 };
424 if !header.is_response() {
425 tracing::warn!(
426 frame_id = header.frame_id,
427 "dropping EZSP command frame from the NCP"
428 );
429 continue;
430 }
431 if header.overflow() {
432 tracing::warn!("NCP reports it ran out of memory (overflow)");
433 }
434 if header.is_callback() {
435 match Callback::decode(version, header.frame_id, header.params) {
436 Ok(cb) => {
437 tracing::trace!(?cb, "ezsp callback");
438 let _ = events.send(EzspEvent::Callback(cb));
439 }
440 Err(e) => {
441 tracing::warn!(frame_id = header.frame_id, error = %e, "dropping malformed EZSP callback")
442 }
443 }
444 continue;
445 }
446 let pending = inner.pending.lock().ok().and_then(|mut p| p.take());
447 let Some(pending) = pending else {
448 tracing::warn!(
449 frame_id = header.frame_id,
450 seq = header.seq,
451 "EZSP response with no command waiting"
452 );
453 continue;
454 };
455 if header.seq != pending.seq {
456 tracing::warn!(
457 want = pending.seq,
458 got = header.seq,
459 "EZSP response out of sequence"
460 );
461 if let Ok(mut p) = inner.pending.lock() {
462 *p = Some(pending);
463 }
464 continue;
465 }
466 let result = if header.truncated() {
467 Err(EzspError::Decode(DecodeError::Truncated(
468 zigbee_primitives::wire::Truncated {
469 offset: 0,
470 needed: 0,
471 },
472 )))
473 } else if header.frame_id == ids::frame::INVALID_COMMAND
474 || header.frame_id == pending.frame_id
475 {
476 Response::decode(version, header.frame_id, header.params).map_err(EzspError::from)
477 } else {
478 Err(EzspError::Decode(DecodeError::UnknownFrame(
479 header.frame_id,
480 )))
481 };
482 let _ = pending.reply.send(result);
483 };
484 tracing::warn!(%reason, "EZSP link down");
485 let Some(inner) = weak.upgrade() else { return };
486 if let Ok(mut down) = inner.down.lock() {
487 *down = Some(reason.clone());
488 }
489 if let Some(p) = inner.pending.lock().ok().and_then(|mut p| p.take()) {
490 let _ = p.reply.send(Err(EzspError::Down(reason.clone())));
491 }
492 let _ = events.send(EzspEvent::Down(reason));
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 #[test]
500 fn unpacks_stack_versions() {
501 assert_eq!(unpack_stack_version(0x7440), (7, 4, 4, 0));
502 assert_eq!(unpack_stack_version(0x6A30), (6, 10, 3, 0));
503 }
504}