zigbee-core 0.1.0

Core Zigbee layers in `no-std` — NWK, APS, security and ZDO; the implementation behind the `zigbee` crate
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
//! Device descriptor configuration and ZDP discovery responses.
//!
//! Holds the node/power/endpoint descriptors this device advertises and builds
//! the matching ZDP `*_rsp` payloads (2.4.4) used to answer the discovery
//! requests a coordinator issues during interview (Node_Desc, Power_Desc,
//! Active_EP, Simple_Desc, Match_Desc, IEEE_addr, NWK_addr).

use byte::BytesExt;
use byte::ctx;
use zigbee_types::IeeeAddress;

use crate::apl::descriptors::node_descriptor::LogicalType;
use crate::apl::descriptors::node_power_descriptor::CurrentPowerMode;
use crate::apl::descriptors::node_power_descriptor::CurrentPowerSourceLevel;
use crate::apl::descriptors::node_power_descriptor::PowerSource;
use crate::nwk::nlme::management::NlmeLeaveStatus;

// ZDP request cluster identifiers (2.4.3).
pub const NWK_ADDR_REQ: u16 = 0x0000;
pub const IEEE_ADDR_REQ: u16 = 0x0001;
pub const NODE_DESC_REQ: u16 = 0x0002;
pub const POWER_DESC_REQ: u16 = 0x0003;
pub const SIMPLE_DESC_REQ: u16 = 0x0004;
pub const ACTIVE_EP_REQ: u16 = 0x0005;
pub const MATCH_DESC_REQ: u16 = 0x0006;
pub const BIND_REQ: u16 = 0x0021;
pub const UNBIND_REQ: u16 = 0x0022;
pub const MGMT_LEAVE_REQ: u16 = 0x0034;

// ZDP response cluster identifiers (2.4.4): request id | 0x8000.
pub const NWK_ADDR_RSP: u16 = 0x8000;
pub const IEEE_ADDR_RSP: u16 = 0x8001;
pub const NODE_DESC_RSP: u16 = 0x8002;
pub const POWER_DESC_RSP: u16 = 0x8003;
pub const SIMPLE_DESC_RSP: u16 = 0x8004;
pub const ACTIVE_EP_RSP: u16 = 0x8005;
pub const MATCH_DESC_RSP: u16 = 0x8006;
pub const BIND_RSP: u16 = 0x8021;
pub const UNBIND_RSP: u16 = 0x8022;
pub const MGMT_LEAVE_RSP: u16 = 0x8034;

// ZDP status codes (2.4.5)
const STATUS_SUCCESS: u8 = 0x00;
const STATUS_INV_REQUESTTYPE: u8 = 0x80;
const STATUS_DEVICE_NOT_FOUND: u8 = 0x81;
const STATUS_INVALID_EP: u8 = 0x82;
const STATUS_NOT_ACTIVE: u8 = 0x83;
const STATUS_NOT_SUPPORTED: u8 = 0x84;
const STATUS_NO_ENTRY: u8 = 0x88;
const STATUS_NOT_PERMITTED: u8 = 0x8b;
const STATUS_TABLE_FULL: u8 = 0x8c;
const STATUS_NOT_AUTHORIZED: u8 = 0x8d;

// Mgmt_Leave_req options (2.4.3.3.5)
const MGMT_LEAVE_REMOVE_CHILDREN: u8 = 0b0100_0000;
const MGMT_LEAVE_REJOIN: u8 = 0b1000_0000;

const NODE_DESCRIPTOR_SIZE: usize = 13;
const POWER_DESCRIPTOR_SIZE: usize = 2;

// a Match_Desc_req profile of 0xffff matches every endpoint (2.4.4.2.7.1.1)
const WILDCARD_PROFILE_ID: u16 = 0xffff;

// append raw bytes at offset, reporting a short buffer instead of panicking
fn append(out: &mut [u8], offset: &mut usize, bytes: &[u8]) -> Result<(), byte::Error> {
    let end = offset
        .checked_add(bytes.len())
        .ok_or(byte::Error::Incomplete)?;
    out.get_mut(*offset..end)
        .ok_or(byte::Error::Incomplete)?
        .copy_from_slice(bytes);
    *offset = end;
    Ok(())
}

/// Static configuration of the node descriptor (2.3.2.3).
///
/// The default describes an end device with no capabilities announced; fill in
/// what the node actually is.
#[derive(Debug, Clone, Copy, Default)]
pub struct NodeDescriptorConfig {
    pub logical_type: LogicalType,
    pub complex_descriptor_available: bool,
    pub user_descriptor_available: bool,
    /// Frequency band field (5 bits, 2.3.2.3.5).
    pub frequency_band: u8,
    /// MAC capability flags (2.3.2.3.6) — bit 3 set means rx-on-when-idle.
    pub mac_capability_flags: u8,
    pub manufacturer_code: u16,
    pub maximum_buffer_size: u8,
    pub maximum_incoming_transfer_size: u16,
    pub server_mask: u16,
    pub maximum_outgoing_transfer_size: u16,
    pub descriptor_capability_field: u8,
}

impl NodeDescriptorConfig {
    // serialize the 13-byte node descriptor (2.3.2.3) in transmission order
    fn write(&self, out: &mut [u8]) -> Result<usize, byte::Error> {
        let offset = &mut 0;
        let logical_type = match self.logical_type {
            LogicalType::Coordinator => 0b000,
            LogicalType::Router => 0b001,
            LogicalType::EndDevice => 0b010,
            LogicalType::Reserved(v) => v,
        };
        let byte0 = (logical_type & 0b111)
            | (u8::from(self.complex_descriptor_available) << 3)
            | (u8::from(self.user_descriptor_available) << 4);
        out.write_with(offset, byte0, ctx::LE)?;
        // APS flags (3 bits, always 0) + frequency band (5 bits)
        out.write_with(offset, (self.frequency_band & 0x1f) << 3, ctx::LE)?;
        out.write_with(offset, self.mac_capability_flags, ctx::LE)?;
        out.write_with(offset, self.manufacturer_code, ctx::LE)?;
        out.write_with(offset, self.maximum_buffer_size, ctx::LE)?;
        out.write_with(offset, self.maximum_incoming_transfer_size, ctx::LE)?;
        out.write_with(offset, self.server_mask, ctx::LE)?;
        out.write_with(offset, self.maximum_outgoing_transfer_size, ctx::LE)?;
        out.write_with(offset, self.descriptor_capability_field, ctx::LE)?;
        Ok(*offset)
    }
}

