zwave-serial 0.2.1

Z-Wave Serial API host side: frames, ACK/NAK/CAN, retransmits, callbacks, typed controller messages and a controller probe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
//! Typed Serial API messages: request builders and parsers for responses,
//! callbacks and unsolicited frames.
//!
//! Every parser takes the frame payload and returns `Err(Malformed)` rather
//! than panicking on short or inconsistent input; lengths inside a payload
//! are clamped to what the payload actually holds.

use crate::frame::{DataFrame, FrameType};
use crate::function::FunctionId as F;
use crate::NodeId;

/// A payload that does not have the shape its function id promises.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("malformed {0} payload")]
pub struct Malformed(pub &'static str);

type Result<T> = std::result::Result<T, Malformed>;

fn need(p: &[u8], n: usize, what: &'static str) -> Result<()> {
    if p.len() < n {
        Err(Malformed(what))
    } else {
        Ok(())
    }
}

/// Appends a node id as `len` bytes (1 classic, 2 when the Serial API uses 16-bit node ids).
pub fn node_bytes(node: NodeId, len: usize, out: &mut Vec<u8>) {
    if len == 2 {
        out.extend_from_slice(&node.to_be_bytes());
    } else {
        out.push(node as u8);
    }
}

/// The node id at the start of a payload, `len` bytes wide.
pub fn parse_node_id(p: &[u8], len: usize) -> Option<NodeId> {
    node_id(p, 0, len, "node id").ok()
}

/// Reads a node id of `len` bytes (1 classic, 2 Long Range) at `at`.
fn node_id(p: &[u8], at: usize, len: usize, what: &'static str) -> Result<NodeId> {
    need(p, at + len, what)?;
    Ok(if len == 2 {
        u16::from_be_bytes([p[at], p[at + 1]])
    } else {
        u16::from(p[at])
    })
}

/// Parses a command class list, with two-byte ids from `0xF1`, splitting
/// supported from controlled at the `0xEF` mark.
pub fn parse_cc_list(p: &[u8]) -> (Vec<u16>, Vec<u16>) {
    let mut supported = Vec::new();
    let mut controlled = Vec::new();
    let mut after_mark = false;
    let mut i = 0;
    while i < p.len() {
        let b = p[i];
        if b == 0xef {
            after_mark = true;
            i += 1;
            continue;
        }
        let cc = if b >= 0xf1 {
            let Some(&lo) = p.get(i + 1) else { break };
            i += 2;
            (u16::from(b) << 8) | u16::from(lo)
        } else {
            i += 1;
            u16::from(b)
        };
        if after_mark {
            controlled.push(cc);
        } else {
            supported.push(cc);
        }
    }
    (supported, controlled)
}

/// Encodes a command class list (no controlled part).
pub fn encode_cc_list(ccs: &[u16], out: &mut Vec<u8>) {
    for &cc in ccs {
        if cc > 0xff {
            out.extend_from_slice(&cc.to_be_bytes());
        } else {
            out.push(cc as u8);
        }
    }
}

/// Parses a node bit mask (bit 0 of byte 0 is node `first`).
pub fn parse_node_mask(mask: &[u8], first: NodeId) -> Vec<NodeId> {
    let mut v = Vec::new();
    for (i, b) in mask.iter().enumerate() {
        for bit in 0..8 {
            if b & (1 << bit) != 0 {
                v.push(first + (i * 8 + bit) as NodeId);
            }
        }
    }
    v
}

/// Encodes a node bit mask of `len` bytes starting at node 1.
pub fn encode_node_mask(nodes: &[NodeId], len: usize) -> Vec<u8> {
    let mut m = vec![0u8; len];
    for &n in nodes {
        let i = usize::from(n.saturating_sub(1));
        if n >= 1 && i / 8 < len {
            m[i / 8] |= 1 << (i % 8);
        }
    }
    m
}

/// Response to `GET_SERIAL_API_CAPABILITIES`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SerialApiCapabilities {
    /// Firmware (application) version, major.
    pub firmware_major: u8,
    /// Firmware (application) version, minor.
    pub firmware_minor: u8,
    /// Manufacturer id of the stick.
    pub manufacturer_id: u16,
    /// Product type.
    pub product_type: u16,
    /// Product id.
    pub product_id: u16,
    /// Bit mask of supported function ids (bit `n-1` for function `n`).
    pub functions: [u8; 32],
}

impl SerialApiCapabilities {
    /// Parses the response payload.
    pub fn parse(p: &[u8]) -> Result<Self> {
        need(p, 8, "serial API capabilities")?;
        let mut functions = [0u8; 32];
        let mask = &p[8..p.len().min(40)];
        functions[..mask.len()].copy_from_slice(mask);
        Ok(SerialApiCapabilities {
            firmware_major: p[0],
            firmware_minor: p[1],
            manufacturer_id: u16::from_be_bytes([p[2], p[3]]),
            product_type: u16::from_be_bytes([p[4], p[5]]),
            product_id: u16::from_be_bytes([p[6], p[7]]),
            functions,
        })
    }

    /// Encodes the payload (simulators).
    pub fn encode(&self) -> Vec<u8> {
        let mut v = vec![self.firmware_major, self.firmware_minor];
        v.extend_from_slice(&self.manufacturer_id.to_be_bytes());
        v.extend_from_slice(&self.product_type.to_be_bytes());
        v.extend_from_slice(&self.product_id.to_be_bytes());
        v.extend_from_slice(&self.functions);
        v
    }

    /// Whether the controller implements a function.
    pub fn supports(&self, f: F) -> bool {
        let i = usize::from(f.0.wrapping_sub(1));
        f.0 != 0 && self.functions[i / 8] & (1 << (i % 8)) != 0
    }

    /// A function mask with these functions set.
    pub fn mask(functions: &[F]) -> [u8; 32] {
        let mut m = [0u8; 32];
        for f in functions {
            if f.0 != 0 {
                let i = usize::from(f.0 - 1);
                m[i / 8] |= 1 << (i % 8);
            }
        }
        m
    }
}

