bacnet-encoding 0.8.1

BACnet ASN.1/BER encoding, APDU and NPDU codecs per ASHRAE 135-2020
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
//! NPDU encoding and decoding per ASHRAE 135-2020 Clause 6.
//!
//! The Network Protocol Data Unit carries either an application-layer APDU
//! or a network-layer message, with optional source/destination routing
//! information for multi-hop BACnet internetworks.

use bacnet_types::enums::NetworkPriority;
use bacnet_types::error::Error;
use bacnet_types::MacAddr;
use bytes::{BufMut, Bytes, BytesMut};

/// BACnet protocol version (always 1).
pub const BACNET_PROTOCOL_VERSION: u8 = 1;

// ---------------------------------------------------------------------------
// Address used in NPDU routing fields
// ---------------------------------------------------------------------------

/// Network-layer address: network number + MAC address.
///
/// Used for source/destination fields in routed NPDUs.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NpduAddress {
    /// Network number (1-65534, or 0xFFFF for global broadcast destination).
    pub network: u16,
    /// MAC-layer address (variable length, empty for broadcast).
    pub mac_address: MacAddr,
}

// ---------------------------------------------------------------------------
// NPDU struct
// ---------------------------------------------------------------------------

/// Decoded Network Protocol Data Unit (Clause 6.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Npdu {
    /// Whether this is a network-layer message (vs application-layer APDU).
    pub is_network_message: bool,
    /// Whether the sender expects a reply.
    pub expecting_reply: bool,
    /// Message priority.
    pub priority: NetworkPriority,
    /// Remote destination address, if routed.
    pub destination: Option<NpduAddress>,
    /// Originating source address (populated by routers).
    pub source: Option<NpduAddress>,
    /// Remaining hop count for routed messages (0-255).
    pub hop_count: u8,
    /// Network message type (when `is_network_message` is true).
    pub message_type: Option<u8>,
    /// Vendor ID for proprietary network messages (message_type >= 0x80).
    pub vendor_id: Option<u16>,
    /// Payload: either APDU bytes or network message data.
    pub payload: Bytes,
}