/// Static configuration of the node power descriptor (2.3.2.4).
#[derive(Debug, Clone, Copy)]
pub struct PowerDescriptorConfig<'a> {
    /// Sleep/power-saving mode (2.3.2.4.1).
    pub current_power_mode: CurrentPowerMode,
    /// The power sources present on the node (2.3.2.4.2).
    pub available_power_sources: &'a [PowerSource],
    /// The source currently in use (2.3.2.4.3).
    pub current_power_source: PowerSource,
    /// Charge level of that source (2.3.2.4.4).
    pub current_power_source_level: CurrentPowerSourceLevel,
}

impl PowerDescriptorConfig<'_> {
    // serialize the 2-byte node power descriptor (2.3.2.4); each octet holds
    // the earlier-transmitted field in its low nibble
    fn write(&self, out: &mut [u8]) -> Result<usize, byte::Error> {
        let offset = &mut 0;
        out.write_with(
            offset,
            self.current_power_mode.bits()
                | (PowerSource::bitmap(self.available_power_sources) << 4),
            ctx::LE,
        )?;
        out.write_with(
            offset,
            self.current_power_source.bits() | (self.current_power_source_level.bits() << 4),
            ctx::LE,
        )?;
        Ok(*offset)
    }
}

/// One application endpoint exposed by this device (2.3.2.5).
#[derive(Debug, Clone, Copy)]
pub struct EndpointDescriptor<'a> {
    pub endpoint: u8,
    pub profile_id: u16,
    pub device_id: u16,
    pub device_version: u8,
    pub input_clusters: &'a [u16],
    pub output_clusters: &'a [u16],
}

impl EndpointDescriptor<'_> {
    // serialize the simple descriptor (2.3.2.5); cluster ids as little-endian
    // u16
    fn write(&self, out: &mut [u8]) -> Result<usize, byte::Error> {
        let offset = &mut 0;
        out.write_with(offset, self.endpoint, ctx::LE)?;
        out.write_with(offset, self.profile_id, ctx::LE)?;
        out.write_with(offset, self.device_id, ctx::LE)?;
        out.write_with(offset, self.device_version & 0x0f, ctx::LE)?;
        out.write_with(
            offset,
            u8::try_from(self.input_clusters.len()).unwrap_or(u8::MAX),
            ctx::LE,
        )?;
        for &cluster in self.input_clusters {
            out.write_with(offset, cluster, ctx::LE)?;
        }
        out.write_with(
            offset,
            u8::try_from(self.output_clusters.len()).unwrap_or(u8::MAX),
            ctx::LE,
        )?;
        for &cluster in self.output_clusters {
            out.write_with(offset, cluster, ctx::LE)?;
        }
        Ok(*offset)
    }
}

/// The descriptors this device advertises to the network.
#[derive(Debug, Clone, Copy)]
pub struct DeviceDescriptorConfig<'a> {
    pub node: NodeDescriptorConfig,
    pub power: PowerDescriptorConfig<'a>,
    pub endpoints: &'a [EndpointDescriptor<'a>],
}