/// Response to `GET_INIT_DATA`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitData {
    /// Serial API version.
    pub api_version: u8,
    /// Capability flags.
    pub capabilities: u8,
    /// Nodes in the network.
    pub nodes: Vec<NodeId>,
    /// Chip type (e.g. 0x07 for 700 series, 0x08 for 800 series).
    pub chip_type: Option<u8>,
    /// Chip version.
    pub chip_version: Option<u8>,
}

impl InitData {
    /// The controller runs the end node (slave) API, not a controller API.
    pub fn is_end_node(&self) -> bool {
        self.capabilities & 0x01 != 0
    }
    /// The controller is a secondary controller.
    pub fn is_secondary(&self) -> bool {
        self.capabilities & 0x04 != 0
    }
    /// The controller is the static update controller (SIS).
    pub fn is_sis(&self) -> bool {
        self.capabilities & 0x08 != 0
    }

    /// Parses the response payload.
    pub fn parse(p: &[u8]) -> Result<Self> {
        need(p, 3, "init data")?;
        let len = usize::from(p[2]).min(p.len() - 3);
        let nodes = parse_node_mask(&p[3..3 + len], 1);
        Ok(InitData {
            api_version: p[0],
            capabilities: p[1],
            nodes,
            chip_type: p.get(3 + len).copied(),
            chip_version: p.get(4 + len).copied(),
        })
    }

    /// Encodes the payload (simulators).
    pub fn encode(&self) -> Vec<u8> {
        let mut v = vec![self.api_version, self.capabilities, 29];
        v.extend_from_slice(&encode_node_mask(&self.nodes, 29));
        v.extend(self.chip_type);
        v.extend(self.chip_version);
        v
    }
}

/// Response to `GET_CONTROLLER_VERSION`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ControllerVersion {
    /// The library version string, e.g. `Z-Wave 7.21`.
    pub version: String,
    /// The library type (1 static controller, 7 bridge controller, ...).
    pub library_type: u8,
}

impl ControllerVersion {
    /// Parses the response payload.
    pub fn parse(p: &[u8]) -> Result<Self> {
        let nul = p
            .iter()
            .position(|&b| b == 0)
            .ok_or(Malformed("controller version"))?;
        let version = String::from_utf8_lossy(&p[..nul]).trim().to_string();
        Ok(ControllerVersion {
            version,
            library_type: p.get(nul + 1).copied().unwrap_or(0),
        })
    }

    /// Encodes the payload (simulators).
    pub fn encode(&self) -> Vec<u8> {
        let mut v = self.version.as_bytes().to_vec();
        v.push(0);
        v.push(self.library_type);
        v
    }

    /// A readable library type.
    pub fn library_name(&self) -> &'static str {
        match self.library_type {
            0x01 => "static controller",
            0x02 => "controller",
            0x03 => "enhanced end node",
            0x04 => "end node",
            0x05 => "installer",
            0x06 => "routing end node",
            0x07 => "bridge controller",
            0x08 => "device under test",
            _ => "unknown",
        }
    }
}

/// Response to `GET_CONTROLLER_ID`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ControllerId {
    /// Home id.
    pub home_id: u32,
    /// The controller's own node id.
    pub node_id: NodeId,
}

impl ControllerId {
    /// Parses the response payload (`node_id_len` 1 or 2).
    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
        need(p, 4 + node_id_len, "controller id")?;
        Ok(ControllerId {
            home_id: u32::from_be_bytes([p[0], p[1], p[2], p[3]]),
            node_id: node_id(p, 4, node_id_len, "controller id")?,
        })
    }

    /// Encodes the payload (simulators).
    pub fn encode(&self, node_id_len: usize) -> Vec<u8> {
        let mut v = self.home_id.to_be_bytes().to_vec();
        node_bytes(self.node_id, node_id_len, &mut v);
        v
    }
}

/// Response to `GET_NODE_PROTOCOL_INFO`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeProtocolInfo {
    /// Always listening (mains powered).
    pub listening: bool,
    /// Routing node.
    pub routing: bool,
    /// Frequently listening, woken by a beam every 1000 ms.
    pub flirs_1000: bool,
    /// Frequently listening, woken by a beam every 250 ms.
    pub flirs_250: bool,
    /// The node supports beaming.
    pub beaming: bool,
    /// The node is a controller.
    pub controller: bool,
    /// The protocol security flag.
    pub security: bool,
    /// Protocol version code (bits 0-2 of the capability byte; 3 for current devices).
    pub protocol_version: u8,
    /// Supported speeds: bit 0 9.6k, bit 1 40k, bit 2 100k.
    pub speeds: u8,
    /// Basic device class.
    pub basic: u8,
    /// Generic device class.
    pub generic: u8,
    /// Specific device class.
    pub specific: u8,
}

impl NodeProtocolInfo {
    /// Whether the node is reachable at any time (listening or FLiRS).
    pub fn reachable(&self) -> bool {
        self.listening || self.flirs_250 || self.flirs_1000
    }

    /// Parses the response payload. An all-zero response means "no such node".
    pub fn parse(p: &[u8]) -> Result<Option<Self>> {
        need(p, 6, "node protocol info")?;
        if p[3] == 0 && p[4] == 0 {
            return Ok(None);
        }
        let cap = p[0];
        let sec = p[1];
        let max_baud = (cap >> 3) & 0x07;
        let mut speeds = match max_baud {
            0b010 => 0b011,
            0b001 => 0b001,
            _ => 0b001,
        };
        if p[2] & 0x01 != 0 {
            speeds |= 0b100;
        }
        Ok(Some(NodeProtocolInfo {
            listening: cap & 0x80 != 0,
            routing: cap & 0x40 != 0,
            flirs_1000: sec & 0x40 != 0,
            flirs_250: sec & 0x20 != 0,
            beaming: sec & 0x10 != 0,
            controller: sec & 0x02 != 0,
            security: sec & 0x01 != 0,
            protocol_version: cap & 0x07,
            speeds,
            basic: p[3],
            generic: p[4],
            specific: p[5],
        }))
    }