impl Default for Npdu {
    fn default() -> Self {
        Self {
            is_network_message: false,
            expecting_reply: false,
            priority: NetworkPriority::NORMAL,
            destination: None,
            source: None,
            hop_count: 255,
            message_type: None,
            vendor_id: None,
            payload: Bytes::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Encoding
// ---------------------------------------------------------------------------

/// Encode an NPDU to wire format.
pub fn encode_npdu(buf: &mut BytesMut, npdu: &Npdu) -> Result<(), Error> {
    buf.put_u8(BACNET_PROTOCOL_VERSION);

    let mut control: u8 = npdu.priority.to_raw() & 0x03;
    if npdu.is_network_message {
        control |= 0x80;
    }
    if npdu.destination.is_some() {
        control |= 0x20;
    }
    if npdu.source.is_some() {
        control |= 0x08;
    }
    if npdu.expecting_reply {
        control |= 0x04;
    }
    buf.put_u8(control);

    if let Some(dest) = &npdu.destination {
        if dest.network == 0 {
            return Err(Error::Encoding("NPDU DNET must not be 0".into()));
        }
        buf.put_u16(dest.network);
        if dest.mac_address.len() > 255 {
            return Err(Error::Encoding(
                "NPDU destination MAC address exceeds 255 bytes".into(),
            ));
        }
        buf.put_u8(dest.mac_address.len() as u8);
        buf.put_slice(&dest.mac_address);
    }

    if let Some(src) = &npdu.source {
        if src.network == 0 || src.network == 0xFFFF {
            return Err(Error::Encoding(format!(
                "NPDU SNET must be 1..65534, got {}",
                src.network
            )));
        }
        if src.mac_address.is_empty() {
            return Err(Error::Encoding("NPDU SLEN must not be 0".into()));
        }
        buf.put_u16(src.network);
        if src.mac_address.len() > 255 {
            return Err(Error::Encoding(
                "NPDU source MAC address exceeds 255 bytes".into(),
            ));
        }
        buf.put_u8(src.mac_address.len() as u8);
        buf.put_slice(&src.mac_address);
    }

    if npdu.destination.is_some() {
        buf.put_u8(npdu.hop_count);
    }

    if npdu.is_network_message {
        if let Some(msg_type) = npdu.message_type {
            buf.put_u8(msg_type);
            if msg_type >= 0x80 {
                buf.put_u16(npdu.vendor_id.unwrap_or(0));
            }
        }
    }

    buf.put_slice(&npdu.payload);

    Ok(())
}

// ---------------------------------------------------------------------------
// Decoding
// ---------------------------------------------------------------------------

/// Decode an NPDU from raw bytes.
///
/// Returns the decoded [`Npdu`]. The `payload` field contains either the
/// APDU bytes or network message data.
pub fn decode_npdu(data: Bytes) -> Result<Npdu, Error> {
    if data.len() < 2 {
        return Err(Error::buffer_too_short(2, data.len()));
    }

    let version = data[0];
    if version != BACNET_PROTOCOL_VERSION {
        return Err(Error::decoding(
            0,
            format!("unsupported BACnet protocol version: {version}"),
        ));
    }

    let control = data[1];
    let is_network_message = control & 0x80 != 0;
    let has_destination = control & 0x20 != 0;
    let has_source = control & 0x08 != 0;
    let expecting_reply = control & 0x04 != 0;
    let priority = NetworkPriority::from_raw(control & 0x03);

    if control & 0x50 != 0 {
        tracing::warn!(
            control_byte = control,
            "NPDU control byte has reserved bits set (bits 4 or 6)"
        );
    }

    let mut offset = 2;
    let mut destination = None;
    let mut source = None;
    let mut hop_count: u8 = 255;

    if has_destination {
        if offset + 3 > data.len() {
            return Err(Error::decoding(
                offset,
                "NPDU too short for destination fields",
            ));
        }
        let dnet = u16::from_be_bytes([data[offset], data[offset + 1]]);
        offset += 2;
        let dlen = data[offset] as usize;
        offset += 1;

        if dlen > 0 && offset + dlen > data.len() {
            return Err(Error::decoding(
                offset,
                format!("NPDU destination address truncated: DLEN={dlen}"),
            ));
        }
        let dadr = MacAddr::from_slice(&data[offset..offset + dlen]);
        offset += dlen;

        if dnet == 0 {
            return Err(Error::decoding(
                offset - dlen - 3, // point back to DNET field
                "NPDU destination network 0 is invalid",
            ));
        }

        destination = Some(NpduAddress {
            network: dnet,
            mac_address: dadr,
        });
    }

    if has_source {
        if offset + 3 > data.len() {
            return Err(Error::decoding(offset, "NPDU too short for source fields"));
        }
        let snet = u16::from_be_bytes([data[offset], data[offset + 1]]);
        offset += 2;
        let slen = data[offset] as usize;
        offset += 1;

        if slen == 0 {
            return Err(Error::decoding(offset - 1, "NPDU source SLEN=0 is invalid"));
        }

        if slen > 0 && offset + slen > data.len() {
            return Err(Error::decoding(
                offset,
                format!("NPDU source address truncated: SLEN={slen}"),
            ));
        }
        let sadr = MacAddr::from_slice(&data[offset..offset + slen]);
        offset += slen;

        source = Some(NpduAddress {
            network: snet,
            mac_address: sadr,
        });

        if snet == 0 {
            return Err(Error::decoding(
                offset - slen - 3, // point back to SNET field
                "NPDU source network 0 is invalid",
            ));
        }
        if snet == 0xFFFF {
            return Err(Error::decoding(
                offset - slen - 3,
                "NPDU source network 0xFFFF is invalid",
            ));
        }
    }

    if has_destination {
        if offset >= data.len() {
            return Err(Error::decoding(offset, "NPDU too short for hop count"));
        }
        hop_count = data[offset];
        offset += 1;
    }

    let mut message_type = None;
    let mut vendor_id = None;

    if is_network_message {
        if offset >= data.len() {
            return Err(Error::decoding(
                offset,
                "NPDU too short for network message type",
            ));
        }
        let msg_type = data[offset];
        offset += 1;
        message_type = Some(msg_type);

        if msg_type >= 0x80 {
            if offset + 2 > data.len() {
                return Err(Error::decoding(
                    offset,
                    "NPDU too short for proprietary vendor ID",
                ));
            }
            vendor_id = Some(u16::from_be_bytes([data[offset], data[offset + 1]]));
            offset += 2;
        }
    }

    let payload = data.slice(offset..);

    Ok(Npdu {
        is_network_message,
        expecting_reply,
        priority,
        destination,
        source,
        hop_count,
        message_type,
        vendor_id,
        payload,
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn encode_to_vec(npdu: &Npdu) -> Vec<u8> {
        let mut buf = BytesMut::with_capacity(64);
        encode_npdu(&mut buf, npdu).unwrap();
        buf.to_vec()
    }

    #[test]
    fn minimal_local_apdu() {
        // Simplest case: local, no routing, with APDU payload
        let npdu = Npdu {
            payload: Bytes::from_static(&[0x10, 0x08]), // UnconfirmedRequest WhoIs
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        // version=1, control=0x00 (normal priority, no flags), payload
        assert_eq!(encoded, vec![0x01, 0x00, 0x10, 0x08]);

        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn expecting_reply_flag() {
        let npdu = Npdu {
            expecting_reply: true,
            payload: Bytes::from_static(&[0xAA]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        assert_eq!(encoded[1], 0x04); // control: expecting_reply bit
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert!(decoded.expecting_reply);
    }

    #[test]
    fn priority_encoding() {
        for (prio, expected_bits) in [
            (NetworkPriority::NORMAL, 0x00),
            (NetworkPriority::URGENT, 0x01),
            (NetworkPriority::CRITICAL_EQUIPMENT, 0x02),
            (NetworkPriority::LIFE_SAFETY, 0x03),
        ] {
            let npdu = Npdu {
                priority: prio,
                payload: Bytes::new(),
                ..Default::default()
            };
            let encoded = encode_to_vec(&npdu);
            assert_eq!(encoded[1] & 0x03, expected_bits);
            let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
            assert_eq!(decoded.priority, prio);
        }
    }

    #[test]
    fn destination_only_round_trip() {
        let npdu = Npdu {
            destination: Some(NpduAddress {
                network: 1000,
                mac_address: MacAddr::from_slice(&[0x0A, 0x00, 0x01, 0x01, 0xBA, 0xC0]),
            }),
            hop_count: 254,
            payload: Bytes::from_static(&[0x10, 0x08]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        // control: has_destination = 0x20
        assert_eq!(encoded[1] & 0x20, 0x20);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn destination_broadcast() {
        // Global broadcast: DNET=0xFFFF, DLEN=0 (no DADR)
        let npdu = Npdu {
            destination: Some(NpduAddress {
                network: 0xFFFF,
                mac_address: MacAddr::new(),
            }),
            hop_count: 255,
            payload: Bytes::from_static(&[0x10, 0x08]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        // version(1) + control(1) + DNET(2) + DLEN(1) + hop_count(1) + payload(2)
        assert_eq!(encoded.len(), 8);
        // DNET = 0xFFFF
        assert_eq!(&encoded[2..4], &[0xFF, 0xFF]);
        // DLEN = 0
        assert_eq!(encoded[4], 0);

        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn source_only_round_trip() {
        let npdu = Npdu {
            source: Some(NpduAddress {
                network: 500,
                mac_address: MacAddr::from_slice(&[0x01]),
            }),
            payload: Bytes::from_static(&[0x30, 0x01, 0x0C]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        // control: has_source = 0x08
        assert_eq!(encoded[1] & 0x08, 0x08);
        // No hop count (no destination)
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn source_and_destination_round_trip() {
        let npdu = Npdu {
            expecting_reply: true,
            destination: Some(NpduAddress {
                network: 2000,
                mac_address: MacAddr::from_slice(&[0x0A, 0x00, 0x02, 0x01, 0xBA, 0xC0]),
            }),
            source: Some(NpduAddress {
                network: 1000,
                mac_address: MacAddr::from_slice(&[0x0A, 0x00, 0x01, 0x01, 0xBA, 0xC0]),
            }),
            hop_count: 250,
            payload: Bytes::from_static(&[0x00, 0x05, 0x01, 0x0C]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        // control: destination(0x20) | source(0x08) | expecting_reply(0x04) = 0x2C
        assert_eq!(encoded[1], 0x2C);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn network_message_round_trip() {
        let npdu = Npdu {
            is_network_message: true,
            message_type: Some(0x01), // I-Am-Router-To-Network
            payload: Bytes::from_static(&[0x03, 0xE8]), // network 1000
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        // control: network_message = 0x80
        assert_eq!(encoded[1] & 0x80, 0x80);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn proprietary_network_message_round_trip() {
        let npdu = Npdu {
            is_network_message: true,
            message_type: Some(0x80), // Proprietary range
            vendor_id: Some(999),
            payload: Bytes::from_static(&[0xDE, 0xAD]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn wire_format_who_is_broadcast() {
        // Real-world WhoIs global broadcast:
        // Version=1, Control=0x20 (dest present), DNET=0xFFFF, DLEN=0,
        // HopCount=255, APDU=[0x10, 0x08]
        let wire = [0x01, 0x20, 0xFF, 0xFF, 0x00, 0xFF, 0x10, 0x08];
        let decoded = decode_npdu(Bytes::copy_from_slice(&wire)).unwrap();
        assert!(!decoded.is_network_message);
        assert!(!decoded.expecting_reply);
        assert_eq!(decoded.priority, NetworkPriority::NORMAL);
        assert_eq!(
            decoded.destination,
            Some(NpduAddress {
                network: 0xFFFF,
                mac_address: MacAddr::new(),
            })
        );
        assert!(decoded.source.is_none());
        assert_eq!(decoded.hop_count, 255);
        assert_eq!(decoded.payload, vec![0x10, 0x08]);

        // Re-encode should match
        let reencoded = encode_to_vec(&decoded);
        assert_eq!(reencoded, wire);
    }

    #[test]
    fn decode_too_short() {
        assert!(decode_npdu(Bytes::new()).is_err());
        assert!(decode_npdu(Bytes::from_static(&[0x01])).is_err());
    }

    #[test]
    fn decode_wrong_version() {
        assert!(decode_npdu(Bytes::from_static(&[0x02, 0x00])).is_err());
    }

    #[test]
    fn decode_truncated_destination() {
        // Has destination flag but not enough bytes
        assert!(decode_npdu(Bytes::from_static(&[0x01, 0x20, 0xFF])).is_err());
    }

    #[test]
    fn decode_truncated_source() {
        // Has source flag but not enough bytes after destination
        assert!(decode_npdu(Bytes::from_static(&[0x01, 0x08, 0x00])).is_err());
    }

    // --- NPDU edge case tests ---

    #[test]
    fn npdu_network_zero() {
        // DNET=0 is invalid per Clause 6.2.2 — rejected at encode time
        let npdu = Npdu {
            destination: Some(NpduAddress {
                network: 0,
                mac_address: MacAddr::from_slice(&[0x01]),
            }),
            hop_count: 255,
            payload: Bytes::from_static(&[0x10, 0x08]),
            ..Default::default()
        };
        let mut buf = BytesMut::new();
        let result = encode_npdu(&mut buf, &npdu);
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("DNET"), "got: {err}");
    }

    #[test]
    fn npdu_network_fffe() {
        // 0xFFFE is the max non-broadcast network number
        // (0xFFFF is broadcast, 0xFFFE is the largest valid unicast network)
        let npdu = Npdu {
            destination: Some(NpduAddress {
                network: 0xFFFE,
                mac_address: MacAddr::from_slice(&[0x01, 0x02]),
            }),
            hop_count: 200,
            payload: Bytes::from_static(&[0xAA]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded.destination.as_ref().unwrap().network, 0xFFFE);
        assert_eq!(decoded.hop_count, 200);
    }

    #[test]
    fn npdu_hop_count_zero() {
        // Hop count 0 is valid (means don't forward further)
        let npdu = Npdu {
            destination: Some(NpduAddress {
                network: 1000,
                mac_address: MacAddr::new(),
            }),
            hop_count: 0,
            payload: Bytes::from_static(&[0x10, 0x08]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded.hop_count, 0);
    }

    #[test]
    fn npdu_source_with_empty_mac() {
        // SLEN=0 is invalid for source per Clause 6.2.2 — rejected at encode time
        let npdu = Npdu {
            source: Some(NpduAddress {
                network: 500,
                mac_address: MacAddr::new(),
            }),
            payload: Bytes::from_static(&[0xBB]),
            ..Default::default()
        };
        let mut buf = BytesMut::new();
        let result = encode_npdu(&mut buf, &npdu);
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("SLEN"), "got: {err}");
    }

    #[test]
    fn npdu_destination_dlen_zero_broadcast_accepted() {
        // DLEN=0 is valid for destination (broadcast) per Clause 6.2.2
        let npdu = Npdu {
            destination: Some(NpduAddress {
                network: 0xFFFF,
                mac_address: MacAddr::new(),
            }),
            hop_count: 255,
            payload: Bytes::from_static(&[0x10, 0x08]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded.destination.as_ref().unwrap().network, 0xFFFF);
        assert!(decoded.destination.as_ref().unwrap().mac_address.is_empty());
    }

    #[test]
    fn npdu_destination_truncated_mac() {
        // DNET + DLEN present but MAC bytes are short
        // Version=1, Control=0x20 (dest present), DNET=1000, DLEN=6, only 2 MAC bytes
        let data = [0x01, 0x20, 0x03, 0xE8, 0x06, 0x01, 0x02];
        assert!(decode_npdu(Bytes::copy_from_slice(&data)).is_err());
    }

    #[test]
    fn npdu_source_truncated_mac() {
        // Source present but MAC bytes truncated
        let data = [0x01, 0x08, 0x01, 0xF4, 0x04, 0x01]; // SNET=500, SLEN=4, only 1 byte
        assert!(decode_npdu(Bytes::copy_from_slice(&data)).is_err());
    }

    #[test]
    fn npdu_missing_hop_count() {
        // Destination present but data ends before hop count
        // Version=1, Control=0x20, DNET=0xFFFF, DLEN=0
        let data = [0x01, 0x20, 0xFF, 0xFF, 0x00];
        assert!(decode_npdu(Bytes::copy_from_slice(&data)).is_err());
    }

    #[test]
    fn npdu_network_message_truncated_type() {
        // Network message flag set but no message type byte
        let data = [0x01, 0x80]; // is_network_message = true, but no type byte
        assert!(decode_npdu(Bytes::copy_from_slice(&data)).is_err());
    }

    #[test]
    fn npdu_proprietary_message_truncated_vendor() {
        // Proprietary message type (>=0x80) but vendor ID missing
        let data = [0x01, 0x80, 0x80]; // msg_type=0x80, need 2 more bytes for vendor
        assert!(decode_npdu(Bytes::copy_from_slice(&data)).is_err());
    }

    #[test]
    fn npdu_all_flags_round_trip() {
        // Maximum complexity: all flags set
        let npdu = Npdu {
            is_network_message: false,
            expecting_reply: true,
            priority: NetworkPriority::LIFE_SAFETY,
            destination: Some(NpduAddress {
                network: 2000,
                mac_address: MacAddr::from_slice(&[0x0A, 0x00, 0x02, 0x01, 0xBA, 0xC0]),
            }),
            source: Some(NpduAddress {
                network: 1000,
                mac_address: MacAddr::from_slice(&[0x0A, 0x00, 0x01, 0x01, 0xBA, 0xC0]),
            }),
            hop_count: 127,
            payload: Bytes::from_static(&[0xDE, 0xAD, 0xBE, 0xEF]),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert_eq!(decoded, npdu);
    }

    #[test]
    fn npdu_empty_payload() {
        // No payload at all
        let npdu = Npdu {
            payload: Bytes::new(),
            ..Default::default()
        };
        let encoded = encode_to_vec(&npdu);
        let decoded = decode_npdu(Bytes::from(encoded)).unwrap();
        assert!(decoded.payload.is_empty());
    }

    #[test]
    fn reject_snet_zero() {
        // Source network 0 is invalid per Clause 6.2.2 — rejected at encode time
        let npdu = Npdu {
            source: Some(NpduAddress {
                network: 0,
                mac_address: MacAddr::from_slice(&[0x01]),
            }),
            payload: Bytes::from_static(&[0x10, 0x08]),
            ..Default::default()
        };
        let mut buf = BytesMut::new();
        let result = encode_npdu(&mut buf, &npdu);
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("SNET"), "got: {err}");
    }

    #[test]
    fn reserved_bits_warning_still_decodes() {
        // Reserved bits set in control byte should NOT cause decode failure
        // (warning only). Construct wire bytes manually with reserved bit 6 set.
        let mut data = vec![0x01, 0x40]; // version=1, control with reserved bit 6
        data.extend_from_slice(&[0x10, 0x08]);

        // Should decode successfully (warning only, not error)
        let result = decode_npdu(Bytes::copy_from_slice(&data));
        assert!(
            result.is_ok(),
            "reserved bits should not cause decode failure"
        );
    }
}