impl DeviceDescriptorConfig<'_> {
    fn endpoint(&self, endpoint: u8) -> Option<&EndpointDescriptor<'_>> {
        self.endpoints.iter().find(|e| e.endpoint == endpoint)
    }

    /// Whether the device implements the given endpoint.
    pub fn supports_endpoint(&self, endpoint: u8) -> bool {
        self.endpoint(endpoint).is_some()
    }

    /// Build a Node_Desc_rsp payload (2.4.4.2.3): seq, status,
    /// NWKAddrOfInterest, node descriptor. Returns bytes written.
    pub fn node_desc_rsp(
        &self,
        seq: u8,
        nwk_addr: u16,
        out: &mut [u8],
    ) -> Result<usize, byte::Error> {
        let offset = &mut 0;
        out.write_with(offset, seq, ctx::LE)?;
        out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
        out.write_with(offset, nwk_addr, ctx::LE)?;
        let mut nd = [0u8; NODE_DESCRIPTOR_SIZE];
        let n = self.node.write(&mut nd)?;
        append(out, offset, &nd[..n])?;
        Ok(*offset)
    }

    /// Build a Power_Desc_rsp payload (2.4.4.2.4): seq, status,
    /// NWKAddrOfInterest, power descriptor.
    pub fn power_desc_rsp(
        &self,
        seq: u8,
        nwk_addr: u16,
        out: &mut [u8],
    ) -> Result<usize, byte::Error> {
        let offset = &mut 0;
        out.write_with(offset, seq, ctx::LE)?;
        out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
        out.write_with(offset, nwk_addr, ctx::LE)?;
        let mut pd = [0u8; POWER_DESCRIPTOR_SIZE];
        let n = self.power.write(&mut pd)?;
        append(out, offset, &pd[..n])?;
        Ok(*offset)
    }

    /// Endpoints matching the request (2.4.4.2.7.1.1), written into `out`.
    ///
    /// Returns how many were written.
    pub fn matching_endpoints(&self, request: &MatchDescReq<'_>, out: &mut [u8]) -> usize {
        let mut count = 0;
        for ep in self.endpoints {
            if request.profile_id != WILDCARD_PROFILE_ID && request.profile_id != ep.profile_id {
                continue;
            }
            let matches = request
                .input_clusters()
                .any(|cluster| ep.input_clusters.contains(&cluster))
                || request
                    .output_clusters()
                    .any(|cluster| ep.output_clusters.contains(&cluster));
            if matches {
                let Some(slot) = out.get_mut(count) else {
                    break;
                };
                *slot = ep.endpoint;
                count += 1;
            }
        }
        count
    }

    /// Build an Active_EP_rsp payload (2.4.4.2.6): seq, status,
    /// NWKAddrOfInterest, endpoint count + list.
    pub fn active_ep_rsp(
        &self,
        seq: u8,
        nwk_addr: u16,
        out: &mut [u8],
    ) -> Result<usize, byte::Error> {
        let offset = &mut 0;
        out.write_with(offset, seq, ctx::LE)?;
        out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
        out.write_with(offset, nwk_addr, ctx::LE)?;
        out.write_with(
            offset,
            u8::try_from(self.endpoints.len()).unwrap_or(u8::MAX),
            ctx::LE,
        )?;
        for ep in self.endpoints {
            out.write_with(offset, ep.endpoint, ctx::LE)?;
        }
        Ok(*offset)
    }

    /// Build a Simple_Desc_rsp payload (2.4.4.2.5): seq, status,
    /// NWKAddrOfInterest, length, simple descriptor. An unknown endpoint yields
    /// status NOT_ACTIVE with length 0.
    pub fn simple_desc_rsp(
        &self,
        seq: u8,
        nwk_addr: u16,
        endpoint: u8,
        out: &mut [u8],
    ) -> Result<usize, byte::Error> {
        let offset = &mut 0;
        out.write_with(offset, seq, ctx::LE)?;

        if let Some(ep) = self.endpoint(endpoint) {
            let mut desc = [0u8; 64];
            let len = ep.write(&mut desc)?;
            out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
            out.write_with(offset, nwk_addr, ctx::LE)?;
            out.write_with(offset, u8::try_from(len).unwrap_or(u8::MAX), ctx::LE)?;
            append(out, offset, &desc[..len])?;
        } else {
            out.write_with(offset, STATUS_NOT_ACTIVE, ctx::LE)?;
            out.write_with(offset, nwk_addr, ctx::LE)?;
            out.write_with(offset, 0u8, ctx::LE)?;
        }
        Ok(*offset)
    }
}

/// Address request type: report only the addressed device (2.4.3.1.1).
pub const ADDR_REQUEST_SINGLE: u8 = 0x00;
/// Address request type: also report the associated devices (2.4.3.1.1).
pub const ADDR_REQUEST_EXTENDED: u8 = 0x01;

/// A parsed NWK_addr_req (2.4.3.1.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NwkAddrReq {
    /// ZDP transaction sequence number to echo in the response.
    pub seq: u8,
    /// The address the responder must match against its own (or a child's).
    pub ieee_addr: IeeeAddress,
    pub request_type: u8,
}

/// Parse a NWK_addr_req payload (2.4.3.1.1): seq, IEEEAddress(8),
/// RequestType(1), StartIndex(1).
pub fn parse_nwk_addr_req(asdu: &[u8]) -> Option<NwkAddrReq> {
    let offset = &mut 0;
    let seq: u8 = asdu.read_with(offset, ctx::LE).ok()?;
    let ieee_addr: u64 = asdu.read_with(offset, ctx::LE).ok()?;
    let request_type: u8 = asdu.read_with(offset, ctx::LE).ok()?;
    Some(NwkAddrReq {
        seq,
        ieee_addr: IeeeAddress(ieee_addr),
        request_type,
    })
}

/// A parsed IEEE_addr_req (2.4.3.1.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IeeeAddrReq {
    /// ZDP transaction sequence number to echo in the response.
    pub seq: u8,
    /// The address the responder must match against its own (or a child's).
    pub nwk_addr_of_interest: u16,
    pub request_type: u8,
}

/// Parse an IEEE_addr_req payload (2.4.3.1.2): seq, NWKAddrOfInterest(2),
/// RequestType(1), StartIndex(1).
pub fn parse_ieee_addr_req(asdu: &[u8]) -> Option<IeeeAddrReq> {
    let offset = &mut 0;
    let seq: u8 = asdu.read_with(offset, ctx::LE).ok()?;
    let nwk_addr_of_interest: u16 = asdu.read_with(offset, ctx::LE).ok()?;
    let request_type: u8 = asdu.read_with(offset, ctx::LE).ok()?;
    Some(IeeeAddrReq {
        seq,
        nwk_addr_of_interest,
        request_type,
    })
}

/// Read the NWKAddrOfInterest a discovery request is about
/// (2.4.3.1.3-2.4.3.1.6).
pub fn parse_addr_of_interest(asdu: &[u8]) -> Option<u16> {
    Some(u16::from_le_bytes(asdu.get(1..3)?.try_into().ok()?))
}

/// Build an IEEE_addr_rsp / NWK_addr_rsp payload (2.4.4.2.1/2.4.4.2.2): seq,
/// status, IEEEAddrRemoteDev, NWKAddrRemoteDev.
///
/// An extended response adds NumAssocDev and StartIndex; this device reports
/// no associated devices, as only a parent keeps that list.
pub fn addr_rsp(
    seq: u8,
    ieee_addr: IeeeAddress,
    nwk_addr: u16,
    extended: bool,
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
    out.write_with(offset, ieee_addr.0, ctx::LE)?;
    out.write_with(offset, nwk_addr, ctx::LE)?;
    if extended {
        // NumAssocDev, StartIndex; the device list is empty
        out.write_with(offset, 0u8, ctx::LE)?;
        out.write_with(offset, 0u8, ctx::LE)?;
    }
    Ok(*offset)
}

