Skip to main content

zigbee_znp/
client.rs

1//! An async ZNP client: one synchronous request at a time, as MT requires,
2//! and every asynchronous frame as an event.
3
4use std::sync::{Arc, Mutex, Weak};
5use std::time::Duration;
6
7use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
8use tokio::sync::{mpsc, oneshot};
9use zigbee_primitives::wire::Reader;
10
11use crate::frame::{Decoded, Decoder, Frame, FrameError, Kind};
12use crate::ids::{self, subsystem};
13use crate::message::{DecodeError, Indication, Request};
14
15/// The serial bootloader on CC2652 sticks waits a few seconds for an image
16/// unless it sees this byte first.
17const SKIP_BOOTLOADER: u8 = 0xEF;
18/// The longest an OSAL NV read returns per request.
19const NV_CHUNK: usize = 240;
20
21/// Client errors.
22#[derive(Debug, Clone, thiserror::Error)]
23pub enum ZnpError {
24    /// The port closed or failed.
25    #[error("ZNP port down: {0}")]
26    Down(String),
27    /// Nothing answered `SYS_PING`.
28    #[error("no ZNP reply (is this a Z-Stack coordinator at the right baud rate?)")]
29    NoReply,
30    /// No response in time.
31    #[error("no response to {subsystem:#04x} {id:#04x}")]
32    Timeout {
33        /// Subsystem.
34        subsystem: u8,
35        /// Command.
36        id: u8,
37    },
38    /// The NCP does not know the command.
39    #[error("the NCP rejected {subsystem:#04x} {id:#04x} (RPC error {code:#04x})")]
40    Rpc {
41        /// Subsystem.
42        subsystem: u8,
43        /// Command.
44        id: u8,
45        /// 1 invalid subsystem, 2 invalid command, 3 invalid parameter, 4 invalid length.
46        code: u8,
47    },
48    /// The command returned a failure status.
49    #[error("{subsystem:#04x} {id:#04x} failed with status {status:#04x}")]
50    Status {
51        /// Subsystem.
52        subsystem: u8,
53        /// Command.
54        id: u8,
55        /// Status.
56        status: u8,
57    },
58    /// A response did not parse.
59    #[error("bad ZNP response: {0}")]
60    Decode(#[from] DecodeError),
61    /// A request did not encode.
62    #[error(transparent)]
63    Frame(#[from] FrameError),
64    /// The firmware is not Z-Stack 3.
65    #[error("Z-Stack product {product} {major}.{minor}.{maint} is not supported: need Z-Stack 3.0.x or 3.x.0 (Zigbee 3.0)")]
66    Unsupported {
67        /// Product id.
68        product: u8,
69        /// Major release.
70        major: u8,
71        /// Minor release.
72        minor: u8,
73        /// Maintenance release.
74        maint: u8,
75    },
76}
77
78impl From<zigbee_primitives::wire::Truncated> for ZnpError {
79    fn from(e: zigbee_primitives::wire::Truncated) -> Self {
80        ZnpError::Decode(DecodeError::Truncated(e))
81    }
82}
83
84/// `SYS_VERSION`.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct Version {
87    /// Transport revision.
88    pub transport: u8,
89    /// Product ([`ids::product`]).
90    pub product: u8,
91    /// Major release.
92    pub major: u8,
93    /// Minor release.
94    pub minor: u8,
95    /// Maintenance release.
96    pub maint: u8,
97    /// Firmware build, usually a date such as 20230507.
98    pub revision: Option<u32>,
99}
100
101impl Version {
102    /// Parse the response.
103    pub fn parse(data: &[u8]) -> Result<Version, DecodeError> {
104        let mut r = Reader::new(data);
105        Ok(Version {
106            transport: r.u8()?,
107            product: r.u8()?,
108            major: r.u8()?,
109            minor: r.u8()?,
110            maint: r.u8()?,
111            revision: if r.remaining() >= 4 {
112                Some(r.u32()?)
113            } else {
114                None
115            },
116        })
117    }
118
119    /// Z-Stack 3.0.x or 3.x.0.
120    pub fn is_supported(&self) -> bool {
121        matches!(
122            self.product,
123            ids::product::ZSTACK_3X0 | ids::product::ZSTACK_30X
124        )
125    }
126
127    /// Extended NV tables (3.x.0) rather than legacy items (3.0.x).
128    pub fn has_extended_nv(&self) -> bool {
129        self.product == ids::product::ZSTACK_3X0
130    }
131
132    /// `3.30.00.20230507`-style text.
133    pub fn firmware(&self) -> String {
134        match self.revision {
135            Some(rev) => format!("{}.{}.{}.{rev}", self.major, self.minor, self.maint),
136            None => format!("{}.{}.{}", self.major, self.minor, self.maint),
137        }
138    }
139}
140
141/// Something the NCP sent on its own.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub enum ZnpEvent {
144    /// An indication.
145    Indication(Indication),
146    /// The port is down; every later request fails.
147    Down(String),
148}
149
150/// Client settings.
151#[derive(Debug, Clone)]
152pub struct ClientConfig {
153    /// How long to wait for each synchronous response.
154    pub response_timeout: Duration,
155    /// Pings before giving up at start.
156    pub ping_attempts: u32,
157    /// Send the CC2652 bootloader skip byte first.
158    pub skip_bootloader: bool,
159    /// How long to wait after it.
160    pub bootloader_delay: Duration,
161}
162
163impl Default for ClientConfig {
164    fn default() -> Self {
165        ClientConfig {
166            response_timeout: Duration::from_secs(6),
167            ping_attempts: 3,
168            skip_bootloader: true,
169            bootloader_delay: Duration::from_millis(500),
170        }
171    }
172}
173
174struct Pending {
175    subsystem: u8,
176    id: u8,
177    reply: oneshot::Sender<Result<Vec<u8>, ZnpError>>,
178}
179
180struct Inner {
181    write: mpsc::Sender<Vec<u8>>,
182    down: Mutex<Option<String>>,
183    lock: tokio::sync::Mutex<()>,
184    pending: Mutex<Option<Pending>>,
185    timeout: Duration,
186    /// Dropped with the client, which stops the reader and closes the port.
187    _close: oneshot::Sender<()>,
188}
189
190/// A ZNP client. Clones share one connection.
191#[derive(Clone)]
192pub struct Znp {
193    inner: Arc<Inner>,
194    version: Version,
195}
196
197impl std::fmt::Debug for Znp {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        f.debug_struct("Znp")
200            .field("version", &self.version)
201            .finish_non_exhaustive()
202    }
203}
204
205impl Znp {
206    /// Connect over `io`: skip the bootloader, ping, and read the version,
207    /// requiring Z-Stack 3. Indications arrive on the receiver; it is
208    /// unbounded so a slow consumer never stalls responses.
209    pub async fn start<T>(
210        io: T,
211        config: ClientConfig,
212    ) -> Result<(Znp, mpsc::UnboundedReceiver<ZnpEvent>), ZnpError>
213    where
214        T: AsyncRead + AsyncWrite + Send + 'static,
215    {
216        let (znp, events) = Znp::open(io, config).await?;
217        let version = znp.version;
218        if !version.is_supported() {
219            return Err(ZnpError::Unsupported {
220                product: version.product,
221                major: version.major,
222                minor: version.minor,
223                maint: version.maint,
224            });
225        }
226        Ok((znp, events))
227    }
228
229    /// Connect over `io` and read the version without requiring a
230    /// supported product: what a probe needs.
231    pub async fn open<T>(
232        io: T,
233        config: ClientConfig,
234    ) -> Result<(Znp, mpsc::UnboundedReceiver<ZnpEvent>), ZnpError>
235    where
236        T: AsyncRead + AsyncWrite + Send + 'static,
237    {
238        let (inner, events) = spawn(io, &config);
239        if config.skip_bootloader {
240            let _ = inner.write.send(vec![SKIP_BOOTLOADER]).await;
241            tokio::time::sleep(config.bootloader_delay).await;
242        }
243        let mut znp = Znp {
244            inner,
245            version: Version {
246                transport: 0,
247                product: 0,
248                major: 0,
249                minor: 0,
250                maint: 0,
251                revision: None,
252            },
253        };
254        let mut answered = false;
255        for _ in 0..config.ping_attempts.max(1) {
256            match znp.request(Request::SysPing).await {
257                Ok(_) => {
258                    answered = true;
259                    break;
260                }
261                Err(ZnpError::Timeout { .. }) => continue,
262                Err(e) => return Err(e),
263            }
264        }
265        if !answered {
266            return Err(ZnpError::NoReply);
267        }
268        znp.version = Version::parse(&znp.request(Request::SysVersion).await?)?;
269        Ok((znp, events))
270    }
271
272    /// The firmware's version.
273    pub fn version(&self) -> Version {
274        self.version
275    }
276
277    /// Send a synchronous request and return its response data.
278    pub async fn request(&self, request: Request) -> Result<Vec<u8>, ZnpError> {
279        let frame = request.encode();
280        let bytes = frame.encode()?;
281        if frame.kind != Kind::Sreq {
282            self.send(bytes).await?;
283            return Ok(Vec::new());
284        }
285        let _one_at_a_time = self.inner.lock.lock().await;
286        if let Some(why) = self.inner.down.lock().ok().and_then(|d| d.clone()) {
287            return Err(ZnpError::Down(why));
288        }
289        let (tx, rx) = oneshot::channel();
290        if let Ok(mut p) = self.inner.pending.lock() {
291            *p = Some(Pending {
292                subsystem: frame.subsystem,
293                id: frame.id,
294                reply: tx,
295            });
296        }
297        tracing::trace!(subsystem = frame.subsystem, id = frame.id, "znp tx");
298        self.send(bytes).await?;
299        let result = match tokio::time::timeout(self.inner.timeout, rx).await {
300            Ok(Ok(result)) => result,
301            Ok(Err(_)) => Err(ZnpError::Down(self.down_reason())),
302            Err(_) => Err(ZnpError::Timeout {
303                subsystem: frame.subsystem,
304                id: frame.id,
305            }),
306        };
307        if let Ok(mut p) = self.inner.pending.lock() {
308            *p = None;
309        }
310        result
311    }
312
313    /// A request whose response starts with a status byte; require success.
314    pub async fn request_ok(&self, request: Request) -> Result<Vec<u8>, ZnpError> {
315        let (subsystem, id) = request.command();
316        let data = self.request(request).await?;
317        match data.first() {
318            Some(&ids::status::SUCCESS) | None => Ok(data),
319            Some(&status) => Err(ZnpError::Status {
320                subsystem,
321                id,
322                status,
323            }),
324        }
325    }
326
327    async fn send(&self, bytes: Vec<u8>) -> Result<(), ZnpError> {
328        self.inner
329            .write
330            .send(bytes)
331            .await
332            .map_err(|_| ZnpError::Down(self.down_reason()))
333    }
334
335    fn down_reason(&self) -> String {
336        self.inner
337            .down
338            .lock()
339            .ok()
340            .and_then(|d| d.clone())
341            .unwrap_or_else(|| "port closed".into())
342    }
343
344    /// Read a whole OSAL NV item. `None` when it does not exist.
345    pub async fn nv_read(&self, id: u16) -> Result<Option<Vec<u8>>, ZnpError> {
346        let len = self.request(Request::OsalNvLength { id }).await?;
347        let len = usize::from(Reader::new(&len).u16()?);
348        if len == 0 {
349            return Ok(None);
350        }
351        let mut value = Vec::with_capacity(len);
352        while value.len() < len {
353            let offset = u8::try_from(value.len()).map_err(|_| ZnpError::Status {
354                subsystem: subsystem::SYS,
355                id: ids::sys::OSAL_NV_READ,
356                status: ids::status::NV_BAD_ITEM_LEN,
357            })?;
358            let data = self.request_ok(Request::OsalNvRead { id, offset }).await?;
359            let mut r = Reader::new(&data);
360            let _status = r.u8()?;
361            let chunk = r.u8_prefixed()?;
362            if chunk.is_empty() {
363                break;
364            }
365            value.extend_from_slice(chunk);
366        }
367        value.truncate(len);
368        Ok(Some(value))
369    }
370
371    /// Write an OSAL NV item, creating it at this length if needed.
372    pub async fn nv_write(&self, id: u16, value: &[u8]) -> Result<(), ZnpError> {
373        let len = u16::try_from(value.len()).unwrap_or(u16::MAX);
374        let init = self
375            .request(Request::OsalNvItemInit {
376                id,
377                len,
378                init: value
379                    .get(..value.len().min(NV_CHUNK))
380                    .unwrap_or(value)
381                    .to_vec(),
382            })
383            .await?;
384        match init.first() {
385            Some(&ids::status::SUCCESS) | Some(&ids::status::NV_ITEM_UNINIT) => {}
386            Some(&status) => {
387                return Err(ZnpError::Status {
388                    subsystem: subsystem::SYS,
389                    id: ids::sys::OSAL_NV_ITEM_INIT,
390                    status,
391                })
392            }
393            None => {}
394        }
395        for (i, chunk) in value.chunks(NV_CHUNK).enumerate() {
396            let offset = u8::try_from(i * NV_CHUNK).map_err(|_| ZnpError::Status {
397                subsystem: subsystem::SYS,
398                id: ids::sys::OSAL_NV_WRITE,
399                status: ids::status::NV_BAD_ITEM_LEN,
400            })?;
401            self.request_ok(Request::OsalNvWrite {
402                id,
403                offset,
404                value: chunk.to_vec(),
405            })
406            .await?;
407        }
408        Ok(())
409    }
410
411    /// Read a whole extended NV item. `None` when it does not exist.
412    pub async fn nv_ex_read(
413        &self,
414        sysid: u8,
415        item: u16,
416        sub: u16,
417    ) -> Result<Option<Vec<u8>>, ZnpError> {
418        let len = self.request(Request::NvLength { sysid, item, sub }).await?;
419        let len = Reader::new(&len).u32()? as usize;
420        if len == 0 {
421            return Ok(None);
422        }
423        let mut value = Vec::with_capacity(len.min(4096));
424        while value.len() < len {
425            let want = (len - value.len()).min(NV_CHUNK);
426            let data = self
427                .request_ok(Request::NvRead {
428                    sysid,
429                    item,
430                    sub,
431                    offset: u16::try_from(value.len()).unwrap_or(u16::MAX),
432                    len: want as u8,
433                })
434                .await?;
435            let mut r = Reader::new(&data);
436            let _status = r.u8()?;
437            let chunk = r.u8_prefixed()?;
438            if chunk.is_empty() {
439                break;
440            }
441            value.extend_from_slice(chunk);
442        }
443        value.truncate(len);
444        Ok(Some(value))
445    }
446
447    /// Write an existing extended NV item.
448    pub async fn nv_ex_write(
449        &self,
450        sysid: u8,
451        item: u16,
452        sub: u16,
453        value: &[u8],
454    ) -> Result<(), ZnpError> {
455        for (i, chunk) in value.chunks(NV_CHUNK).enumerate() {
456            self.request_ok(Request::NvWrite {
457                sysid,
458                item,
459                sub,
460                offset: u16::try_from(i * NV_CHUNK).unwrap_or(u16::MAX),
461                value: chunk.to_vec(),
462            })
463            .await?;
464        }
465        Ok(())
466    }
467}
468
469fn spawn<T>(io: T, config: &ClientConfig) -> (Arc<Inner>, mpsc::UnboundedReceiver<ZnpEvent>)
470where
471    T: AsyncRead + AsyncWrite + Send + 'static,
472{
473    let (read, mut write) = tokio::io::split(io);
474    let (write_tx, mut write_rx) = mpsc::channel::<Vec<u8>>(16);
475    let (close_tx, close_rx) = oneshot::channel();
476    let inner = Arc::new(Inner {
477        write: write_tx,
478        down: Mutex::new(None),
479        lock: tokio::sync::Mutex::new(()),
480        pending: Mutex::new(None),
481        timeout: config.response_timeout,
482        _close: close_tx,
483    });
484    let (event_tx, event_rx) = mpsc::unbounded_channel();
485    tokio::spawn(async move {
486        while let Some(bytes) = write_rx.recv().await {
487            if write.write_all(&bytes).await.is_err() || write.flush().await.is_err() {
488                break;
489            }
490        }
491    });
492    // The reader holds the client weakly: dropping the last `Znp` ends both
493    // tasks, which closes the port.
494    tokio::spawn(reader(Arc::downgrade(&inner), read, close_rx, event_tx));
495    (inner, event_rx)
496}
497
498async fn reader<R>(
499    weak: Weak<Inner>,
500    mut read: R,
501    mut close: oneshot::Receiver<()>,
502    events: mpsc::UnboundedSender<ZnpEvent>,
503) where
504    R: AsyncRead + Unpin,
505{
506    let mut decoder = Decoder::new();
507    let mut buf = [0u8; 256];
508    let reason = loop {
509        let read = tokio::select! {
510            r = read.read(&mut buf) => r,
511            _ = &mut close => return,
512        };
513        let n = match read {
514            Ok(0) => break "port closed".to_string(),
515            Ok(n) => n,
516            Err(e) => break format!("read: {e}"),
517        };
518        let Some(inner) = weak.upgrade() else { return };
519        for decoded in decoder.push(buf.get(..n).unwrap_or(&[])) {
520            match decoded {
521                Decoded::BadFcs => tracing::warn!("dropping ZNP frame with a bad check byte"),
522                Decoded::Frame(frame) => handle(&inner, frame, &events),
523            }
524        }
525    };
526    tracing::warn!(%reason, "ZNP port down");
527    let Some(inner) = weak.upgrade() else { return };
528    if let Ok(mut d) = inner.down.lock() {
529        *d = Some(reason.clone());
530    }
531    if let Some(p) = inner.pending.lock().ok().and_then(|mut p| p.take()) {
532        let _ = p.reply.send(Err(ZnpError::Down(reason.clone())));
533    }
534    let _ = events.send(ZnpEvent::Down(reason));
535}
536
537fn handle(inner: &Inner, frame: Frame, events: &mpsc::UnboundedSender<ZnpEvent>) {
538    match frame.kind {
539        Kind::Srsp => {
540            let pending = inner.pending.lock().ok().and_then(|mut p| p.take());
541            let Some(pending) = pending else {
542                tracing::warn!(
543                    subsystem = frame.subsystem,
544                    id = frame.id,
545                    "ZNP response with no request waiting"
546                );
547                return;
548            };
549            if frame.subsystem == subsystem::RPC_ERROR && frame.id == 0 {
550                let mut r = Reader::new(&frame.data);
551                let code = r.u8().unwrap_or(0);
552                let _ = pending.reply.send(Err(ZnpError::Rpc {
553                    subsystem: pending.subsystem,
554                    id: pending.id,
555                    code,
556                }));
557            } else if frame.subsystem == pending.subsystem && frame.id == pending.id {
558                let _ = pending.reply.send(Ok(frame.data));
559            } else {
560                tracing::warn!(
561                    subsystem = frame.subsystem,
562                    id = frame.id,
563                    "ZNP response for another request"
564                );
565                if let Ok(mut p) = inner.pending.lock() {
566                    *p = Some(pending);
567                }
568            }
569        }
570        Kind::Areq => match Indication::decode(&frame) {
571            Ok(ind) => {
572                tracing::trace!(?ind, "znp indication");
573                let _ = events.send(ZnpEvent::Indication(ind));
574            }
575            Err(DecodeError::Unknown { .. }) => {
576                tracing::trace!(
577                    subsystem = frame.subsystem,
578                    id = frame.id,
579                    "ignoring ZNP indication"
580                )
581            }
582            Err(e) => tracing::warn!(error = %e, "dropping malformed ZNP indication"),
583        },
584        Kind::Sreq | Kind::Poll => {
585            tracing::warn!("dropping a request frame from the NCP")
586        }
587    }
588}