    /// Encodes the payload (simulators).
    pub fn encode(&self) -> Vec<u8> {
        let cap = (if self.listening { 0x80 } else { 0 })
            | (if self.routing { 0x40 } else { 0 })
            | (0b010 << 3)
            | (self.protocol_version & 0x07);
        let sec = (if self.flirs_1000 { 0x40 } else { 0 })
            | (if self.flirs_250 { 0x20 } else { 0 })
            | (if self.beaming { 0x10 } else { 0 })
            | (if self.controller { 0x02 } else { 0 })
            | (if self.security { 0x01 } else { 0 })
            | 0x04;
        vec![
            cap,
            sec,
            if self.speeds & 0b100 != 0 { 1 } else { 0 },
            self.basic,
            self.generic,
            self.specific,
        ]
    }
}

/// A node information frame: device classes and command classes.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct NodeInfo {
    /// Basic device class.
    pub basic: u8,
    /// Generic device class.
    pub generic: u8,
    /// Specific device class.
    pub specific: u8,
    /// Supported command classes.
    pub supported: Vec<u16>,
    /// Controlled command classes (after the `0xEF` mark).
    pub controlled: Vec<u16>,
}

impl NodeInfo {
    /// Parses `[basic, generic, specific, ccs..]`.
    pub fn parse(p: &[u8]) -> Result<Self> {
        need(p, 3, "node info")?;
        let (supported, controlled) = parse_cc_list(&p[3..]);
        Ok(NodeInfo {
            basic: p[0],
            generic: p[1],
            specific: p[2],
            supported,
            controlled,
        })
    }

    /// Encodes `[basic, generic, specific, ccs..]`.
    pub fn encode(&self) -> Vec<u8> {
        let mut v = vec![self.basic, self.generic, self.specific];
        encode_cc_list(&self.supported, &mut v);
        if !self.controlled.is_empty() {
            v.push(0xef);
            encode_cc_list(&self.controlled, &mut v);
        }
        v
    }
}

/// Reception flags of a received frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RxStatus(pub u8);

impl RxStatus {
    /// Received at low power.
    pub fn low_power(self) -> bool {
        self.0 & 0x02 != 0
    }
    /// Sent as broadcast.
    pub fn broadcast(self) -> bool {
        self.0 & 0x0c == 0x04
    }
    /// Sent as multicast.
    pub fn multicast(self) -> bool {
        self.0 & 0x0c == 0x08
    }
    /// The frame was routed through repeaters.
    pub fn routed(self) -> bool {
        self.0 & 0x01 != 0
    }
}

/// A command class frame received from a node (`APPLICATION_COMMAND_HANDLER`
/// or its bridge variant).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApplicationCommand {
    /// Reception flags.
    pub rx_status: RxStatus,
    /// Sending node.
    pub source: NodeId,
    /// Destination (the bridge variant can address virtual nodes); `None` for the classic variant.
    pub destination: Option<NodeId>,
    /// The command class frame.
    pub command: Vec<u8>,
    /// Received signal strength, dBm, when the controller reports it.
    pub rssi: Option<i8>,
}

fn rssi(b: Option<&u8>) -> Option<i8> {
    // 0x7D..0x7F are "not available" / "below sensitivity" / "max power saturated".
    b.map(|&v| v as i8).filter(|v| *v < 0x7d)
}

impl ApplicationCommand {
    /// Parses an `APPLICATION_COMMAND_HANDLER` payload.
    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
        need(p, 2 + node_id_len, "application command")?;
        let source = node_id(p, 1, node_id_len, "application command")?;
        let at = 1 + node_id_len;
        let len = usize::from(p[at]);
        let body = p
            .get(at + 1..at + 1 + len)
            .ok_or(Malformed("application command"))?;
        Ok(ApplicationCommand {
            rx_status: RxStatus(p[0]),
            source,
            destination: None,
            command: body.to_vec(),
            rssi: rssi(p.get(at + 1 + len)),
        })
    }

    /// Parses a `BRIDGE_APPLICATION_COMMAND_HANDLER` payload.
    pub fn parse_bridge(p: &[u8], node_id_len: usize) -> Result<Self> {
        need(p, 2 + 2 * node_id_len, "bridge application command")?;
        let destination = node_id(p, 1, node_id_len, "bridge application command")?;
        let source = node_id(
            p,
            1 + node_id_len,
            node_id_len,
            "bridge application command",
        )?;
        let at = 1 + 2 * node_id_len;
        let len = usize::from(p[at]);
        let body = p
            .get(at + 1..at + 1 + len)
            .ok_or(Malformed("bridge application command"))?;
        let mut rest = at + 1 + len;
        // Multicast node mask: length byte and mask.
        if let Some(&mlen) = p.get(rest) {
            rest += 1 + usize::from(mlen);
        }
        Ok(ApplicationCommand {
            rx_status: RxStatus(p[0]),
            source,
            destination: Some(destination),
            command: body.to_vec(),
            rssi: rssi(p.get(rest)),
        })
    }

    /// Encodes as an `APPLICATION_COMMAND_HANDLER` request frame (simulators).
    pub fn to_frame(&self, node_id_len: usize) -> DataFrame {
        let mut v = vec![self.rx_status.0];
        node_bytes(self.source, node_id_len, &mut v);
        v.push(self.command.len() as u8);
        v.extend_from_slice(&self.command);
        if let Some(r) = self.rssi {
            v.push(r as u8);
        }
        DataFrame::request(F::APPLICATION_COMMAND_HANDLER, v)
    }
}

/// `APPLICATION_UPDATE` frames.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApplicationUpdate {
    /// A node information frame arrived (answer to Request Node Info, or the node sent it).
    NodeInfoReceived {
        /// The node.
        node: NodeId,
        /// Its node information.
        info: NodeInfo,
    },
    /// Request Node Info failed.
    NodeInfoRequestFailed,
    /// A SmartStart node asks to be included.
    SmartStartHomeIdReceived {
        /// Its NWI home id (from its DSK).
        nwi_home_id: [u8; 4],
        /// Long Range request.
        long_range: bool,
        /// Its node information.
        info: NodeInfo,
    },
    /// An already included SmartStart node powered up.
    SmartStartIncludedNodeInfo {
        /// Its NWI home id.
        nwi_home_id: [u8; 4],
    },
    /// Another controller added a node.
    NodeAdded {
        /// The node.
        node: NodeId,
    },
    /// Another controller removed a node.
    NodeRemoved {
        /// The node.
        node: NodeId,
    },
    /// The SUC changed.
    SucIdChanged,
    /// Anything else.
    Other {
        /// Update type.
        kind: u8,
    },
}