/// Build an IEEE_addr_rsp / NWK_addr_rsp reporting an error (2.4.4.2.1): the
/// associated-device fields are omitted, the echoed addresses are not.
pub fn addr_rsp_error(
    seq: u8,
    error: DiscoveryError,
    ieee_addr: IeeeAddress,
    nwk_addr: u16,
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, error.code(), ctx::LE)?;
    out.write_with(offset, ieee_addr.0, ctx::LE)?;
    out.write_with(offset, nwk_addr, ctx::LE)?;
    Ok(*offset)
}

/// Build a Node_Desc_rsp / Power_Desc_rsp reporting an error
/// (2.4.4.2.3/2.4.4.2.4): seq, status, NWKAddrOfInterest; the descriptor is
/// only present on success.
pub fn descriptor_rsp_error(
    seq: u8,
    error: DiscoveryError,
    nwk_addr_of_interest: u16,
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, error.code(), ctx::LE)?;
    out.write_with(offset, nwk_addr_of_interest, ctx::LE)?;
    Ok(*offset)
}

/// Build an Active_EP_rsp reporting an error (2.4.4.2.6), which carries a zero
/// endpoint count in place of the endpoint list.
pub fn active_ep_rsp_error(
    seq: u8,
    error: DiscoveryError,
    nwk_addr_of_interest: u16,
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    // 2.4.4.2.6 keeps ActiveEPCount on the error paths and sets it to 0; only
    // ActiveEPList is omitted
    let offset = &mut descriptor_rsp_error(seq, error, nwk_addr_of_interest, out)?;
    out.write_with(offset, 0u8, ctx::LE)?;
    Ok(*offset)
}

/// Build a Simple_Desc_rsp reporting an error (2.4.4.2.5), which carries a
/// zero descriptor length in place of the descriptor.
pub fn simple_desc_rsp_error(
    seq: u8,
    error: DiscoveryError,
    nwk_addr_of_interest: u16,
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    let offset = &mut descriptor_rsp_error(seq, error, nwk_addr_of_interest, out)?;
    out.write_with(offset, 0u8, ctx::LE)?;
    Ok(*offset)
}

/// Build a Node_Desc_req payload (2.4.3.1.3): seq, NWKAddrOfInterest.
pub fn node_desc_req(
    seq: u8,
    nwk_addr_of_interest: u16,
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, nwk_addr_of_interest, ctx::LE)?;
    Ok(*offset)
}

/// A parsed Node_Desc_rsp (2.4.4.2.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NodeDescRsp {
    /// ZDP transaction sequence number of the request being answered.
    pub seq: u8,
    pub status: u8,
    pub nwk_addr_of_interest: u16,
    /// Server mask of the responding node (2.3.2.3.10), absent unless the
    /// status is SUCCESS.
    pub server_mask: Option<u16>,
}

impl NodeDescRsp {
    /// Stack revision the responder complies with, taken from the upper seven
    /// bits of the server mask (2.3.2.3.10); `None` without a descriptor.
    pub fn stack_revision(&self) -> Option<u8> {
        self.server_mask.map(|mask| (mask >> 9) as u8)
    }
}

/// Parse a Node_Desc_rsp payload (2.4.4.2.3).
pub fn parse_node_desc_rsp(asdu: &[u8]) -> Option<NodeDescRsp> {
    let seq = *asdu.first()?;
    let status = *asdu.get(1)?;
    let nwk_addr_of_interest = u16::from_le_bytes(asdu.get(2..4)?.try_into().ok()?);
    // server mask sits 8 octets into the node descriptor (2.3.2.3)
    let server_mask = asdu
        .get(12..14)
        .and_then(|bytes| bytes.try_into().ok())
        .map(u16::from_le_bytes)
        .filter(|_| status == STATUS_SUCCESS);

    Some(NodeDescRsp {
        seq,
        status,
        nwk_addr_of_interest,
        server_mask,
    })
}

/// A parsed Bind_req / Unbind_req (2.4.3.2.2/2.4.3.2.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BindReq {
    /// ZDP transaction sequence number to echo in the response.
    pub seq: u8,
    /// Device the binding applies to; must be this device.
    pub src_address: IeeeAddress,
    pub src_endpoint: u8,
    pub cluster_id: u16,
    pub destination: BindReqDestination,
}

/// Destination of a Bind_req, by addressing mode (2.4.3.2.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindReqDestination {
    Group(u16),
    Device { ieee: IeeeAddress, endpoint: u8 },
}

/// Parse a Bind_req / Unbind_req payload (2.4.3.2.2): seq, SrcAddress(8),
/// SrcEndp(1), ClusterID(2), DstAddrMode(1), DstAddress(2 or 8), DstEndp(0/1).
pub fn parse_bind_req(asdu: &[u8]) -> Option<BindReq> {
    let offset = &mut 0;
    let seq: u8 = asdu.read_with(offset, ctx::LE).ok()?;
    let src_address: u64 = asdu.read_with(offset, ctx::LE).ok()?;
    let src_endpoint: u8 = asdu.read_with(offset, ctx::LE).ok()?;
    let cluster_id: u16 = asdu.read_with(offset, ctx::LE).ok()?;
    let dst_addr_mode: u8 = asdu.read_with(offset, ctx::LE).ok()?;

    let destination = match dst_addr_mode {
        BIND_ADDR_MODE_GROUP => BindReqDestination::Group(asdu.read_with(offset, ctx::LE).ok()?),
        BIND_ADDR_MODE_DEVICE => BindReqDestination::Device {
            ieee: IeeeAddress(asdu.read_with(offset, ctx::LE).ok()?),
            endpoint: asdu.read_with(offset, ctx::LE).ok()?,
        },
        _ => return None,
    };

    Some(BindReq {
        seq,
        src_address: IeeeAddress(src_address),
        src_endpoint,
        cluster_id,
        destination,
    })
}

/// Bind_req destination addressing mode: 16-bit group address (2.4.3.2.2).
const BIND_ADDR_MODE_GROUP: u8 = 0x01;
/// Bind_req destination addressing mode: 64-bit address plus endpoint.
const BIND_ADDR_MODE_DEVICE: u8 = 0x03;

