Skip to main content

zwave_serial/
message.rs

1//! Typed Serial API messages: request builders and parsers for responses,
2//! callbacks and unsolicited frames.
3//!
4//! Every parser takes the frame payload and returns `Err(Malformed)` rather
5//! than panicking on short or inconsistent input; lengths inside a payload
6//! are clamped to what the payload actually holds.
7
8use crate::frame::{DataFrame, FrameType};
9use crate::function::FunctionId as F;
10use crate::NodeId;
11
12/// A payload that does not have the shape its function id promises.
13#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14#[error("malformed {0} payload")]
15pub struct Malformed(pub &'static str);
16
17type Result<T> = std::result::Result<T, Malformed>;
18
19fn need(p: &[u8], n: usize, what: &'static str) -> Result<()> {
20    if p.len() < n {
21        Err(Malformed(what))
22    } else {
23        Ok(())
24    }
25}
26
27/// Appends a node id as `len` bytes (1 classic, 2 when the Serial API uses 16-bit node ids).
28pub fn node_bytes(node: NodeId, len: usize, out: &mut Vec<u8>) {
29    if len == 2 {
30        out.extend_from_slice(&node.to_be_bytes());
31    } else {
32        out.push(node as u8);
33    }
34}
35
36/// The node id at the start of a payload, `len` bytes wide.
37pub fn parse_node_id(p: &[u8], len: usize) -> Option<NodeId> {
38    node_id(p, 0, len, "node id").ok()
39}
40
41/// Reads a node id of `len` bytes (1 classic, 2 Long Range) at `at`.
42fn node_id(p: &[u8], at: usize, len: usize, what: &'static str) -> Result<NodeId> {
43    need(p, at + len, what)?;
44    Ok(if len == 2 {
45        u16::from_be_bytes([p[at], p[at + 1]])
46    } else {
47        u16::from(p[at])
48    })
49}
50
51/// Parses a command class list, with two-byte ids from `0xF1`, splitting
52/// supported from controlled at the `0xEF` mark.
53pub fn parse_cc_list(p: &[u8]) -> (Vec<u16>, Vec<u16>) {
54    let mut supported = Vec::new();
55    let mut controlled = Vec::new();
56    let mut after_mark = false;
57    let mut i = 0;
58    while i < p.len() {
59        let b = p[i];
60        if b == 0xef {
61            after_mark = true;
62            i += 1;
63            continue;
64        }
65        let cc = if b >= 0xf1 {
66            let Some(&lo) = p.get(i + 1) else { break };
67            i += 2;
68            (u16::from(b) << 8) | u16::from(lo)
69        } else {
70            i += 1;
71            u16::from(b)
72        };
73        if after_mark {
74            controlled.push(cc);
75        } else {
76            supported.push(cc);
77        }
78    }
79    (supported, controlled)
80}
81
82/// Encodes a command class list (no controlled part).
83pub fn encode_cc_list(ccs: &[u16], out: &mut Vec<u8>) {
84    for &cc in ccs {
85        if cc > 0xff {
86            out.extend_from_slice(&cc.to_be_bytes());
87        } else {
88            out.push(cc as u8);
89        }
90    }
91}
92
93/// Parses a node bit mask (bit 0 of byte 0 is node `first`).
94pub fn parse_node_mask(mask: &[u8], first: NodeId) -> Vec<NodeId> {
95    let mut v = Vec::new();
96    for (i, b) in mask.iter().enumerate() {
97        for bit in 0..8 {
98            if b & (1 << bit) != 0 {
99                v.push(first + (i * 8 + bit) as NodeId);
100            }
101        }
102    }
103    v
104}
105
106/// Encodes a node bit mask of `len` bytes starting at node 1.
107pub fn encode_node_mask(nodes: &[NodeId], len: usize) -> Vec<u8> {
108    let mut m = vec![0u8; len];
109    for &n in nodes {
110        let i = usize::from(n.saturating_sub(1));
111        if n >= 1 && i / 8 < len {
112            m[i / 8] |= 1 << (i % 8);
113        }
114    }
115    m
116}
117
118/// Response to `GET_SERIAL_API_CAPABILITIES`.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct SerialApiCapabilities {
121    /// Firmware (application) version, major.
122    pub firmware_major: u8,
123    /// Firmware (application) version, minor.
124    pub firmware_minor: u8,
125    /// Manufacturer id of the stick.
126    pub manufacturer_id: u16,
127    /// Product type.
128    pub product_type: u16,
129    /// Product id.
130    pub product_id: u16,
131    /// Bit mask of supported function ids (bit `n-1` for function `n`).
132    pub functions: [u8; 32],
133}
134
135impl SerialApiCapabilities {
136    /// Parses the response payload.
137    pub fn parse(p: &[u8]) -> Result<Self> {
138        need(p, 8, "serial API capabilities")?;
139        let mut functions = [0u8; 32];
140        let mask = &p[8..p.len().min(40)];
141        functions[..mask.len()].copy_from_slice(mask);
142        Ok(SerialApiCapabilities {
143            firmware_major: p[0],
144            firmware_minor: p[1],
145            manufacturer_id: u16::from_be_bytes([p[2], p[3]]),
146            product_type: u16::from_be_bytes([p[4], p[5]]),
147            product_id: u16::from_be_bytes([p[6], p[7]]),
148            functions,
149        })
150    }
151
152    /// Encodes the payload (simulators).
153    pub fn encode(&self) -> Vec<u8> {
154        let mut v = vec![self.firmware_major, self.firmware_minor];
155        v.extend_from_slice(&self.manufacturer_id.to_be_bytes());
156        v.extend_from_slice(&self.product_type.to_be_bytes());
157        v.extend_from_slice(&self.product_id.to_be_bytes());
158        v.extend_from_slice(&self.functions);
159        v
160    }
161
162    /// Whether the controller implements a function.
163    pub fn supports(&self, f: F) -> bool {
164        let i = usize::from(f.0.wrapping_sub(1));
165        f.0 != 0 && self.functions[i / 8] & (1 << (i % 8)) != 0
166    }
167
168    /// A function mask with these functions set.
169    pub fn mask(functions: &[F]) -> [u8; 32] {
170        let mut m = [0u8; 32];
171        for f in functions {
172            if f.0 != 0 {
173                let i = usize::from(f.0 - 1);
174                m[i / 8] |= 1 << (i % 8);
175            }
176        }
177        m
178    }
179}
180
181/// Response to `GET_INIT_DATA`.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct InitData {
184    /// Serial API version.
185    pub api_version: u8,
186    /// Capability flags.
187    pub capabilities: u8,
188    /// Nodes in the network.
189    pub nodes: Vec<NodeId>,
190    /// Chip type (e.g. 0x07 for 700 series, 0x08 for 800 series).
191    pub chip_type: Option<u8>,
192    /// Chip version.
193    pub chip_version: Option<u8>,
194}
195
196impl InitData {
197    /// The controller runs the end node (slave) API, not a controller API.
198    pub fn is_end_node(&self) -> bool {
199        self.capabilities & 0x01 != 0
200    }
201    /// The controller is a secondary controller.
202    pub fn is_secondary(&self) -> bool {
203        self.capabilities & 0x04 != 0
204    }
205    /// The controller is the static update controller (SIS).
206    pub fn is_sis(&self) -> bool {
207        self.capabilities & 0x08 != 0
208    }
209
210    /// Parses the response payload.
211    pub fn parse(p: &[u8]) -> Result<Self> {
212        need(p, 3, "init data")?;
213        let len = usize::from(p[2]).min(p.len() - 3);
214        let nodes = parse_node_mask(&p[3..3 + len], 1);
215        Ok(InitData {
216            api_version: p[0],
217            capabilities: p[1],
218            nodes,
219            chip_type: p.get(3 + len).copied(),
220            chip_version: p.get(4 + len).copied(),
221        })
222    }
223
224    /// Encodes the payload (simulators).
225    pub fn encode(&self) -> Vec<u8> {
226        let mut v = vec![self.api_version, self.capabilities, 29];
227        v.extend_from_slice(&encode_node_mask(&self.nodes, 29));
228        v.extend(self.chip_type);
229        v.extend(self.chip_version);
230        v
231    }
232}
233
234/// Response to `GET_CONTROLLER_VERSION`.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct ControllerVersion {
237    /// The library version string, e.g. `Z-Wave 7.21`.
238    pub version: String,
239    /// The library type (1 static controller, 7 bridge controller, ...).
240    pub library_type: u8,
241}
242
243impl ControllerVersion {
244    /// Parses the response payload.
245    pub fn parse(p: &[u8]) -> Result<Self> {
246        let nul = p
247            .iter()
248            .position(|&b| b == 0)
249            .ok_or(Malformed("controller version"))?;
250        let version = String::from_utf8_lossy(&p[..nul]).trim().to_string();
251        Ok(ControllerVersion {
252            version,
253            library_type: p.get(nul + 1).copied().unwrap_or(0),
254        })
255    }
256
257    /// Encodes the payload (simulators).
258    pub fn encode(&self) -> Vec<u8> {
259        let mut v = self.version.as_bytes().to_vec();
260        v.push(0);
261        v.push(self.library_type);
262        v
263    }
264
265    /// A readable library type.
266    pub fn library_name(&self) -> &'static str {
267        match self.library_type {
268            0x01 => "static controller",
269            0x02 => "controller",
270            0x03 => "enhanced end node",
271            0x04 => "end node",
272            0x05 => "installer",
273            0x06 => "routing end node",
274            0x07 => "bridge controller",
275            0x08 => "device under test",
276            _ => "unknown",
277        }
278    }
279}
280
281/// Response to `GET_CONTROLLER_ID`.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub struct ControllerId {
284    /// Home id.
285    pub home_id: u32,
286    /// The controller's own node id.
287    pub node_id: NodeId,
288}
289
290impl ControllerId {
291    /// Parses the response payload (`node_id_len` 1 or 2).
292    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
293        need(p, 4 + node_id_len, "controller id")?;
294        Ok(ControllerId {
295            home_id: u32::from_be_bytes([p[0], p[1], p[2], p[3]]),
296            node_id: node_id(p, 4, node_id_len, "controller id")?,
297        })
298    }
299
300    /// Encodes the payload (simulators).
301    pub fn encode(&self, node_id_len: usize) -> Vec<u8> {
302        let mut v = self.home_id.to_be_bytes().to_vec();
303        node_bytes(self.node_id, node_id_len, &mut v);
304        v
305    }
306}
307
308/// Response to `GET_NODE_PROTOCOL_INFO`.
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310pub struct NodeProtocolInfo {
311    /// Always listening (mains powered).
312    pub listening: bool,
313    /// Routing node.
314    pub routing: bool,
315    /// Frequently listening, woken by a beam every 1000 ms.
316    pub flirs_1000: bool,
317    /// Frequently listening, woken by a beam every 250 ms.
318    pub flirs_250: bool,
319    /// The node supports beaming.
320    pub beaming: bool,
321    /// The node is a controller.
322    pub controller: bool,
323    /// The protocol security flag.
324    pub security: bool,
325    /// Protocol version code (bits 0-2 of the capability byte; 3 for current devices).
326    pub protocol_version: u8,
327    /// Supported speeds: bit 0 9.6k, bit 1 40k, bit 2 100k.
328    pub speeds: u8,
329    /// Basic device class.
330    pub basic: u8,
331    /// Generic device class.
332    pub generic: u8,
333    /// Specific device class.
334    pub specific: u8,
335}
336
337impl NodeProtocolInfo {
338    /// Whether the node is reachable at any time (listening or FLiRS).
339    pub fn reachable(&self) -> bool {
340        self.listening || self.flirs_250 || self.flirs_1000
341    }
342
343    /// Parses the response payload. An all-zero response means "no such node".
344    pub fn parse(p: &[u8]) -> Result<Option<Self>> {
345        need(p, 6, "node protocol info")?;
346        if p[3] == 0 && p[4] == 0 {
347            return Ok(None);
348        }
349        let cap = p[0];
350        let sec = p[1];
351        let max_baud = (cap >> 3) & 0x07;
352        let mut speeds = match max_baud {
353            0b010 => 0b011,
354            0b001 => 0b001,
355            _ => 0b001,
356        };
357        if p[2] & 0x01 != 0 {
358            speeds |= 0b100;
359        }
360        Ok(Some(NodeProtocolInfo {
361            listening: cap & 0x80 != 0,
362            routing: cap & 0x40 != 0,
363            flirs_1000: sec & 0x40 != 0,
364            flirs_250: sec & 0x20 != 0,
365            beaming: sec & 0x10 != 0,
366            controller: sec & 0x02 != 0,
367            security: sec & 0x01 != 0,
368            protocol_version: cap & 0x07,
369            speeds,
370            basic: p[3],
371            generic: p[4],
372            specific: p[5],
373        }))
374    }
375
376    /// Encodes the payload (simulators).
377    pub fn encode(&self) -> Vec<u8> {
378        let cap = (if self.listening { 0x80 } else { 0 })
379            | (if self.routing { 0x40 } else { 0 })
380            | (0b010 << 3)
381            | (self.protocol_version & 0x07);
382        let sec = (if self.flirs_1000 { 0x40 } else { 0 })
383            | (if self.flirs_250 { 0x20 } else { 0 })
384            | (if self.beaming { 0x10 } else { 0 })
385            | (if self.controller { 0x02 } else { 0 })
386            | (if self.security { 0x01 } else { 0 })
387            | 0x04;
388        vec![
389            cap,
390            sec,
391            if self.speeds & 0b100 != 0 { 1 } else { 0 },
392            self.basic,
393            self.generic,
394            self.specific,
395        ]
396    }
397}
398
399/// A node information frame: device classes and command classes.
400#[derive(Debug, Clone, PartialEq, Eq, Default)]
401pub struct NodeInfo {
402    /// Basic device class.
403    pub basic: u8,
404    /// Generic device class.
405    pub generic: u8,
406    /// Specific device class.
407    pub specific: u8,
408    /// Supported command classes.
409    pub supported: Vec<u16>,
410    /// Controlled command classes (after the `0xEF` mark).
411    pub controlled: Vec<u16>,
412}
413
414impl NodeInfo {
415    /// Parses `[basic, generic, specific, ccs..]`.
416    pub fn parse(p: &[u8]) -> Result<Self> {
417        need(p, 3, "node info")?;
418        let (supported, controlled) = parse_cc_list(&p[3..]);
419        Ok(NodeInfo {
420            basic: p[0],
421            generic: p[1],
422            specific: p[2],
423            supported,
424            controlled,
425        })
426    }
427
428    /// Encodes `[basic, generic, specific, ccs..]`.
429    pub fn encode(&self) -> Vec<u8> {
430        let mut v = vec![self.basic, self.generic, self.specific];
431        encode_cc_list(&self.supported, &mut v);
432        if !self.controlled.is_empty() {
433            v.push(0xef);
434            encode_cc_list(&self.controlled, &mut v);
435        }
436        v
437    }
438}
439
440/// Reception flags of a received frame.
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
442pub struct RxStatus(pub u8);
443
444impl RxStatus {
445    /// Received at low power.
446    pub fn low_power(self) -> bool {
447        self.0 & 0x02 != 0
448    }
449    /// Sent as broadcast.
450    pub fn broadcast(self) -> bool {
451        self.0 & 0x0c == 0x04
452    }
453    /// Sent as multicast.
454    pub fn multicast(self) -> bool {
455        self.0 & 0x0c == 0x08
456    }
457    /// The frame was routed through repeaters.
458    pub fn routed(self) -> bool {
459        self.0 & 0x01 != 0
460    }
461}
462
463/// A command class frame received from a node (`APPLICATION_COMMAND_HANDLER`
464/// or its bridge variant).
465#[derive(Debug, Clone, PartialEq, Eq)]
466pub struct ApplicationCommand {
467    /// Reception flags.
468    pub rx_status: RxStatus,
469    /// Sending node.
470    pub source: NodeId,
471    /// Destination (the bridge variant can address virtual nodes); `None` for the classic variant.
472    pub destination: Option<NodeId>,
473    /// The command class frame.
474    pub command: Vec<u8>,
475    /// Received signal strength, dBm, when the controller reports it.
476    pub rssi: Option<i8>,
477}
478
479fn rssi(b: Option<&u8>) -> Option<i8> {
480    // 0x7D..0x7F are "not available" / "below sensitivity" / "max power saturated".
481    b.map(|&v| v as i8).filter(|v| *v < 0x7d)
482}
483
484impl ApplicationCommand {
485    /// Parses an `APPLICATION_COMMAND_HANDLER` payload.
486    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
487        need(p, 2 + node_id_len, "application command")?;
488        let source = node_id(p, 1, node_id_len, "application command")?;
489        let at = 1 + node_id_len;
490        let len = usize::from(p[at]);
491        let body = p
492            .get(at + 1..at + 1 + len)
493            .ok_or(Malformed("application command"))?;
494        Ok(ApplicationCommand {
495            rx_status: RxStatus(p[0]),
496            source,
497            destination: None,
498            command: body.to_vec(),
499            rssi: rssi(p.get(at + 1 + len)),
500        })
501    }
502
503    /// Parses a `BRIDGE_APPLICATION_COMMAND_HANDLER` payload.
504    pub fn parse_bridge(p: &[u8], node_id_len: usize) -> Result<Self> {
505        need(p, 2 + 2 * node_id_len, "bridge application command")?;
506        let destination = node_id(p, 1, node_id_len, "bridge application command")?;
507        let source = node_id(
508            p,
509            1 + node_id_len,
510            node_id_len,
511            "bridge application command",
512        )?;
513        let at = 1 + 2 * node_id_len;
514        let len = usize::from(p[at]);
515        let body = p
516            .get(at + 1..at + 1 + len)
517            .ok_or(Malformed("bridge application command"))?;
518        let mut rest = at + 1 + len;
519        // Multicast node mask: length byte and mask.
520        if let Some(&mlen) = p.get(rest) {
521            rest += 1 + usize::from(mlen);
522        }
523        Ok(ApplicationCommand {
524            rx_status: RxStatus(p[0]),
525            source,
526            destination: Some(destination),
527            command: body.to_vec(),
528            rssi: rssi(p.get(rest)),
529        })
530    }
531
532    /// Encodes as an `APPLICATION_COMMAND_HANDLER` request frame (simulators).
533    pub fn to_frame(&self, node_id_len: usize) -> DataFrame {
534        let mut v = vec![self.rx_status.0];
535        node_bytes(self.source, node_id_len, &mut v);
536        v.push(self.command.len() as u8);
537        v.extend_from_slice(&self.command);
538        if let Some(r) = self.rssi {
539            v.push(r as u8);
540        }
541        DataFrame::request(F::APPLICATION_COMMAND_HANDLER, v)
542    }
543}
544
545/// `APPLICATION_UPDATE` frames.
546#[derive(Debug, Clone, PartialEq, Eq)]
547pub enum ApplicationUpdate {
548    /// A node information frame arrived (answer to Request Node Info, or the node sent it).
549    NodeInfoReceived {
550        /// The node.
551        node: NodeId,
552        /// Its node information.
553        info: NodeInfo,
554    },
555    /// Request Node Info failed.
556    NodeInfoRequestFailed,
557    /// A SmartStart node asks to be included.
558    SmartStartHomeIdReceived {
559        /// Its NWI home id (from its DSK).
560        nwi_home_id: [u8; 4],
561        /// Long Range request.
562        long_range: bool,
563        /// Its node information.
564        info: NodeInfo,
565    },
566    /// An already included SmartStart node powered up.
567    SmartStartIncludedNodeInfo {
568        /// Its NWI home id.
569        nwi_home_id: [u8; 4],
570    },
571    /// Another controller added a node.
572    NodeAdded {
573        /// The node.
574        node: NodeId,
575    },
576    /// Another controller removed a node.
577    NodeRemoved {
578        /// The node.
579        node: NodeId,
580    },
581    /// The SUC changed.
582    SucIdChanged,
583    /// Anything else.
584    Other {
585        /// Update type.
586        kind: u8,
587    },
588}
589
590impl ApplicationUpdate {
591    /// Parses an `APPLICATION_UPDATE` payload.
592    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
593        need(p, 1, "application update")?;
594        let kind = p[0];
595        let rest = &p[1..];
596        let node_info = |rest: &[u8]| -> Result<(NodeId, NodeInfo)> {
597            let node = node_id(rest, 0, node_id_len, "node info update")?;
598            let len_at = node_id_len;
599            need(rest, len_at + 1, "node info update")?;
600            let len = usize::from(rest[len_at]);
601            let body = &rest[len_at + 1..rest.len().min(len_at + 1 + len)];
602            Ok((node, NodeInfo::parse(body)?))
603        };
604        Ok(match kind {
605            0x84 => {
606                let (node, info) = node_info(rest)?;
607                ApplicationUpdate::NodeInfoReceived { node, info }
608            }
609            0x81 => ApplicationUpdate::NodeInfoRequestFailed,
610            0x85 | 0x87 => {
611                // [remote node id, rx status, NWI home id (4), length, basic, generic, specific, ccs]
612                let at = node_id_len + 1;
613                need(rest, at + 5, "smartstart request")?;
614                let nwi: [u8; 4] = rest[at..at + 4].try_into().expect("4 bytes");
615                let body = &rest[at + 5..];
616                let info = NodeInfo::parse(body).unwrap_or_default();
617                ApplicationUpdate::SmartStartHomeIdReceived {
618                    nwi_home_id: nwi,
619                    long_range: kind == 0x87,
620                    info,
621                }
622            }
623            0x86 => {
624                let at = node_id_len + 1;
625                need(rest, at + 4, "smartstart node info")?;
626                ApplicationUpdate::SmartStartIncludedNodeInfo {
627                    nwi_home_id: rest[at..at + 4].try_into().expect("4 bytes"),
628                }
629            }
630            0x40 => ApplicationUpdate::NodeAdded {
631                node: node_id(rest, 0, node_id_len, "node added")?,
632            },
633            0x20 => ApplicationUpdate::NodeRemoved {
634                node: node_id(rest, 0, node_id_len, "node removed")?,
635            },
636            0x10 => ApplicationUpdate::SucIdChanged,
637            k => ApplicationUpdate::Other { kind: k },
638        })
639    }
640
641    /// Encodes as a request frame (simulators).
642    pub fn to_frame(&self, node_id_len: usize) -> DataFrame {
643        let zero = |kind: u8| {
644            let mut v = vec![kind];
645            node_bytes(0, node_id_len, &mut v);
646            v
647        };
648        let p = match self {
649            ApplicationUpdate::NodeInfoReceived { node, info } => {
650                let body = info.encode();
651                let mut v = vec![0x84];
652                node_bytes(*node, node_id_len, &mut v);
653                v.push(body.len() as u8);
654                v.extend_from_slice(&body);
655                v
656            }
657            ApplicationUpdate::NodeInfoRequestFailed => {
658                let mut v = zero(0x81);
659                v.push(0);
660                v
661            }
662            ApplicationUpdate::SmartStartHomeIdReceived {
663                nwi_home_id,
664                long_range,
665                info,
666            } => {
667                let body = info.encode();
668                let mut v = zero(if *long_range { 0x87 } else { 0x85 });
669                v.push(0);
670                v.extend_from_slice(nwi_home_id);
671                v.push(body.len().saturating_sub(3) as u8);
672                v.extend_from_slice(&body);
673                v
674            }
675            ApplicationUpdate::SmartStartIncludedNodeInfo { nwi_home_id } => {
676                let mut v = zero(0x86);
677                v.push(0);
678                v.extend_from_slice(nwi_home_id);
679                v
680            }
681            ApplicationUpdate::NodeAdded { node } | ApplicationUpdate::NodeRemoved { node } => {
682                let mut v = vec![if matches!(self, ApplicationUpdate::NodeAdded { .. }) {
683                    0x40
684                } else {
685                    0x20
686                }];
687                node_bytes(*node, node_id_len, &mut v);
688                v.push(0);
689                v
690            }
691            ApplicationUpdate::SucIdChanged => {
692                let mut v = zero(0x10);
693                v.push(0);
694                v
695            }
696            ApplicationUpdate::Other { kind } => {
697                let mut v = zero(*kind);
698                v.push(0);
699                v
700            }
701        };
702        DataFrame::request(F::APPLICATION_UPDATE, p)
703    }
704}
705
706/// How a SendData ended.
707#[derive(Debug, Clone, Copy, PartialEq, Eq)]
708pub enum TransmitStatus {
709    /// Delivered and acknowledged.
710    Ok,
711    /// Sent but not acknowledged (the node is asleep, out of range or gone).
712    NoAck,
713    /// The radio could not transmit (jammed channel).
714    Fail,
715    /// The controller was busy.
716    NotIdle,
717    /// No route to the node.
718    NoRoute,
719    /// Another value.
720    Other(u8),
721}
722
723impl TransmitStatus {
724    /// From the wire byte.
725    pub fn from_u8(v: u8) -> Self {
726        match v {
727            0x00 => TransmitStatus::Ok,
728            0x01 => TransmitStatus::NoAck,
729            0x02 => TransmitStatus::Fail,
730            0x03 => TransmitStatus::NotIdle,
731            0x04 => TransmitStatus::NoRoute,
732            o => TransmitStatus::Other(o),
733        }
734    }
735    /// To the wire byte.
736    pub fn to_u8(self) -> u8 {
737        match self {
738            TransmitStatus::Ok => 0,
739            TransmitStatus::NoAck => 1,
740            TransmitStatus::Fail => 2,
741            TransmitStatus::NotIdle => 3,
742            TransmitStatus::NoRoute => 4,
743            TransmitStatus::Other(o) => o,
744        }
745    }
746}
747
748/// The transmit report the controller appends to a SendData callback once
749/// TX status reporting is enabled: the route the frame took and its signal.
750#[derive(Debug, Clone, PartialEq, Eq, Default)]
751pub struct TxReport {
752    /// Time on air until the ACK, in 10 ms ticks.
753    pub ticks: u16,
754    /// Repeaters used, nearest the controller first.
755    pub repeaters: Vec<NodeId>,
756    /// RSSI of the ACK at the controller, dBm.
757    pub ack_rssi: Option<i8>,
758    /// RSSI of the ACK at each repeater, dBm.
759    pub repeater_rssi: Vec<i8>,
760    /// Channel the ACK came in on.
761    pub ack_channel: Option<u8>,
762    /// Channel the frame went out on.
763    pub tx_channel: u8,
764    /// Route scheme state (which routing attempt succeeded).
765    pub route_scheme: u8,
766    /// Speed: 1 = 9.6k, 2 = 40k, 3 = 100k.
767    pub speed: u8,
768    /// Routing attempts.
769    pub attempts: u8,
770    /// Last working node before a failed link, if any.
771    pub failed_from: Option<NodeId>,
772    /// First node after a failed link, if any.
773    pub failed_to: Option<NodeId>,
774}
775
776impl TxReport {
777    /// Parses the bytes after the transmit status. Returns `None` if the
778    /// controller sent no report.
779    pub fn parse(p: &[u8]) -> Option<Self> {
780        if p.len() < 17 {
781            return None;
782        }
783        let n = usize::from(p[2]).min(4);
784        let repeaters: Vec<NodeId> = p[11..11 + n].iter().map(|&b| NodeId::from(b)).collect();
785        let repeater_rssi = p[4..4 + n]
786            .iter()
787            .map(|&b| b as i8)
788            .filter(|v| *v < 0x7d)
789            .collect();
790        let failed = |i: usize| p.get(i).copied().filter(|&b| b != 0).map(NodeId::from);
791        Some(TxReport {
792            ticks: u16::from_be_bytes([p[0], p[1]]),
793            repeaters,
794            ack_rssi: rssi(p.get(3)),
795            repeater_rssi,
796            ack_channel: Some(p[8]),
797            tx_channel: p[9],
798            route_scheme: p[10],
799            speed: p[15] & 0x07,
800            attempts: p[16],
801            failed_from: failed(17),
802            failed_to: failed(18),
803        })
804    }
805
806    /// Encodes the report bytes (simulators).
807    pub fn encode(&self) -> Vec<u8> {
808        let mut v = self.ticks.to_be_bytes().to_vec();
809        v.push(self.repeaters.len() as u8);
810        v.push(self.ack_rssi.map(|r| r as u8).unwrap_or(0x7f));
811        for i in 0..4 {
812            v.push(self.repeater_rssi.get(i).map(|r| *r as u8).unwrap_or(0x7f));
813        }
814        v.push(self.ack_channel.unwrap_or(0));
815        v.push(self.tx_channel);
816        v.push(self.route_scheme);
817        for i in 0..4 {
818            v.push(self.repeaters.get(i).map(|r| *r as u8).unwrap_or(0));
819        }
820        v.push(self.speed);
821        v.push(self.attempts);
822        v.push(self.failed_from.unwrap_or(0) as u8);
823        v.push(self.failed_to.unwrap_or(0) as u8);
824        v
825    }
826}
827
828/// A SendData callback.
829#[derive(Debug, Clone, PartialEq, Eq)]
830pub struct SendDataResult {
831    /// The transmit status.
832    pub status: TransmitStatus,
833    /// The route and signal report, when enabled.
834    pub report: Option<TxReport>,
835}
836
837impl SendDataResult {
838    /// Parses a SendData callback payload (`[callback id, status, report..]`).
839    pub fn parse(p: &[u8]) -> Result<Self> {
840        need(p, 2, "send data callback")?;
841        Ok(SendDataResult {
842            status: TransmitStatus::from_u8(p[1]),
843            report: TxReport::parse(&p[2..]),
844        })
845    }
846}
847
848/// Transmit options for SendData.
849pub mod tx_options {
850    /// Ask for an acknowledgement.
851    pub const ACK: u8 = 0x01;
852    /// Transmit at low power.
853    pub const LOW_POWER: u8 = 0x02;
854    /// Use routes if direct transmission fails.
855    pub const AUTO_ROUTE: u8 = 0x04;
856    /// Never route.
857    pub const NO_ROUTE: u8 = 0x10;
858    /// Use explorer frames as a last resort.
859    pub const EXPLORE: u8 = 0x20;
860    /// What hosts normally send.
861    pub const DEFAULT: u8 = ACK | AUTO_ROUTE | EXPLORE;
862}
863
864/// Builds a SendData request with node ids of `node_id_len` bytes.
865pub fn send_data(
866    node: NodeId,
867    node_id_len: usize,
868    command: &[u8],
869    options: u8,
870    callback_id: u8,
871) -> DataFrame {
872    let mut v = Vec::with_capacity(command.len() + 5);
873    node_bytes(node, node_id_len, &mut v);
874    v.push(command.len() as u8);
875    v.extend_from_slice(command);
876    v.push(options);
877    v.push(callback_id);
878    DataFrame::request(F::SEND_DATA, v)
879}
880
881/// Inclusion modes for `ADD_NODE_TO_NETWORK`.
882pub mod add_mode {
883    /// Any node.
884    pub const ANY: u8 = 0x01;
885    /// Stop inclusion.
886    pub const STOP: u8 = 0x05;
887    /// Include a SmartStart node by its DSK-derived home ids.
888    pub const SMART_START_DSK: u8 = 0x08;
889    /// Listen for SmartStart inclusion requests.
890    pub const SMART_START_LISTEN: u8 = 0x09;
891    /// Transmit at full power.
892    pub const HIGH_POWER: u8 = 0x80;
893    /// Include over Z-Wave Long Range (SmartStart).
894    pub const PROTOCOL_LONG_RANGE: u8 = 0x20;
895    /// Network-wide inclusion (explorer frames).
896    pub const NETWORK_WIDE: u8 = 0x40;
897}
898
899/// Progress of an inclusion (`ADD_NODE_TO_NETWORK` callbacks).
900#[derive(Debug, Clone, PartialEq, Eq)]
901pub enum AddNodeStatus {
902    /// The controller is in inclusion mode.
903    Ready,
904    /// A node answered.
905    NodeFound,
906    /// An end node is being added; its id and node information.
907    AddingEndNode {
908        /// The node id assigned.
909        node: NodeId,
910        /// Node information.
911        info: NodeInfo,
912    },
913    /// A controller is being added.
914    AddingController {
915        /// The node id assigned.
916        node: NodeId,
917        /// Node information.
918        info: NodeInfo,
919    },
920    /// The protocol part is done; send Stop.
921    ProtocolDone,
922    /// Inclusion finished.
923    Done {
924        /// The node id, if the controller reports it.
925        node: NodeId,
926    },
927    /// Inclusion failed.
928    Failed,
929    /// Another status.
930    Other(u8),
931}
932
933impl AddNodeStatus {
934    /// Parses a callback payload (`[callback id, status, node, len, info..]`).
935    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
936        need(p, 2, "add node status")?;
937        let node = || node_id(p, 2, node_id_len, "add node status");
938        let info = || -> Result<NodeInfo> {
939            let at = 2 + node_id_len;
940            need(p, at + 1, "add node status")?;
941            let len = usize::from(p[at]);
942            NodeInfo::parse(&p[at + 1..p.len().min(at + 1 + len)])
943        };
944        Ok(match p[1] {
945            0x01 => AddNodeStatus::Ready,
946            0x02 => AddNodeStatus::NodeFound,
947            0x03 => AddNodeStatus::AddingEndNode {
948                node: node()?,
949                info: info()?,
950            },
951            0x04 => AddNodeStatus::AddingController {
952                node: node()?,
953                info: info()?,
954            },
955            0x05 => AddNodeStatus::ProtocolDone,
956            0x06 => AddNodeStatus::Done {
957                node: node().unwrap_or(0),
958            },
959            0x07 => AddNodeStatus::Failed,
960            o => AddNodeStatus::Other(o),
961        })
962    }
963
964    /// Encodes as a callback frame (simulators).
965    pub fn to_frame(&self, callback_id: u8, node_id_len: usize) -> DataFrame {
966        let with_info = |status: u8, node: NodeId, info: Option<&NodeInfo>| {
967            let body = info.map(NodeInfo::encode).unwrap_or_default();
968            let mut v = vec![callback_id, status];
969            node_bytes(node, node_id_len, &mut v);
970            v.push(body.len() as u8);
971            v.extend_from_slice(&body);
972            v
973        };
974        let p = match self {
975            AddNodeStatus::Ready => with_info(0x01, 0, None),
976            AddNodeStatus::NodeFound => with_info(0x02, 0, None),
977            AddNodeStatus::AddingEndNode { node, info } => with_info(0x03, *node, Some(info)),
978            AddNodeStatus::AddingController { node, info } => with_info(0x04, *node, Some(info)),
979            AddNodeStatus::ProtocolDone => with_info(0x05, 0, None),
980            AddNodeStatus::Done { node } => with_info(0x06, *node, None),
981            AddNodeStatus::Failed => with_info(0x07, 0, None),
982            AddNodeStatus::Other(o) => with_info(*o, 0, None),
983        };
984        DataFrame::request(F::ADD_NODE_TO_NETWORK, p)
985    }
986}
987
988/// Progress of an exclusion (`REMOVE_NODE_FROM_NETWORK` callbacks).
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
990pub enum RemoveNodeStatus {
991    /// The controller is in exclusion mode.
992    Ready,
993    /// A node answered.
994    NodeFound,
995    /// An end node is being removed.
996    RemovingEndNode {
997        /// Its old node id (0 if it was not in this network).
998        node: NodeId,
999    },
1000    /// A controller is being removed.
1001    RemovingController {
1002        /// Its old node id.
1003        node: NodeId,
1004    },
1005    /// Exclusion finished.
1006    Done {
1007        /// The removed node (0 if it was not in this network).
1008        node: NodeId,
1009    },
1010    /// Exclusion failed.
1011    Failed,
1012    /// Another status.
1013    Other(u8),
1014}
1015
1016impl RemoveNodeStatus {
1017    /// Parses a callback payload.
1018    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
1019        need(p, 2, "remove node status")?;
1020        let node = || node_id(p, 2, node_id_len, "remove node status").unwrap_or(0);
1021        Ok(match p[1] {
1022            0x01 => RemoveNodeStatus::Ready,
1023            0x02 => RemoveNodeStatus::NodeFound,
1024            0x03 => RemoveNodeStatus::RemovingEndNode { node: node() },
1025            0x04 => RemoveNodeStatus::RemovingController { node: node() },
1026            0x06 => RemoveNodeStatus::Done { node: node() },
1027            0x07 => RemoveNodeStatus::Failed,
1028            o => RemoveNodeStatus::Other(o),
1029        })
1030    }
1031
1032    /// Encodes as a callback frame (simulators).
1033    pub fn to_frame(&self, callback_id: u8, node_id_len: usize) -> DataFrame {
1034        let (s, n) = match *self {
1035            RemoveNodeStatus::Ready => (0x01, 0),
1036            RemoveNodeStatus::NodeFound => (0x02, 0),
1037            RemoveNodeStatus::RemovingEndNode { node } => (0x03, node),
1038            RemoveNodeStatus::RemovingController { node } => (0x04, node),
1039            RemoveNodeStatus::Done { node } => (0x06, node),
1040            RemoveNodeStatus::Failed => (0x07, 0),
1041            RemoveNodeStatus::Other(o) => (o, 0),
1042        };
1043        let mut v = vec![callback_id, s];
1044        node_bytes(n, node_id_len, &mut v);
1045        v.push(0);
1046        DataFrame::request(F::REMOVE_NODE_FROM_NETWORK, v)
1047    }
1048}
1049
1050/// Serial API setup subcommands.
1051pub mod setup {
1052    /// Which subcommands the controller supports.
1053    pub const GET_SUPPORTED: u8 = 0x01;
1054    /// Enable or disable transmit reports on SendData callbacks.
1055    pub const SET_TX_STATUS_REPORT: u8 = 0x02;
1056    /// The RF region.
1057    pub const GET_RF_REGION: u8 = 0x20;
1058    /// Set the RF region (needs a soft reset to apply).
1059    pub const SET_RF_REGION: u8 = 0x40;
1060    /// Set 8- or 16-bit node ids on the Serial API.
1061    pub const SET_NODE_ID_TYPE: u8 = 0x80;
1062    /// Node ids are one byte.
1063    pub const NODE_ID_SHORT: u8 = 0x01;
1064    /// Node ids are two bytes (needed for Long Range).
1065    pub const NODE_ID_LONG: u8 = 0x02;
1066}
1067
1068/// An RF region.
1069#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1070pub enum RfRegion {
1071    /// Europe.
1072    Europe,
1073    /// USA.
1074    Usa,
1075    /// Australia and New Zealand.
1076    AustraliaNewZealand,
1077    /// Hong Kong.
1078    HongKong,
1079    /// India.
1080    India,
1081    /// Israel.
1082    Israel,
1083    /// Russia.
1084    Russia,
1085    /// China.
1086    China,
1087    /// USA with Long Range.
1088    UsaLongRange,
1089    /// Europe with Long Range.
1090    EuropeLongRange,
1091    /// Japan.
1092    Japan,
1093    /// Korea.
1094    Korea,
1095    /// Another value.
1096    Other(u8),
1097}
1098
1099impl RfRegion {
1100    /// From the wire byte.
1101    pub fn from_u8(v: u8) -> Self {
1102        match v {
1103            0x00 => RfRegion::Europe,
1104            0x01 => RfRegion::Usa,
1105            0x02 => RfRegion::AustraliaNewZealand,
1106            0x03 => RfRegion::HongKong,
1107            0x05 => RfRegion::India,
1108            0x06 => RfRegion::Israel,
1109            0x07 => RfRegion::Russia,
1110            0x08 => RfRegion::China,
1111            0x09 => RfRegion::UsaLongRange,
1112            0x0b => RfRegion::EuropeLongRange,
1113            0x20 => RfRegion::Japan,
1114            0x21 => RfRegion::Korea,
1115            o => RfRegion::Other(o),
1116        }
1117    }
1118
1119    /// To the wire byte.
1120    pub fn to_u8(self) -> u8 {
1121        match self {
1122            RfRegion::Europe => 0x00,
1123            RfRegion::Usa => 0x01,
1124            RfRegion::AustraliaNewZealand => 0x02,
1125            RfRegion::HongKong => 0x03,
1126            RfRegion::India => 0x05,
1127            RfRegion::Israel => 0x06,
1128            RfRegion::Russia => 0x07,
1129            RfRegion::China => 0x08,
1130            RfRegion::UsaLongRange => 0x09,
1131            RfRegion::EuropeLongRange => 0x0b,
1132            RfRegion::Japan => 0x20,
1133            RfRegion::Korea => 0x21,
1134            RfRegion::Other(o) => o,
1135        }
1136    }
1137}
1138
1139/// Neighbor table of a node (`GET_ROUTING_INFO` response).
1140pub fn parse_routing_info(p: &[u8]) -> Result<Vec<NodeId>> {
1141    need(p, 29, "routing info")?;
1142    Ok(parse_node_mask(&p[..29], 1))
1143}
1144
1145/// Builds a `GET_ROUTING_INFO` request.
1146pub fn get_routing_info(node: NodeId, node_id_len: usize) -> DataFrame {
1147    let mut v = Vec::with_capacity(5);
1148    node_bytes(node, node_id_len, &mut v);
1149    v.extend_from_slice(&[0, 0, 0]);
1150    DataFrame::request(F::GET_ROUTING_INFO, v)
1151}
1152
1153/// Long Range nodes per `GET_LONG_RANGE_NODES` segment (128 bytes of mask).
1154pub const LONG_RANGE_NODES_PER_SEGMENT: u16 = 1024;
1155
1156/// A `GET_LONG_RANGE_NODES` response: more segments follow, the segment, and its nodes.
1157pub fn parse_long_range_nodes(p: &[u8]) -> Result<(bool, u8, Vec<NodeId>)> {
1158    need(p, 3, "long range nodes")?;
1159    let segment = p[1];
1160    let len = usize::from(p[2]).min(p.len() - 3).min(128);
1161    let first = 256 + LONG_RANGE_NODES_PER_SEGMENT * NodeId::from(segment);
1162    Ok((p[0] != 0, segment, parse_node_mask(&p[3..3 + len], first)))
1163}
1164
1165/// Encodes a `GET_LONG_RANGE_NODES` response (simulators).
1166pub fn encode_long_range_nodes(more: bool, segment: u8, nodes: &[NodeId]) -> Vec<u8> {
1167    let first = 256 + LONG_RANGE_NODES_PER_SEGMENT * NodeId::from(segment);
1168    let mut mask = vec![0u8; 128];
1169    for &n in nodes {
1170        if n >= first && n < first + LONG_RANGE_NODES_PER_SEGMENT {
1171            let i = usize::from(n - first);
1172            mask[i / 8] |= 1 << (i % 8);
1173        }
1174    }
1175    let mut v = vec![u8::from(more), segment, 128];
1176    v.extend_from_slice(&mask);
1177    v
1178}
1179
1180/// NVM backup subcommands (`NVM_OPERATIONS`, `EXTENDED_NVM_OPERATIONS`).
1181pub mod nvm {
1182    /// Open the NVM for reading or writing; the response holds its size.
1183    pub const OPEN: u8 = 0x00;
1184    /// Read a chunk.
1185    pub const READ: u8 = 0x01;
1186    /// Write a chunk.
1187    pub const WRITE: u8 = 0x02;
1188    /// Close.
1189    pub const CLOSE: u8 = 0x03;
1190    /// Status: OK.
1191    pub const STATUS_OK: u8 = 0x00;
1192    /// Status: end of file reached (the chunk is the last).
1193    pub const STATUS_EOF: u8 = 0xff;
1194}
1195
1196/// A response to an NVM operation.
1197#[derive(Debug, Clone, PartialEq, Eq)]
1198pub struct NvmResponse {
1199    /// Status.
1200    pub status: u8,
1201    /// For Open: the NVM size. For Read: the offset.
1202    pub offset_or_size: u32,
1203    /// Data read.
1204    pub data: Vec<u8>,
1205}
1206
1207impl NvmResponse {
1208    /// Parses a response; `extended` for 32-bit offsets.
1209    pub fn parse(p: &[u8], extended: bool) -> Result<Self> {
1210        let off_len = if extended { 4 } else { 2 };
1211        need(p, 2, "NVM response")?;
1212        let status = p[0];
1213        let len = usize::from(p[1]);
1214        let offset_or_size = if p.len() >= 2 + off_len {
1215            if extended {
1216                u32::from_be_bytes([p[2], p[3], p[4], p[5]])
1217            } else {
1218                u32::from(u16::from_be_bytes([p[2], p[3]]))
1219            }
1220        } else {
1221            0
1222        };
1223        let start = (2 + off_len).min(p.len());
1224        let data = p[start..p.len().min(start + len)].to_vec();
1225        Ok(NvmResponse {
1226            status,
1227            offset_or_size,
1228            data,
1229        })
1230    }
1231
1232    /// Encodes (simulators).
1233    pub fn encode(&self, extended: bool) -> Vec<u8> {
1234        let mut v = vec![self.status, self.data.len() as u8];
1235        if extended {
1236            v.extend_from_slice(&self.offset_or_size.to_be_bytes());
1237        } else {
1238            v.extend_from_slice(&(self.offset_or_size as u16).to_be_bytes());
1239        }
1240        v.extend_from_slice(&self.data);
1241        v
1242    }
1243}
1244
1245/// Builds an NVM operation request.
1246pub fn nvm_request(extended: bool, op: u8, length: u8, offset: u32) -> DataFrame {
1247    let f = if extended {
1248        F::EXTENDED_NVM_OPERATIONS
1249    } else {
1250        F::NVM_OPERATIONS
1251    };
1252    let mut v = vec![op];
1253    if op == nvm::READ {
1254        v.push(length);
1255        if extended {
1256            v.extend_from_slice(&offset.to_be_bytes());
1257        } else {
1258            v.extend_from_slice(&(offset as u16).to_be_bytes());
1259        }
1260    }
1261    DataFrame::request(f, v)
1262}
1263
1264/// Builds an NVM write of `data` at `offset`.
1265pub fn nvm_write(extended: bool, offset: u32, data: &[u8]) -> DataFrame {
1266    let f = if extended {
1267        F::EXTENDED_NVM_OPERATIONS
1268    } else {
1269        F::NVM_OPERATIONS
1270    };
1271    let mut v = vec![nvm::WRITE, data.len() as u8];
1272    if extended {
1273        v.extend_from_slice(&offset.to_be_bytes());
1274    } else {
1275        v.extend_from_slice(&(offset as u16).to_be_bytes());
1276    }
1277    v.extend_from_slice(data);
1278    DataFrame::request(f, v)
1279}
1280
1281/// Whether a frame is the response to `function`.
1282pub fn is_response(f: &DataFrame, function: crate::FunctionId) -> bool {
1283    f.kind == FrameType::Response && f.function == function.0
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288    use super::*;
1289
1290    #[test]
1291    fn capabilities_mask() {
1292        let c = SerialApiCapabilities {
1293            firmware_major: 7,
1294            firmware_minor: 21,
1295            manufacturer_id: 0,
1296            product_type: 4,
1297            product_id: 1,
1298            functions: SerialApiCapabilities::mask(&[
1299                F::SEND_DATA,
1300                F::GET_ROUTING_INFO,
1301                F::NVM_OPERATIONS,
1302            ]),
1303        };
1304        let back = SerialApiCapabilities::parse(&c.encode()).unwrap();
1305        assert!(back.supports(F::SEND_DATA));
1306        assert!(back.supports(F::GET_ROUTING_INFO));
1307        assert!(!back.supports(F::EXTENDED_NVM_OPERATIONS));
1308        assert_eq!(back, c);
1309    }
1310
1311    #[test]
1312    fn init_data_and_masks() {
1313        let d = InitData {
1314            api_version: 9,
1315            capabilities: 0x08,
1316            nodes: vec![1, 2, 5, 232],
1317            chip_type: Some(8),
1318            chip_version: Some(0),
1319        };
1320        let back = InitData::parse(&d.encode()).unwrap();
1321        assert_eq!(back, d);
1322        assert!(back.is_sis());
1323        assert!(InitData::parse(&[1, 2]).is_err());
1324        // A length byte larger than the payload is clamped.
1325        assert!(InitData::parse(&[1, 2, 200, 0xff]).unwrap().nodes.len() == 8);
1326    }
1327
1328    #[test]
1329    fn cc_list_with_mark_and_extended() {
1330        let (s, c) = parse_cc_list(&[0x5e, 0x25, 0xf1, 0x00, 0xef, 0x20, 0xf2]);
1331        assert_eq!(s, vec![0x5e, 0x25, 0xf100]);
1332        assert_eq!(c, vec![0x20]);
1333    }
1334
1335    #[test]
1336    fn application_command_variants() {
1337        let a = ApplicationCommand {
1338            rx_status: RxStatus(0),
1339            source: 4,
1340            destination: None,
1341            command: vec![0x31, 0x05, 0x01, 0x22, 0x00, 0xe1],
1342            rssi: Some(-60),
1343        };
1344        let f = a.to_frame(1);
1345        assert_eq!(ApplicationCommand::parse(&f.payload, 1).unwrap(), a);
1346        // Length byte beyond the payload.
1347        assert!(ApplicationCommand::parse(&[0, 4, 9, 0x20], 1).is_err());
1348        // Bridge format: rx, dest, src, len, cmd, mask len, rssi.
1349        let b = ApplicationCommand::parse_bridge(&[0, 1, 4, 2, 0x20, 0x02, 0, 0xc4], 1).unwrap();
1350        assert_eq!(b.source, 4);
1351        assert_eq!(b.destination, Some(1));
1352        assert_eq!(b.command, vec![0x20, 0x02]);
1353        assert_eq!(b.rssi, Some(-60));
1354    }
1355
1356    #[test]
1357    fn tx_report_roundtrip() {
1358        let r = TxReport {
1359            ticks: 3,
1360            repeaters: vec![7, 9],
1361            ack_rssi: Some(-71),
1362            repeater_rssi: vec![-50, -60],
1363            ack_channel: Some(1),
1364            tx_channel: 1,
1365            route_scheme: 3,
1366            speed: 3,
1367            attempts: 1,
1368            failed_from: None,
1369            failed_to: None,
1370        };
1371        let mut p = vec![0x01, 0x00];
1372        p.extend_from_slice(&r.encode());
1373        let res = SendDataResult::parse(&p).unwrap();
1374        assert_eq!(res.status, TransmitStatus::Ok);
1375        assert_eq!(res.report.unwrap(), r);
1376        assert_eq!(SendDataResult::parse(&[1, 1]).unwrap().report, None);
1377    }
1378
1379    #[test]
1380    fn add_node_status() {
1381        let info = NodeInfo {
1382            basic: 4,
1383            generic: 0x21,
1384            specific: 1,
1385            supported: vec![0x5e, 0x9f],
1386            controlled: vec![],
1387        };
1388        let s = AddNodeStatus::AddingEndNode { node: 7, info };
1389        assert_eq!(
1390            AddNodeStatus::parse(&s.to_frame(3, 1).payload, 1).unwrap(),
1391            s
1392        );
1393        assert_eq!(
1394            AddNodeStatus::parse(&[3, 6, 7, 0], 1).unwrap(),
1395            AddNodeStatus::Done { node: 7 }
1396        );
1397    }
1398
1399    #[test]
1400    fn application_updates() {
1401        let info = NodeInfo {
1402            basic: 4,
1403            generic: 0x07,
1404            specific: 1,
1405            supported: vec![0x5e, 0x71],
1406            controlled: vec![],
1407        };
1408        let u = ApplicationUpdate::NodeInfoReceived {
1409            node: 3,
1410            info: info.clone(),
1411        };
1412        assert_eq!(
1413            ApplicationUpdate::parse(&u.to_frame(1).payload, 1).unwrap(),
1414            u
1415        );
1416        let s = ApplicationUpdate::SmartStartHomeIdReceived {
1417            nwi_home_id: [0xc1, 2, 3, 4],
1418            long_range: false,
1419            info,
1420        };
1421        assert_eq!(
1422            ApplicationUpdate::parse(&s.to_frame(1).payload, 1).unwrap(),
1423            s
1424        );
1425    }
1426
1427    #[test]
1428    fn protocol_info() {
1429        let i = NodeProtocolInfo {
1430            listening: false,
1431            routing: true,
1432            flirs_1000: false,
1433            flirs_250: false,
1434            beaming: true,
1435            controller: false,
1436            security: true,
1437            protocol_version: 3,
1438            speeds: 0b111,
1439            basic: 4,
1440            generic: 0x21,
1441            specific: 1,
1442        };
1443        assert_eq!(NodeProtocolInfo::parse(&i.encode()).unwrap(), Some(i));
1444        assert_eq!(NodeProtocolInfo::parse(&[0; 6]).unwrap(), None);
1445    }
1446
1447    #[test]
1448    fn nvm_responses() {
1449        let r = NvmResponse {
1450            status: 0,
1451            offset_or_size: 0x1000,
1452            data: vec![],
1453        };
1454        assert_eq!(NvmResponse::parse(&r.encode(false), false).unwrap(), r);
1455        let r = NvmResponse {
1456            status: 0xff,
1457            offset_or_size: 0x20,
1458            data: vec![1, 2, 3],
1459        };
1460        assert_eq!(NvmResponse::parse(&r.encode(true), true).unwrap(), r);
1461    }
1462}