impl ApplicationUpdate {
    /// Parses an `APPLICATION_UPDATE` payload.
    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
        need(p, 1, "application update")?;
        let kind = p[0];
        let rest = &p[1..];
        let node_info = |rest: &[u8]| -> Result<(NodeId, NodeInfo)> {
            let node = node_id(rest, 0, node_id_len, "node info update")?;
            let len_at = node_id_len;
            need(rest, len_at + 1, "node info update")?;
            let len = usize::from(rest[len_at]);
            let body = &rest[len_at + 1..rest.len().min(len_at + 1 + len)];
            Ok((node, NodeInfo::parse(body)?))
        };
        Ok(match kind {
            0x84 => {
                let (node, info) = node_info(rest)?;
                ApplicationUpdate::NodeInfoReceived { node, info }
            }
            0x81 => ApplicationUpdate::NodeInfoRequestFailed,
            0x85 | 0x87 => {
                // [remote node id, rx status, NWI home id (4), length, basic, generic, specific, ccs]
                let at = node_id_len + 1;
                need(rest, at + 5, "smartstart request")?;
                let nwi: [u8; 4] = rest[at..at + 4].try_into().expect("4 bytes");
                let body = &rest[at + 5..];
                let info = NodeInfo::parse(body).unwrap_or_default();
                ApplicationUpdate::SmartStartHomeIdReceived {
                    nwi_home_id: nwi,
                    long_range: kind == 0x87,
                    info,
                }
            }
            0x86 => {
                let at = node_id_len + 1;
                need(rest, at + 4, "smartstart node info")?;
                ApplicationUpdate::SmartStartIncludedNodeInfo {
                    nwi_home_id: rest[at..at + 4].try_into().expect("4 bytes"),
                }
            }
            0x40 => ApplicationUpdate::NodeAdded {
                node: node_id(rest, 0, node_id_len, "node added")?,
            },
            0x20 => ApplicationUpdate::NodeRemoved {
                node: node_id(rest, 0, node_id_len, "node removed")?,
            },
            0x10 => ApplicationUpdate::SucIdChanged,
            k => ApplicationUpdate::Other { kind: k },
        })
    }

    /// Encodes as a request frame (simulators).
    pub fn to_frame(&self, node_id_len: usize) -> DataFrame {
        let zero = |kind: u8| {
            let mut v = vec![kind];
            node_bytes(0, node_id_len, &mut v);
            v
        };
        let p = match self {
            ApplicationUpdate::NodeInfoReceived { node, info } => {
                let body = info.encode();
                let mut v = vec![0x84];
                node_bytes(*node, node_id_len, &mut v);
                v.push(body.len() as u8);
                v.extend_from_slice(&body);
                v
            }
            ApplicationUpdate::NodeInfoRequestFailed => {
                let mut v = zero(0x81);
                v.push(0);
                v
            }
            ApplicationUpdate::SmartStartHomeIdReceived {
                nwi_home_id,
                long_range,
                info,
            } => {
                let body = info.encode();
                let mut v = zero(if *long_range { 0x87 } else { 0x85 });
                v.push(0);
                v.extend_from_slice(nwi_home_id);
                v.push(body.len().saturating_sub(3) as u8);
                v.extend_from_slice(&body);
                v
            }
            ApplicationUpdate::SmartStartIncludedNodeInfo { nwi_home_id } => {
                let mut v = zero(0x86);
                v.push(0);
                v.extend_from_slice(nwi_home_id);
                v
            }
            ApplicationUpdate::NodeAdded { node } | ApplicationUpdate::NodeRemoved { node } => {
                let mut v = vec![if matches!(self, ApplicationUpdate::NodeAdded { .. }) {
                    0x40
                } else {
                    0x20
                }];
                node_bytes(*node, node_id_len, &mut v);
                v.push(0);
                v
            }
            ApplicationUpdate::SucIdChanged => {
                let mut v = zero(0x10);
                v.push(0);
                v
            }
            ApplicationUpdate::Other { kind } => {
                let mut v = zero(*kind);
                v.push(0);
                v
            }
        };
        DataFrame::request(F::APPLICATION_UPDATE, p)
    }
}

/// How a SendData ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransmitStatus {
    /// Delivered and acknowledged.
    Ok,
    /// Sent but not acknowledged (the node is asleep, out of range or gone).
    NoAck,
    /// The radio could not transmit (jammed channel).
    Fail,
    /// The controller was busy.
    NotIdle,
    /// No route to the node.
    NoRoute,
    /// Another value.
    Other(u8),
}

impl TransmitStatus {
    /// From the wire byte.
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x00 => TransmitStatus::Ok,
            0x01 => TransmitStatus::NoAck,
            0x02 => TransmitStatus::Fail,
            0x03 => TransmitStatus::NotIdle,
            0x04 => TransmitStatus::NoRoute,
            o => TransmitStatus::Other(o),
        }
    }
    /// To the wire byte.
    pub fn to_u8(self) -> u8 {
        match self {
            TransmitStatus::Ok => 0,
            TransmitStatus::NoAck => 1,
            TransmitStatus::Fail => 2,
            TransmitStatus::NotIdle => 3,
            TransmitStatus::NoRoute => 4,
            TransmitStatus::Other(o) => o,
        }
    }
}

