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