/// Outcome of a Bind_req / Unbind_req, as reported in the response
/// (2.4.4.3.2/2.4.4.3.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindStatus {
    Success,
    InvalidEndpoint,
    TableFull,
    NoEntry,
    NotSupported,
}

impl BindStatus {
    fn code(self) -> u8 {
        match self {
            Self::Success => STATUS_SUCCESS,
            Self::InvalidEndpoint => STATUS_INVALID_EP,
            Self::TableFull => STATUS_TABLE_FULL,
            Self::NoEntry => STATUS_NO_ENTRY,
            Self::NotSupported => STATUS_NOT_SUPPORTED,
        }
    }
}

/// Build a Bind_rsp / Unbind_rsp payload (2.4.4.3.2/2.4.4.3.3): seq, status.
pub fn bind_rsp(seq: u8, status: BindStatus, out: &mut [u8]) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, status.code(), ctx::LE)?;
    Ok(*offset)
}

/// A parsed Match_Desc_req (2.4.3.1.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MatchDescReq<'a> {
    /// ZDP transaction sequence number to echo in the response.
    pub seq: u8,
    pub nwk_addr_of_interest: u16,
    pub profile_id: u16,
    input_clusters: &'a [u8],
    output_clusters: &'a [u8],
}

impl MatchDescReq<'_> {
    /// Input cluster identifiers to match against.
    pub fn input_clusters(&self) -> impl Iterator<Item = u16> + '_ {
        cluster_ids(self.input_clusters)
    }

    /// Output cluster identifiers to match against.
    pub fn output_clusters(&self) -> impl Iterator<Item = u16> + '_ {
        cluster_ids(self.output_clusters)
    }
}

fn cluster_ids(bytes: &[u8]) -> impl Iterator<Item = u16> + '_ {
    bytes
        .as_chunks::<2>()
        .0
        .iter()
        .copied()
        .map(u16::from_le_bytes)
}

/// Parse a Match_Desc_req payload (2.4.3.1.7).
///
/// Returns `None` if the payload is truncated or a declared cluster count runs
/// past the end of the ASDU.
pub fn parse_match_desc_req(asdu: &[u8]) -> Option<MatchDescReq<'_>> {
    let seq = *asdu.first()?;
    let nwk_addr_of_interest = u16::from_le_bytes(asdu.get(1..3)?.try_into().ok()?);
    let profile_id = u16::from_le_bytes(asdu.get(3..5)?.try_into().ok()?);

    let in_count = usize::from(*asdu.get(5)?);
    let in_end = 6 + in_count * 2;
    let input_clusters = asdu.get(6..in_end)?;

    let out_count = usize::from(*asdu.get(in_end)?);
    let out_start = in_end + 1;
    let output_clusters = asdu.get(out_start..out_start + out_count * 2)?;

    Some(MatchDescReq {
        seq,
        nwk_addr_of_interest,
        profile_id,
        input_clusters,
        output_clusters,
    })
}

/// Build a Match_Desc_rsp payload (2.4.4.2.7): seq, status,
/// NWKAddrOfInterest, MatchLength, MatchList.
pub fn match_desc_rsp(
    seq: u8,
    nwk_addr: u16,
    matches: &[u8],
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, STATUS_SUCCESS, ctx::LE)?;
    out.write_with(offset, nwk_addr, ctx::LE)?;
    out.write_with(
        offset,
        u8::try_from(matches.len()).unwrap_or(u8::MAX),
        ctx::LE,
    )?;
    for &endpoint in matches {
        out.write_with(offset, endpoint, ctx::LE)?;
    }
    Ok(*offset)
}

/// Why a discovery request could not be answered with data (2.4.4.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscoveryError {
    /// The request named another device and this device cannot answer for it
    /// (2.4.4.2.7 step 2.b.i).
    InvalidRequestType,
    /// The request named a device this router knows nothing about (2.4.4.2.7
    /// step 4.b.i).
    DeviceNotFound,
}

impl DiscoveryError {
    fn code(self) -> u8 {
        match self {
            Self::InvalidRequestType => STATUS_INV_REQUESTTYPE,
            Self::DeviceNotFound => STATUS_DEVICE_NOT_FOUND,
        }
    }
}

/// Build a Match_Desc_rsp carrying only Status and MatchLength (2.4.4.2.7).
///
/// NWKAddrOfInterest is omitted on purpose: the error paths of 2.4.4.2.7
/// (steps 2.b.iii, 4.b.ii, 6.b) all specify Status and MatchLength only, and
/// only the success path (step 7.b) carries the address. Dissectors that model
/// the response as a fixed layout report the short frame as malformed.
pub fn match_desc_rsp_error(
    seq: u8,
    error: DiscoveryError,
    out: &mut [u8],
) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, error.code(), ctx::LE)?;
    out.write_with(offset, 0u8, ctx::LE)?;
    Ok(*offset)
}

/// A parsed Mgmt_Leave_req (2.4.3.3.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MgmtLeaveReq {
    /// ZDP transaction sequence number to echo in the response.
    pub seq: u8,
    /// Device to remove; `None` for the NULL address, which targets the
    /// recipient itself.
    pub device_address: Option<IeeeAddress>,
    pub remove_children: bool,
    pub rejoin: bool,
}

/// Parse a Mgmt_Leave_req payload (2.4.3.3.5).
///
/// Returns `None` if the payload is too short.
pub fn parse_mgmt_leave_req(asdu: &[u8]) -> Option<MgmtLeaveReq> {
    let seq = *asdu.first()?;
    let addr_bytes: [u8; 8] = asdu.get(1..9)?.try_into().ok()?;
    let device_address = match u64::from_le_bytes(addr_bytes) {
        0 => None,
        addr => Some(IeeeAddress(addr)),
    };
    let options = *asdu.get(9)?;
    Some(MgmtLeaveReq {
        seq,
        device_address,
        remove_children: options & MGMT_LEAVE_REMOVE_CHILDREN != 0,
        rejoin: options & MGMT_LEAVE_REJOIN != 0,
    })
}