/// The transmit report the controller appends to a SendData callback once
/// TX status reporting is enabled: the route the frame took and its signal.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TxReport {
    /// Time on air until the ACK, in 10 ms ticks.
    pub ticks: u16,
    /// Repeaters used, nearest the controller first.
    pub repeaters: Vec<NodeId>,
    /// RSSI of the ACK at the controller, dBm.
    pub ack_rssi: Option<i8>,
    /// RSSI of the ACK at each repeater, dBm.
    pub repeater_rssi: Vec<i8>,
    /// Channel the ACK came in on.
    pub ack_channel: Option<u8>,
    /// Channel the frame went out on.
    pub tx_channel: u8,
    /// Route scheme state (which routing attempt succeeded).
    pub route_scheme: u8,
    /// Speed: 1 = 9.6k, 2 = 40k, 3 = 100k.
    pub speed: u8,
    /// Routing attempts.
    pub attempts: u8,
    /// Last working node before a failed link, if any.
    pub failed_from: Option<NodeId>,
    /// First node after a failed link, if any.
    pub failed_to: Option<NodeId>,
}

impl TxReport {
    /// Parses the bytes after the transmit status. Returns `None` if the
    /// controller sent no report.
    pub fn parse(p: &[u8]) -> Option<Self> {
        if p.len() < 17 {
            return None;
        }
        let n = usize::from(p[2]).min(4);
        let repeaters: Vec<NodeId> = p[11..11 + n].iter().map(|&b| NodeId::from(b)).collect();
        let repeater_rssi = p[4..4 + n]
            .iter()
            .map(|&b| b as i8)
            .filter(|v| *v < 0x7d)
            .collect();
        let failed = |i: usize| p.get(i).copied().filter(|&b| b != 0).map(NodeId::from);
        Some(TxReport {
            ticks: u16::from_be_bytes([p[0], p[1]]),
            repeaters,
            ack_rssi: rssi(p.get(3)),
            repeater_rssi,
            ack_channel: Some(p[8]),
            tx_channel: p[9],
            route_scheme: p[10],
            speed: p[15] & 0x07,
            attempts: p[16],
            failed_from: failed(17),
            failed_to: failed(18),
        })
    }

    /// Encodes the report bytes (simulators).
    pub fn encode(&self) -> Vec<u8> {
        let mut v = self.ticks.to_be_bytes().to_vec();
        v.push(self.repeaters.len() as u8);
        v.push(self.ack_rssi.map(|r| r as u8).unwrap_or(0x7f));
        for i in 0..4 {
            v.push(self.repeater_rssi.get(i).map(|r| *r as u8).unwrap_or(0x7f));
        }
        v.push(self.ack_channel.unwrap_or(0));
        v.push(self.tx_channel);
        v.push(self.route_scheme);
        for i in 0..4 {
            v.push(self.repeaters.get(i).map(|r| *r as u8).unwrap_or(0));
        }
        v.push(self.speed);
        v.push(self.attempts);
        v.push(self.failed_from.unwrap_or(0) as u8);
        v.push(self.failed_to.unwrap_or(0) as u8);
        v
    }
}

/// A SendData callback.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendDataResult {
    /// The transmit status.
    pub status: TransmitStatus,
    /// The route and signal report, when enabled.
    pub report: Option<TxReport>,
}

impl SendDataResult {
    /// Parses a SendData callback payload (`[callback id, status, report..]`).
    pub fn parse(p: &[u8]) -> Result<Self> {
        need(p, 2, "send data callback")?;
        Ok(SendDataResult {
            status: TransmitStatus::from_u8(p[1]),
            report: TxReport::parse(&p[2..]),
        })
    }
}

/// Transmit options for SendData.
pub mod tx_options {
    /// Ask for an acknowledgement.
    pub const ACK: u8 = 0x01;
    /// Transmit at low power.
    pub const LOW_POWER: u8 = 0x02;
    /// Use routes if direct transmission fails.
    pub const AUTO_ROUTE: u8 = 0x04;
    /// Never route.
    pub const NO_ROUTE: u8 = 0x10;
    /// Use explorer frames as a last resort.
    pub const EXPLORE: u8 = 0x20;
    /// What hosts normally send.
    pub const DEFAULT: u8 = ACK | AUTO_ROUTE | EXPLORE;
}

/// Builds a SendData request with node ids of `node_id_len` bytes.
pub fn send_data(
    node: NodeId,
    node_id_len: usize,
    command: &[u8],
    options: u8,
    callback_id: u8,
) -> DataFrame {
    let mut v = Vec::with_capacity(command.len() + 5);
    node_bytes(node, node_id_len, &mut v);
    v.push(command.len() as u8);
    v.extend_from_slice(command);
    v.push(options);
    v.push(callback_id);
    DataFrame::request(F::SEND_DATA, v)
}

/// Inclusion modes for `ADD_NODE_TO_NETWORK`.
pub mod add_mode {
    /// Any node.
    pub const ANY: u8 = 0x01;
    /// Stop inclusion.
    pub const STOP: u8 = 0x05;
    /// Include a SmartStart node by its DSK-derived home ids.
    pub const SMART_START_DSK: u8 = 0x08;
    /// Listen for SmartStart inclusion requests.
    pub const SMART_START_LISTEN: u8 = 0x09;
    /// Transmit at full power.
    pub const HIGH_POWER: u8 = 0x80;
    /// Include over Z-Wave Long Range (SmartStart).
    pub const PROTOCOL_LONG_RANGE: u8 = 0x20;
    /// Network-wide inclusion (explorer frames).
    pub const NETWORK_WIDE: u8 = 0x40;
}

/// Progress of an inclusion (`ADD_NODE_TO_NETWORK` callbacks).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AddNodeStatus {
    /// The controller is in inclusion mode.
    Ready,
    /// A node answered.
    NodeFound,
    /// An end node is being added; its id and node information.
    AddingEndNode {
        /// The node id assigned.
        node: NodeId,
        /// Node information.
        info: NodeInfo,
    },
    /// A controller is being added.
    AddingController {
        /// The node id assigned.
        node: NodeId,
        /// Node information.
        info: NodeInfo,
    },
    /// The protocol part is done; send Stop.
    ProtocolDone,
    /// Inclusion finished.
    Done {
        /// The node id, if the controller reports it.
        node: NodeId,
    },
    /// Inclusion failed.
    Failed,
    /// Another status.
    Other(u8),
}

