Skip to main content

zigbee_ezsp/
client.rs

1//! An async EZSP client over an ASH link.
2
3use 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/// What the NCP said about itself during start-up.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct NcpInfo {
23    /// Negotiated protocol version.
24    pub protocol: ProtocolVersion,
25    /// Stack type (2 for a Zigbee mesh stack).
26    pub stack_type: u8,
27    /// The `version` command's packed stack version (one nibble per part).
28    pub stack_version_packed: u16,
29    /// The full EmberZNet version from `VERSION_INFO`.
30    pub stack_version: StackVersion,
31    /// Why the NCP last reset (the RSTACK code).
32    pub reset_code: u8,
33}
34
35/// Unpack the `version` command's stack version: `0x7440` is 7.4.4.0.
36pub 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/// Client errors.
46#[derive(Debug, Clone, thiserror::Error)]
47pub enum EzspError {
48    /// The ASH link failed.
49    #[error("ASH link: {0}")]
50    Link(#[from] LinkError),
51    /// The link went down (NCP reset, timeouts, port closed).
52    #[error("NCP link down: {0}")]
53    Down(String),
54    /// No RSTACK: nothing that speaks ASH is on the port.
55    #[error("no ASH reply (is this an EZSP adapter at the right baud rate?)")]
56    NoReply,
57    /// No response to a command in time.
58    #[error("no response to frame {0:#06x}")]
59    Timeout(u16),
60    /// A frame header did not parse.
61    #[error("bad EZSP header: {0}")]
62    Header(#[from] HeaderError),
63    /// A response did not parse.
64    #[error("bad EZSP response: {0}")]
65    Decode(#[from] DecodeError),
66    /// The NCP rejected the command as invalid.
67    #[error("NCP rejected frame {frame_id:#06x} as invalid (reason {reason:#04x})")]
68    InvalidCommand {
69        /// The command.
70        frame_id: u16,
71        /// `EzspStatus` reason.
72        reason: u8,
73    },
74    /// The command ran and returned a failure status.
75    #[error("frame {frame_id:#06x} failed: {status}")]
76    Status {
77        /// The command.
78        frame_id: u16,
79        /// The status.
80        status: Status,
81    },
82    /// The NCP answered with a response that does not fit the command.
83    #[error("unexpected response {0:?}")]
84    Unexpected(Box<Response>),
85    /// The NCP's protocol version is outside what this crate speaks.
86    #[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        /// The NCP's protocol version.
92        protocol: u8,
93        /// Its packed stack version.
94        stack_version: u16,
95    },
96    /// The NCP is not a Zigbee stack.
97    #[error("stack type {0} is not a Zigbee mesh stack")]
98    StackType(u8),
99}
100
101/// Something the NCP sent that is not a response.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum EzspEvent {
104    /// A callback.
105    Callback(Callback),
106    /// The link is down; every later call fails. Start a new client.
107    Down(String),
108}
109
110/// Client settings.
111#[derive(Debug, Clone)]
112pub struct ClientConfig {
113    /// The ASH link's settings.
114    pub ash: AshConfig,
115    /// How long to wait for each response.
116    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/// An EZSP client. Clones share one connection; commands are sent one at a
145/// time, as EZSP requires.
146#[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
159/// Reset the link (RST) and wait for RSTACK. Returns the reset code.
160async 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
185/// Reset the NCP's ASH layer and report the RSTACK code: the one frame
186/// [`Ezsp::start`] begins with, and the cheapest proof that an EZSP NCP is on
187/// the port. Returns [`EzspError::NoReply`] when nothing answers.
188pub 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    /// Connect over `io`: reset the link, negotiate the protocol version
198    /// and read the stack version. Callbacks arrive on the receiver; it is
199    /// unbounded so a slow consumer never stalls command responses.
200    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        // The reader holds the client weakly: dropping the last `Ezsp` drops
220        // the link, which ends the link task and closes the port.
221        tokio::spawn(reader(Arc::downgrade(&inner), link_events, event_tx));
222        let ezsp = Ezsp { inner };
223
224        // First `version` in the legacy format, asking for the newest we speak.
225        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        // Again in the extended format, now at the NCP's version.
238        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    /// The negotiated protocol version.
274    pub fn version(&self) -> ProtocolVersion {
275        ProtocolVersion(self.inner.version.load(Ordering::SeqCst))
276    }
277
278    /// Send a command and wait for its response.
279    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    /// Send a command whose response is a status and require success.
336    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    /// `getValue`, requiring success.
347    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    /// `setValue`, requiring success.
359    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    /// `setConfigurationValue`, requiring success.
364    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    /// `getConfigurationValue`, requiring success.
370    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    /// `setPolicy`, requiring success.
385    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}