/// Map an NLME-LEAVE.confirm status onto the ZDP status enumeration (2.4.5).
///
/// The Mgmt_Leave_rsp Status field carries NOT_SUPPORTED, NOT_AUTHORIZED or
/// any status code returned by NLME-LEAVE.confirm (2.4.4.4.5).
pub fn leave_status(status: NlmeLeaveStatus) -> u8 {
    match status {
        NlmeLeaveStatus::Success => STATUS_SUCCESS,
        NlmeLeaveStatus::InvalidRequest => STATUS_INV_REQUESTTYPE,
        NlmeLeaveStatus::UnknownDevice => STATUS_DEVICE_NOT_FOUND,
        NlmeLeaveStatus::MacError => STATUS_NOT_PERMITTED,
        NlmeLeaveStatus::NotAuthorized => STATUS_NOT_AUTHORIZED,
    }
}

/// Build a Mgmt_Leave_rsp payload (2.4.4.4.5): seq, status.
pub fn mgmt_leave_rsp(seq: u8, status: u8, out: &mut [u8]) -> Result<usize, byte::Error> {
    let offset = &mut 0;
    out.write_with(offset, seq, ctx::LE)?;
    out.write_with(offset, status, ctx::LE)?;
    Ok(*offset)
}

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

    const NODE: NodeDescriptorConfig = NodeDescriptorConfig {
        logical_type: LogicalType::EndDevice,
        complex_descriptor_available: false,
        user_descriptor_available: false,
        frequency_band: 0x08,
        mac_capability_flags: 0x88,
        manufacturer_code: 0x1037,
        maximum_buffer_size: 80,
        maximum_incoming_transfer_size: 128,
        server_mask: 0,
        maximum_outgoing_transfer_size: 128,
        descriptor_capability_field: 0,
    };

    // mains-powered, on when idle, 100% charge
    const POWER: PowerDescriptorConfig = PowerDescriptorConfig {
        current_power_mode: CurrentPowerMode::Synchronized,
        available_power_sources: &[PowerSource::ConstantMainPower],
        current_power_source: PowerSource::ConstantMainPower,
        current_power_source_level: CurrentPowerSourceLevel::Full,
    };

    const ENDPOINTS: [EndpointDescriptor; 1] = [EndpointDescriptor {
        endpoint: 1,
        profile_id: 0x0104,
        device_id: 0x0302,
        device_version: 1,
        input_clusters: &[0x0000, 0x0402],
        output_clusters: &[0x0019],
    }];

    fn cfg() -> DeviceDescriptorConfig<'static> {
        DeviceDescriptorConfig {
            node: NODE,
            power: POWER,
            endpoints: &ENDPOINTS,
        }
    }

    #[test]
    fn node_desc_rsp_layout() {
        let mut out = [0u8; 32];
        let n = cfg().node_desc_rsp(0x42, 0x1234, &mut out).unwrap();
        assert_eq!(
            &out[..n],
            &[
                0x42, 0x00, 0x34, 0x12, // seq, status, NWKAddrOfInterest
                0x02, 0x40, 0x88, // logical type / freq band / mac flags
                0x37, 0x10, // manufacturer code
                0x50, // max buffer
                0x80, 0x00, // max incoming
                0x00, 0x00, // server mask
                0x80, 0x00, // max outgoing
                0x00, // descriptor capability
            ]
        );
    }

    #[test]
    fn active_ep_rsp_layout() {
        let mut out = [0u8; 16];
        let n = cfg().active_ep_rsp(0x07, 0x1234, &mut out).unwrap();
        assert_eq!(&out[..n], &[0x07, 0x00, 0x34, 0x12, 0x01, 0x01]);
    }

    #[test]
    fn simple_desc_rsp_known_endpoint() {
        let mut out = [0u8; 32];
        let n = cfg().simple_desc_rsp(0x07, 0x1234, 1, &mut out).unwrap();
        assert_eq!(
            &out[..n],
            &[
                0x07, 0x00, 0x34, 0x12, // seq, status, NWKAddrOfInterest
                0x0e, // length
                0x01, // endpoint
                0x04, 0x01, // profile id
                0x02, 0x03, // device id
                0x01, // device version
                0x02, 0x00, 0x00, 0x02, 0x04, // input count + clusters
                0x01, 0x19, 0x00, // output count + clusters
            ]
        );
    }

    #[test]
    fn simple_desc_rsp_unknown_endpoint_not_active() {
        let mut out = [0u8; 16];
        let n = cfg().simple_desc_rsp(0x07, 0x1234, 9, &mut out).unwrap();
        // status NOT_ACTIVE (0x83), length 0, no descriptor
        assert_eq!(&out[..n], &[0x07, 0x83, 0x34, 0x12, 0x00]);
    }

    #[test]
    fn power_desc_rsp_layout() {
        let mut out = [0u8; 16];
        let n = cfg().power_desc_rsp(0x07, 0x1234, &mut out).unwrap();
        assert_eq!(
            &out[..n],
            &[
                0x07, 0x00, 0x34, 0x12, // seq, status, NWKAddrOfInterest
                0x10, // current power mode | available sources << 4
                0xc1, // current source | level << 4
            ]
        );
    }

    // 2.4.3.1.7: seq, NWKAddrOfInterest, ProfileID, then both cluster lists
    const MATCH_REQ: [u8; 13] = [
        0x33, // seq
        0x34, 0x12, // NWKAddrOfInterest
        0x04, 0x01, // profile id 0x0104
        0x02, 0x00, 0x00, 0x02, 0x04, // 2 input clusters: 0x0000, 0x0402
        0x01, 0x19, 0x00, // 1 output cluster: 0x0019
    ];

    #[test]
    fn parse_match_desc_req_lists() {
        let req = parse_match_desc_req(&MATCH_REQ).unwrap();
        assert_eq!(req.seq, 0x33);
        assert_eq!(req.nwk_addr_of_interest, 0x1234);
        assert_eq!(req.profile_id, 0x0104);
        assert!(req.input_clusters().eq([0x0000, 0x0402]));
        assert!(req.output_clusters().eq([0x0019]));
    }

    #[test]
    fn parse_match_desc_req_rejects_truncated_list() {
        // declares two input clusters but carries one and a half
        assert!(parse_match_desc_req(&MATCH_REQ[..8]).is_none());
        // missing the output cluster count entirely
        assert!(parse_match_desc_req(&MATCH_REQ[..10]).is_none());
        assert!(parse_match_desc_req(&[0x33, 0x34]).is_none());
    }

    #[test]
    fn matching_endpoints_by_input_cluster() {
        // temperature measurement is an input cluster on endpoint 1
        let asdu = [0x33, 0x34, 0x12, 0x04, 0x01, 0x01, 0x02, 0x04, 0x00];
        let req = parse_match_desc_req(&asdu).unwrap();
        let mut out = [0u8; 4];
        assert_eq!(cfg().matching_endpoints(&req, &mut out), 1);
        assert_eq!(out[0], 1);
    }

    #[test]
    fn matching_endpoints_by_output_cluster() {
        // OTA (0x0019) is an output cluster on endpoint 1
        let asdu = [0x33, 0x34, 0x12, 0x04, 0x01, 0x00, 0x01, 0x19, 0x00];
        let req = parse_match_desc_req(&asdu).unwrap();
        let mut out = [0u8; 4];
        assert_eq!(cfg().matching_endpoints(&req, &mut out), 1);
    }

    #[test]
    fn matching_endpoints_wildcard_profile() {
        // profile 0xffff matches regardless of the endpoint's profile
        let asdu = [0x33, 0x34, 0x12, 0xff, 0xff, 0x01, 0x02, 0x04, 0x00];
        let req = parse_match_desc_req(&asdu).unwrap();
        let mut out = [0u8; 4];
        assert_eq!(cfg().matching_endpoints(&req, &mut out), 1);
    }

    #[test]
    fn matching_endpoints_rejects_wrong_profile_and_unknown_cluster() {
        // right cluster, wrong profile
        let asdu = [0x33, 0x34, 0x12, 0x09, 0x01, 0x01, 0x02, 0x04, 0x00];
        let req = parse_match_desc_req(&asdu).unwrap();
        let mut out = [0u8; 4];
        assert_eq!(cfg().matching_endpoints(&req, &mut out), 0);

        // right profile, cluster we do not serve
        let asdu = [0x33, 0x34, 0x12, 0x04, 0x01, 0x01, 0x06, 0x00, 0x00];
        let req = parse_match_desc_req(&asdu).unwrap();
        assert_eq!(cfg().matching_endpoints(&req, &mut out), 0);
    }

    #[test]
    fn match_desc_rsp_layout() {
        let mut out = [0u8; 16];
        let n = match_desc_rsp(0x33, 0x1234, &[1], &mut out).unwrap();
        assert_eq!(&out[..n], &[0x33, 0x00, 0x34, 0x12, 0x01, 0x01]);
    }

    #[test]
    fn match_desc_rsp_error_omits_address() {
        let mut out = [0u8; 16];
        let n = match_desc_rsp_error(0x33, DiscoveryError::InvalidRequestType, &mut out).unwrap();
        // seq, INV_REQUESTTYPE, MatchLength — no NWKAddrOfInterest (2.4.4.2.7
        // step 2.b.iii)
        assert_eq!(&out[..n], &[0x33, 0x80, 0x00]);

        let n = match_desc_rsp_error(0x33, DiscoveryError::DeviceNotFound, &mut out).unwrap();
        assert_eq!(&out[..n], &[0x33, 0x81, 0x00]);
    }

    #[test]
    fn descriptor_rsp_reports_short_buffer_instead_of_panicking() {
        // room for seq, status and NWKAddrOfInterest, but not the descriptor
        let mut out = [0u8; 4];
        assert!(cfg().power_desc_rsp(0x07, 0x1234, &mut out).is_err());
        assert!(cfg().node_desc_rsp(0x07, 0x1234, &mut out).is_err());
        assert!(cfg().simple_desc_rsp(0x07, 0x1234, 1, &mut out).is_err());
    }

    #[test]
    fn bind_rsp_carries_status() {
        let mut out = [0u8; 4];
        let n = bind_rsp(0x21, BindStatus::Success, &mut out).unwrap();
        assert_eq!(&out[..n], &[0x21, 0x00]);
        let n = bind_rsp(0x21, BindStatus::InvalidEndpoint, &mut out).unwrap();
        assert_eq!(&out[..n], &[0x21, 0x82]);
        let n = bind_rsp(0x21, BindStatus::TableFull, &mut out).unwrap();
        assert_eq!(&out[..n], &[0x21, 0x8c]);
    }

    #[test]
    fn parse_bind_req_device_and_group_modes() {
        // seq, SrcAddress, SrcEndp, ClusterID, DstAddrMode=0x03, DstAddress,
        // DstEndp
        let device = [
            0x21, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x0a, 0x02, 0x04, 0x03, 0x01,
            0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01,
        ];
        let request = parse_bind_req(&device).unwrap();
        assert_eq!(request.seq, 0x21);
        assert_eq!(request.src_address, IeeeAddress(0x8877_6655_4433_2211));
        assert_eq!(request.src_endpoint, 0x0a);
        assert_eq!(request.cluster_id, 0x0402);
        assert_eq!(
            request.destination,
            BindReqDestination::Device {
                ieee: IeeeAddress(0x0807_0605_0403_0201),
                endpoint: 0x01,
            }
        );

        // DstAddrMode=0x01 carries a group address and no endpoint
        let group = [
            0x22, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x0a, 0x02, 0x04, 0x01, 0x34,
            0x12,
        ];
        let request = parse_bind_req(&group).unwrap();
        assert_eq!(request.destination, BindReqDestination::Group(0x1234));

        // a truncated device-mode request is rejected
        assert!(parse_bind_req(&device[..device.len() - 1]).is_none());
        // as is an unknown addressing mode
        let mut unknown = device;
        unknown[12] = 0x02;
        assert!(parse_bind_req(&unknown).is_none());
    }

    #[test]
    fn addr_rsp_layout() {
        let mut out = [0u8; 16];
        let n = addr_rsp(
            0x07,
            IeeeAddress(0x0011_2233_4455_6677),
            0x1234,
            false,
            &mut out,
        )
        .unwrap();
        assert_eq!(
            &out[..n],
            &[
                0x07, 0x00, // seq, status
                0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, // IEEE addr (LE)
                0x34, 0x12, // NWK addr (LE)
            ]
        );

        // an extended response reports an empty associated-device list
        let n = addr_rsp(
            0x07,
            IeeeAddress(0x0011_2233_4455_6677),
            0x1234,
            true,
            &mut out,
        )
        .unwrap();
        assert_eq!(&out[n - 2..n], &[0x00, 0x00]);
    }

    #[test]
    fn addr_rsp_error_carries_the_echoed_addresses() {
        let mut out = [0u8; 16];
        let n = addr_rsp_error(
            0x07,
            DiscoveryError::DeviceNotFound,
            IeeeAddress(0x0011_2233_4455_6677),
            0x1234,
            &mut out,
        )
        .unwrap();
        assert_eq!(
            &out[..n],
            &[
                0x07, 0x81, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x34, 0x12
            ]
        );
    }

    #[test]
    fn parse_addr_requests() {
        // 2.4.3.1.1: seq, IEEEAddress, RequestType, StartIndex
        let nwk = [
            0x11, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0x01, 0x00,
        ];
        let request = parse_nwk_addr_req(&nwk).unwrap();
        assert_eq!(request.seq, 0x11);
        assert_eq!(request.ieee_addr, IeeeAddress(0x0011_2233_4455_6677));
        assert_eq!(request.request_type, ADDR_REQUEST_EXTENDED);
        assert!(parse_nwk_addr_req(&nwk[..9]).is_none());

        // 2.4.3.1.2: seq, NWKAddrOfInterest, RequestType, StartIndex
        let ieee = [0x12, 0x34, 0x12, 0x00, 0x00];
        let request = parse_ieee_addr_req(&ieee).unwrap();
        assert_eq!(request.seq, 0x12);
        assert_eq!(request.nwk_addr_of_interest, 0x1234);
        assert_eq!(request.request_type, ADDR_REQUEST_SINGLE);
        assert!(parse_ieee_addr_req(&ieee[..3]).is_none());
    }

    #[test]
    fn descriptor_rsp_error_omits_the_descriptor() {
        let mut out = [0u8; 16];
        let n = descriptor_rsp_error(0x07, DiscoveryError::InvalidRequestType, 0x1234, &mut out)
            .unwrap();
        assert_eq!(&out[..n], &[0x07, 0x80, 0x34, 0x12]);

        // the Simple_Desc_rsp carries a zero descriptor length as well
        let n =
            simple_desc_rsp_error(0x07, DiscoveryError::DeviceNotFound, 0x1234, &mut out).unwrap();
        assert_eq!(&out[..n], &[0x07, 0x81, 0x34, 0x12, 0x00]);
    }

    #[test]
    fn parse_node_desc_rsp_reads_the_stack_revision() {
        let mut out = [0u8; 32];
        let mut cfg = cfg();
        // stack revision 22 in the upper seven bits of the server mask
        cfg.node.server_mask = 22 << 9;
        let n = cfg.node_desc_rsp(0x42, 0x1234, &mut out).unwrap();

        let response = parse_node_desc_rsp(&out[..n]).unwrap();
        assert_eq!(response.seq, 0x42);
        assert_eq!(response.status, STATUS_SUCCESS);
        assert_eq!(response.nwk_addr_of_interest, 0x1234);
        assert_eq!(response.stack_revision(), Some(22));

        // an error response carries no descriptor to read a revision from
        let n =
            descriptor_rsp_error(0x42, DiscoveryError::DeviceNotFound, 0x1234, &mut out).unwrap();
        assert_eq!(
            parse_node_desc_rsp(&out[..n]).unwrap().stack_revision(),
            None
        );
    }

    #[test]
    fn parse_mgmt_leave_req_self_null_address() {
        let asdu = [
            0x09, // seq
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,        // NULL device address
            0b1100_0000, // remove children + rejoin
        ];
        let req = parse_mgmt_leave_req(&asdu).unwrap();
        assert_eq!(req.seq, 0x09);
        assert_eq!(req.device_address, None);
        assert!(req.remove_children);
        assert!(req.rejoin);
    }

    #[test]
    fn parse_mgmt_leave_req_targets_device() {
        let asdu = [
            0x0a, // seq
            0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, // IEEE addr (LE)
            0x00, // no flags
        ];
        let req = parse_mgmt_leave_req(&asdu).unwrap();
        assert_eq!(req.seq, 0x0a);
        assert_eq!(req.device_address, Some(IeeeAddress(0x0011_2233_4455_6677)));
        assert!(!req.remove_children);
        assert!(!req.rejoin);
    }

    #[test]
    fn parse_mgmt_leave_req_too_short() {
        assert!(parse_mgmt_leave_req(&[0x01, 0x02]).is_none());
    }

    #[test]
    fn mgmt_leave_rsp_layout() {
        let mut out = [0u8; 4];
        let n = mgmt_leave_rsp(0x09, 0x00, &mut out).unwrap();
        assert_eq!(&out[..n], &[0x09, 0x00]);
    }
}