impl AddNodeStatus {
    /// Parses a callback payload (`[callback id, status, node, len, info..]`).
    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
        need(p, 2, "add node status")?;
        let node = || node_id(p, 2, node_id_len, "add node status");
        let info = || -> Result<NodeInfo> {
            let at = 2 + node_id_len;
            need(p, at + 1, "add node status")?;
            let len = usize::from(p[at]);
            NodeInfo::parse(&p[at + 1..p.len().min(at + 1 + len)])
        };
        Ok(match p[1] {
            0x01 => AddNodeStatus::Ready,
            0x02 => AddNodeStatus::NodeFound,
            0x03 => AddNodeStatus::AddingEndNode {
                node: node()?,
                info: info()?,
            },
            0x04 => AddNodeStatus::AddingController {
                node: node()?,
                info: info()?,
            },
            0x05 => AddNodeStatus::ProtocolDone,
            0x06 => AddNodeStatus::Done {
                node: node().unwrap_or(0),
            },
            0x07 => AddNodeStatus::Failed,
            o => AddNodeStatus::Other(o),
        })
    }

    /// Encodes as a callback frame (simulators).
    pub fn to_frame(&self, callback_id: u8, node_id_len: usize) -> DataFrame {
        let with_info = |status: u8, node: NodeId, info: Option<&NodeInfo>| {
            let body = info.map(NodeInfo::encode).unwrap_or_default();
            let mut v = vec![callback_id, status];
            node_bytes(node, node_id_len, &mut v);
            v.push(body.len() as u8);
            v.extend_from_slice(&body);
            v
        };
        let p = match self {
            AddNodeStatus::Ready => with_info(0x01, 0, None),
            AddNodeStatus::NodeFound => with_info(0x02, 0, None),
            AddNodeStatus::AddingEndNode { node, info } => with_info(0x03, *node, Some(info)),
            AddNodeStatus::AddingController { node, info } => with_info(0x04, *node, Some(info)),
            AddNodeStatus::ProtocolDone => with_info(0x05, 0, None),
            AddNodeStatus::Done { node } => with_info(0x06, *node, None),
            AddNodeStatus::Failed => with_info(0x07, 0, None),
            AddNodeStatus::Other(o) => with_info(*o, 0, None),
        };
        DataFrame::request(F::ADD_NODE_TO_NETWORK, p)
    }
}

/// Progress of an exclusion (`REMOVE_NODE_FROM_NETWORK` callbacks).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemoveNodeStatus {
    /// The controller is in exclusion mode.
    Ready,
    /// A node answered.
    NodeFound,
    /// An end node is being removed.
    RemovingEndNode {
        /// Its old node id (0 if it was not in this network).
        node: NodeId,
    },
    /// A controller is being removed.
    RemovingController {
        /// Its old node id.
        node: NodeId,
    },
    /// Exclusion finished.
    Done {
        /// The removed node (0 if it was not in this network).
        node: NodeId,
    },
    /// Exclusion failed.
    Failed,
    /// Another status.
    Other(u8),
}

impl RemoveNodeStatus {
    /// Parses a callback payload.
    pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
        need(p, 2, "remove node status")?;
        let node = || node_id(p, 2, node_id_len, "remove node status").unwrap_or(0);
        Ok(match p[1] {
            0x01 => RemoveNodeStatus::Ready,
            0x02 => RemoveNodeStatus::NodeFound,
            0x03 => RemoveNodeStatus::RemovingEndNode { node: node() },
            0x04 => RemoveNodeStatus::RemovingController { node: node() },
            0x06 => RemoveNodeStatus::Done { node: node() },
            0x07 => RemoveNodeStatus::Failed,
            o => RemoveNodeStatus::Other(o),
        })
    }

    /// Encodes as a callback frame (simulators).
    pub fn to_frame(&self, callback_id: u8, node_id_len: usize) -> DataFrame {
        let (s, n) = match *self {
            RemoveNodeStatus::Ready => (0x01, 0),
            RemoveNodeStatus::NodeFound => (0x02, 0),
            RemoveNodeStatus::RemovingEndNode { node } => (0x03, node),
            RemoveNodeStatus::RemovingController { node } => (0x04, node),
            RemoveNodeStatus::Done { node } => (0x06, node),
            RemoveNodeStatus::Failed => (0x07, 0),
            RemoveNodeStatus::Other(o) => (o, 0),
        };
        let mut v = vec![callback_id, s];
        node_bytes(n, node_id_len, &mut v);
        v.push(0);
        DataFrame::request(F::REMOVE_NODE_FROM_NETWORK, v)
    }
}

/// Serial API setup subcommands.
pub mod setup {
    /// Which subcommands the controller supports.
    pub const GET_SUPPORTED: u8 = 0x01;
    /// Enable or disable transmit reports on SendData callbacks.
    pub const SET_TX_STATUS_REPORT: u8 = 0x02;
    /// The RF region.
    pub const GET_RF_REGION: u8 = 0x20;
    /// Set the RF region (needs a soft reset to apply).
    pub const SET_RF_REGION: u8 = 0x40;
    /// Set 8- or 16-bit node ids on the Serial API.
    pub const SET_NODE_ID_TYPE: u8 = 0x80;
    /// Node ids are one byte.
    pub const NODE_ID_SHORT: u8 = 0x01;
    /// Node ids are two bytes (needed for Long Range).
    pub const NODE_ID_LONG: u8 = 0x02;
}

/// An RF region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RfRegion {
    /// Europe.
    Europe,
    /// USA.
    Usa,
    /// Australia and New Zealand.
    AustraliaNewZealand,
    /// Hong Kong.
    HongKong,
    /// India.
    India,
    /// Israel.
    Israel,
    /// Russia.
    Russia,
    /// China.
    China,
    /// USA with Long Range.
    UsaLongRange,
    /// Europe with Long Range.
    EuropeLongRange,
    /// Japan.
    Japan,
    /// Korea.
    Korea,
    /// Another value.
    Other(u8),
}

impl RfRegion {
    /// From the wire byte.
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x00 => RfRegion::Europe,
            0x01 => RfRegion::Usa,
            0x02 => RfRegion::AustraliaNewZealand,
            0x03 => RfRegion::HongKong,
            0x05 => RfRegion::India,
            0x06 => RfRegion::Israel,
            0x07 => RfRegion::Russia,
            0x08 => RfRegion::China,
            0x09 => RfRegion::UsaLongRange,
            0x0b => RfRegion::EuropeLongRange,
            0x20 => RfRegion::Japan,
            0x21 => RfRegion::Korea,
            o => RfRegion::Other(o),
        }
    }

    /// To the wire byte.
    pub fn to_u8(self) -> u8 {
        match self {
            RfRegion::Europe => 0x00,
            RfRegion::Usa => 0x01,
            RfRegion::AustraliaNewZealand => 0x02,
            RfRegion::HongKong => 0x03,
            RfRegion::India => 0x05,
            RfRegion::Israel => 0x06,
            RfRegion::Russia => 0x07,
            RfRegion::China => 0x08,
            RfRegion::UsaLongRange => 0x09,
            RfRegion::EuropeLongRange => 0x0b,
            RfRegion::Japan => 0x20,
            RfRegion::Korea => 0x21,
            RfRegion::Other(o) => o,
        }
    }
}

/// Neighbor table of a node (`GET_ROUTING_INFO` response).
pub fn parse_routing_info(p: &[u8]) -> Result<Vec<NodeId>> {
    need(p, 29, "routing info")?;
    Ok(parse_node_mask(&p[..29], 1))
}

/// Builds a `GET_ROUTING_INFO` request.
pub fn get_routing_info(node: NodeId, node_id_len: usize) -> DataFrame {
    let mut v = Vec::with_capacity(5);
    node_bytes(node, node_id_len, &mut v);
    v.extend_from_slice(&[0, 0, 0]);
    DataFrame::request(F::GET_ROUTING_INFO, v)
}

/// Long Range nodes per `GET_LONG_RANGE_NODES` segment (128 bytes of mask).
pub const LONG_RANGE_NODES_PER_SEGMENT: u16 = 1024;

/// A `GET_LONG_RANGE_NODES` response: more segments follow, the segment, and its nodes.
pub fn parse_long_range_nodes(p: &[u8]) -> Result<(bool, u8, Vec<NodeId>)> {
    need(p, 3, "long range nodes")?;
    let segment = p[1];
    let len = usize::from(p[2]).min(p.len() - 3).min(128);
    let first = 256 + LONG_RANGE_NODES_PER_SEGMENT * NodeId::from(segment);
    Ok((p[0] != 0, segment, parse_node_mask(&p[3..3 + len], first)))
}

/// Encodes a `GET_LONG_RANGE_NODES` response (simulators).
pub fn encode_long_range_nodes(more: bool, segment: u8, nodes: &[NodeId]) -> Vec<u8> {
    let first = 256 + LONG_RANGE_NODES_PER_SEGMENT * NodeId::from(segment);
    let mut mask = vec![0u8; 128];
    for &n in nodes {
        if n >= first && n < first + LONG_RANGE_NODES_PER_SEGMENT {
            let i = usize::from(n - first);
            mask[i / 8] |= 1 << (i % 8);
        }
    }
    let mut v = vec![u8::from(more), segment, 128];
    v.extend_from_slice(&mask);
    v
}

/// NVM backup subcommands (`NVM_OPERATIONS`, `EXTENDED_NVM_OPERATIONS`).
pub mod nvm {
    /// Open the NVM for reading or writing; the response holds its size.
    pub const OPEN: u8 = 0x00;
    /// Read a chunk.
    pub const READ: u8 = 0x01;
    /// Write a chunk.
    pub const WRITE: u8 = 0x02;
    /// Close.
    pub const CLOSE: u8 = 0x03;
    /// Status: OK.
    pub const STATUS_OK: u8 = 0x00;
    /// Status: end of file reached (the chunk is the last).
    pub const STATUS_EOF: u8 = 0xff;
}

/// A response to an NVM operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NvmResponse {
    /// Status.
    pub status: u8,
    /// For Open: the NVM size. For Read: the offset.
    pub offset_or_size: u32,
    /// Data read.
    pub data: Vec<u8>,
}

impl NvmResponse {
    /// Parses a response; `extended` for 32-bit offsets.
    pub fn parse(p: &[u8], extended: bool) -> Result<Self> {
        let off_len = if extended { 4 } else { 2 };
        need(p, 2, "NVM response")?;
        let status = p[0];
        let len = usize::from(p[1]);
        let offset_or_size = if p.len() >= 2 + off_len {
            if extended {
                u32::from_be_bytes([p[2], p[3], p[4], p[5]])
            } else {
                u32::from(u16::from_be_bytes([p[2], p[3]]))
            }
        } else {
            0
        };
        let start = (2 + off_len).min(p.len());
        let data = p[start..p.len().min(start + len)].to_vec();
        Ok(NvmResponse {
            status,
            offset_or_size,
            data,
        })
    }

    /// Encodes (simulators).
    pub fn encode(&self, extended: bool) -> Vec<u8> {
        let mut v = vec![self.status, self.data.len() as u8];
        if extended {
            v.extend_from_slice(&self.offset_or_size.to_be_bytes());
        } else {
            v.extend_from_slice(&(self.offset_or_size as u16).to_be_bytes());
        }
        v.extend_from_slice(&self.data);
        v
    }
}

/// Builds an NVM operation request.
pub fn nvm_request(extended: bool, op: u8, length: u8, offset: u32) -> DataFrame {
    let f = if extended {
        F::EXTENDED_NVM_OPERATIONS
    } else {
        F::NVM_OPERATIONS
    };
    let mut v = vec![op];
    if op == nvm::READ {
        v.push(length);
        if extended {
            v.extend_from_slice(&offset.to_be_bytes());
        } else {
            v.extend_from_slice(&(offset as u16).to_be_bytes());
        }
    }
    DataFrame::request(f, v)
}

/// Builds an NVM write of `data` at `offset`.
pub fn nvm_write(extended: bool, offset: u32, data: &[u8]) -> DataFrame {
    let f = if extended {
        F::EXTENDED_NVM_OPERATIONS
    } else {
        F::NVM_OPERATIONS
    };
    let mut v = vec![nvm::WRITE, data.len() as u8];
    if extended {
        v.extend_from_slice(&offset.to_be_bytes());
    } else {
        v.extend_from_slice(&(offset as u16).to_be_bytes());
    }
    v.extend_from_slice(data);
    DataFrame::request(f, v)
}

/// Whether a frame is the response to `function`.
pub fn is_response(f: &DataFrame, function: crate::FunctionId) -> bool {
    f.kind == FrameType::Response && f.function == function.0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn capabilities_mask() {
        let c = SerialApiCapabilities {
            firmware_major: 7,
            firmware_minor: 21,
            manufacturer_id: 0,
            product_type: 4,
            product_id: 1,
            functions: SerialApiCapabilities::mask(&[
                F::SEND_DATA,
                F::GET_ROUTING_INFO,
                F::NVM_OPERATIONS,
            ]),
        };
        let back = SerialApiCapabilities::parse(&c.encode()).unwrap();
        assert!(back.supports(F::SEND_DATA));
        assert!(back.supports(F::GET_ROUTING_INFO));
        assert!(!back.supports(F::EXTENDED_NVM_OPERATIONS));
        assert_eq!(back, c);
    }

    #[test]
    fn init_data_and_masks() {
        let d = InitData {
            api_version: 9,
            capabilities: 0x08,
            nodes: vec![1, 2, 5, 232],
            chip_type: Some(8),
            chip_version: Some(0),
        };
        let back = InitData::parse(&d.encode()).unwrap();
        assert_eq!(back, d);
        assert!(back.is_sis());
        assert!(InitData::parse(&[1, 2]).is_err());
        // A length byte larger than the payload is clamped.
        assert!(InitData::parse(&[1, 2, 200, 0xff]).unwrap().nodes.len() == 8);
    }

    #[test]
    fn cc_list_with_mark_and_extended() {
        let (s, c) = parse_cc_list(&[0x5e, 0x25, 0xf1, 0x00, 0xef, 0x20, 0xf2]);
        assert_eq!(s, vec![0x5e, 0x25, 0xf100]);
        assert_eq!(c, vec![0x20]);
    }

    #[test]
    fn application_command_variants() {
        let a = ApplicationCommand {
            rx_status: RxStatus(0),
            source: 4,
            destination: None,
            command: vec![0x31, 0x05, 0x01, 0x22, 0x00, 0xe1],
            rssi: Some(-60),
        };
        let f = a.to_frame(1);
        assert_eq!(ApplicationCommand::parse(&f.payload, 1).unwrap(), a);
        // Length byte beyond the payload.
        assert!(ApplicationCommand::parse(&[0, 4, 9, 0x20], 1).is_err());
        // Bridge format: rx, dest, src, len, cmd, mask len, rssi.
        let b = ApplicationCommand::parse_bridge(&[0, 1, 4, 2, 0x20, 0x02, 0, 0xc4], 1).unwrap();
        assert_eq!(b.source, 4);
        assert_eq!(b.destination, Some(1));
        assert_eq!(b.command, vec![0x20, 0x02]);
        assert_eq!(b.rssi, Some(-60));
    }

    #[test]
    fn tx_report_roundtrip() {
        let r = TxReport {
            ticks: 3,
            repeaters: vec![7, 9],
            ack_rssi: Some(-71),
            repeater_rssi: vec![-50, -60],
            ack_channel: Some(1),
            tx_channel: 1,
            route_scheme: 3,
            speed: 3,
            attempts: 1,
            failed_from: None,
            failed_to: None,
        };
        let mut p = vec![0x01, 0x00];
        p.extend_from_slice(&r.encode());
        let res = SendDataResult::parse(&p).unwrap();
        assert_eq!(res.status, TransmitStatus::Ok);
        assert_eq!(res.report.unwrap(), r);
        assert_eq!(SendDataResult::parse(&[1, 1]).unwrap().report, None);
    }

    #[test]
    fn add_node_status() {
        let info = NodeInfo {
            basic: 4,
            generic: 0x21,
            specific: 1,
            supported: vec![0x5e, 0x9f],
            controlled: vec![],
        };
        let s = AddNodeStatus::AddingEndNode { node: 7, info };
        assert_eq!(
            AddNodeStatus::parse(&s.to_frame(3, 1).payload, 1).unwrap(),
            s
        );
        assert_eq!(
            AddNodeStatus::parse(&[3, 6, 7, 0], 1).unwrap(),
            AddNodeStatus::Done { node: 7 }
        );
    }

    #[test]
    fn application_updates() {
        let info = NodeInfo {
            basic: 4,
            generic: 0x07,
            specific: 1,
            supported: vec![0x5e, 0x71],
            controlled: vec![],
        };
        let u = ApplicationUpdate::NodeInfoReceived {
            node: 3,
            info: info.clone(),
        };
        assert_eq!(
            ApplicationUpdate::parse(&u.to_frame(1).payload, 1).unwrap(),
            u
        );
        let s = ApplicationUpdate::SmartStartHomeIdReceived {
            nwi_home_id: [0xc1, 2, 3, 4],
            long_range: false,
            info,
        };
        assert_eq!(
            ApplicationUpdate::parse(&s.to_frame(1).payload, 1).unwrap(),
            s
        );
    }

    #[test]
    fn protocol_info() {
        let i = NodeProtocolInfo {
            listening: false,
            routing: true,
            flirs_1000: false,
            flirs_250: false,
            beaming: true,
            controller: false,
            security: true,
            protocol_version: 3,
            speeds: 0b111,
            basic: 4,
            generic: 0x21,
            specific: 1,
        };
        assert_eq!(NodeProtocolInfo::parse(&i.encode()).unwrap(), Some(i));
        assert_eq!(NodeProtocolInfo::parse(&[0; 6]).unwrap(), None);
    }

    #[test]
    fn nvm_responses() {
        let r = NvmResponse {
            status: 0,
            offset_or_size: 0x1000,
            data: vec![],
        };
        assert_eq!(NvmResponse::parse(&r.encode(false), false).unwrap(), r);
        let r = NvmResponse {
            status: 0xff,
            offset_or_size: 0x20,
            data: vec![1, 2, 3],
        };
        assert_eq!(NvmResponse::parse(&r.encode(true), true).unwrap(), r);
    }
}