bacnet-types 0.11.0

BACnet protocol types, enums, and primitives 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
//! BACnet primitive data types per ASHRAE 135-2020 Clause 20.2.
//!
//! Core types used throughout the protocol: [`ObjectIdentifier`], [`Date`],
//! [`Time`], and the [`PropertyValue`] sum type.

#[cfg(not(feature = "std"))]
use alloc::{format, string::String, vec::Vec};

use crate::enums::ObjectType;
use crate::error::Error;

// ---------------------------------------------------------------------------
// ObjectIdentifier (Clause 20.2.14)
// ---------------------------------------------------------------------------

/// BACnet Object Identifier: 10-bit type + 22-bit instance number.
///
/// Uniquely identifies a BACnet object within a device. Encoded as a
/// 4-byte big-endian value: `(object_type << 22) | instance_number`.
///
/// The all-ones instance value [`WILDCARD_INSTANCE`](Self::WILDCARD_INSTANCE)
/// is still a valid 22-bit wire value, and some service contexts give it
/// wildcard meaning. Use [`ObjectIdentifier::new`] or [`ObjectIdentifier::decode`]
/// when preserving wire-level values. Use [`ObjectIdentifier::new_addressable`]
/// when constructing identifiers for concrete objects that can be stored,
/// addressed, or compared as actual object instances.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ObjectIdentifier {
    object_type: ObjectType,
    instance_number: u32,
}

impl ObjectIdentifier {
    /// Maximum encodable instance number (2^22 - 1 = 4,194,303).
    ///
    /// This is also [`WILDCARD_INSTANCE`](Self::WILDCARD_INSTANCE). It is
    /// accepted by [`ObjectIdentifier::new`] and [`ObjectIdentifier::decode`]
    /// for wire compatibility, but callers that need a concrete addressable
    /// object should use [`MAX_ADDRESSABLE_INSTANCE`](Self::MAX_ADDRESSABLE_INSTANCE)
    /// or [`ObjectIdentifier::new_addressable`].
    pub const MAX_INSTANCE: u32 = 0x3F_FFFF;

    /// The reserved wildcard instance number (4,194,303).
    ///
    /// BACnet service clauses assign this value special "any/local instance"
    /// meaning in selected contexts, for example Who-Is/Who-Am-I discovery and
    /// Device/Network Port object access. It is not a concrete object instance
    /// for addressable-object storage.
    pub const WILDCARD_INSTANCE: u32 = Self::MAX_INSTANCE;

    /// Maximum instance number for a concrete addressable object (4,194,302).
    ///
    /// This excludes [`WILDCARD_INSTANCE`](Self::WILDCARD_INSTANCE).
    pub const MAX_ADDRESSABLE_INSTANCE: u32 = Self::WILDCARD_INSTANCE - 1;

    /// Create a new ObjectIdentifier from any valid 22-bit wire instance.
    ///
    /// This constructor preserves [`WILDCARD_INSTANCE`](Self::WILDCARD_INSTANCE)
    /// because it is a valid encoded value in BACnet service payloads. Use
    /// [`ObjectIdentifier::new_addressable`] when the identifier must name a
    /// concrete object instance.
    ///
    /// # Errors
    /// Returns `Err` if `instance_number` exceeds [`MAX_INSTANCE`](Self::MAX_INSTANCE).
    pub fn new(object_type: ObjectType, instance_number: u32) -> Result<Self, Error> {
        if instance_number > Self::MAX_INSTANCE {
            return Err(Error::OutOfRange(alloc_or_std_format!(
                "instance number {} exceeds max {}",
                instance_number,
                Self::MAX_INSTANCE
            )));
        }
        Ok(Self {
            object_type,
            instance_number,
        })
    }

    /// Create a new ObjectIdentifier for a concrete addressable object.
    ///
    /// This rejects [`WILDCARD_INSTANCE`](Self::WILDCARD_INSTANCE), while
    /// [`ObjectIdentifier::new`] keeps accepting that value for wire-level
    /// round trips and BACnet service contexts where it is meaningful.
    ///
    /// # Errors
    /// Returns `Err` if `instance_number` exceeds
    /// [`MAX_INSTANCE`](Self::MAX_INSTANCE) or equals
    /// [`WILDCARD_INSTANCE`](Self::WILDCARD_INSTANCE).
    pub fn new_addressable(object_type: ObjectType, instance_number: u32) -> Result<Self, Error> {
        if instance_number > Self::MAX_INSTANCE {
            return Err(Error::OutOfRange(alloc_or_std_format!(
                "instance number {} exceeds max {}",
                instance_number,
                Self::MAX_INSTANCE
            )));
        }
        if instance_number == Self::WILDCARD_INSTANCE {
            return Err(Error::OutOfRange(alloc_or_std_format!(
                "instance number {} is reserved as the wildcard value; maximum addressable instance is {}",
                instance_number,
                Self::MAX_ADDRESSABLE_INSTANCE
            )));
        }
        Ok(Self {
            object_type,
            instance_number,
        })
    }

    /// Create without validation. Caller must ensure instance <= MAX_INSTANCE.
    pub const fn new_unchecked(object_type: ObjectType, instance_number: u32) -> Self {
        Self {
            object_type,
            instance_number,
        }
    }

    /// The object type.
    pub const fn object_type(&self) -> ObjectType {
        self.object_type
    }

    /// The instance number (0 to 4,194,303).
    ///
    /// Values returned from wire decoding may equal
    /// [`WILDCARD_INSTANCE`](Self::WILDCARD_INSTANCE). Treat that value as a
    /// concrete addressable object only after the relevant service context has
    /// resolved its wildcard semantics.
    pub const fn instance_number(&self) -> u32 {
        self.instance_number
    }

    /// Encode to the 4-byte BACnet wire format (big-endian).
    pub fn encode(&self) -> [u8; 4] {
        debug_assert!(
            self.object_type.to_raw() <= 0x3FF,
            "ObjectType {} exceeds 10-bit field",
            self.object_type.to_raw()
        );
        debug_assert!(
            self.instance_number <= Self::MAX_INSTANCE,
            "Instance {} exceeds MAX_INSTANCE",
            self.instance_number
        );
        let value = ((self.object_type.to_raw() & 0x3FF) << 22)
            | (self.instance_number & Self::MAX_INSTANCE);
        value.to_be_bytes()
    }

    /// Decode from the 4-byte BACnet wire format (big-endian).
    pub fn decode(data: &[u8]) -> Result<Self, Error> {
        if data.len() != 4 {
            return Err(Error::decoding(
                0,
                format!(
                    "ObjectIdentifier expects exactly 4 bytes, got {}",
                    data.len()
                ),
            ));
        }
        let value = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        let type_raw = (value >> 22) & 0x3FF;
        let instance = value & Self::MAX_INSTANCE;
        Ok(Self {
            object_type: ObjectType::from_raw(type_raw),
            instance_number: instance,
        })
    }
}

impl core::fmt::Debug for ObjectIdentifier {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "ObjectIdentifier({:?}, {})",
            self.object_type, self.instance_number
        )
    }
}

impl core::fmt::Display for ObjectIdentifier {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{},{}", self.object_type, self.instance_number)
    }
}

// ---------------------------------------------------------------------------
// Date (Clause 20.2.12)
// ---------------------------------------------------------------------------

/// BACnet Date: year, month, day, day-of-week.
///
/// - Year: 0-254 relative to 1900 (0xFF = unspecified)
/// - Month: 1-14 (13=odd, 14=even, 0xFF=unspecified)
/// - Day: 1-34 (32=last, 33=odd, 34=even, 0xFF=unspecified)
/// - Day of week: 1=Monday..7=Sunday (0xFF=unspecified)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Date {
    /// Year minus 1900 (0-254, or 0xFF for unspecified).
    pub year: u8,
    /// Month (1-14, or 0xFF for unspecified).
    pub month: u8,
    /// Day of month (1-34, or 0xFF for unspecified).
    pub day: u8,
    /// Day of week (1=Monday..7=Sunday, or 0xFF for unspecified).
    pub day_of_week: u8,
}

impl Date {
    /// Value indicating "unspecified" for any date field.
    pub const UNSPECIFIED: u8 = 0xFF;

    /// Encode to 4 bytes.
    pub fn encode(&self) -> [u8; 4] {
        [self.year, self.month, self.day, self.day_of_week]
    }

    /// Decode from 4 bytes.
    pub fn decode(data: &[u8]) -> Result<Self, Error> {
        if data.len() != 4 {
            return Err(Error::decoding(
                0,
                format!("Date expects exactly 4 bytes, got {}", data.len()),
            ));
        }
        Ok(Self {
            year: data[0],
            month: data[1],
            day: data[2],
            day_of_week: data[3],
        })
    }

    /// Get the actual year (1900 + year field), or None if unspecified.
    pub fn actual_year(&self) -> Option<u16> {
        if self.year == Self::UNSPECIFIED {
            None
        } else {
            Some(1900 + self.year as u16)
        }
    }
}

// ---------------------------------------------------------------------------
// Time (Clause 20.2.13)
// ---------------------------------------------------------------------------

/// BACnet Time: hour, minute, second, hundredths.
///
/// Each field can be 0xFF for "unspecified".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Time {
    /// Hour (0-23, or 0xFF for unspecified).
    pub hour: u8,
    /// Minute (0-59, or 0xFF for unspecified).
    pub minute: u8,
    /// Second (0-59, or 0xFF for unspecified).
    pub second: u8,
    /// Hundredths of a second (0-99, or 0xFF for unspecified).
    pub hundredths: u8,
}

impl Time {
    /// Value indicating "unspecified" for any time field.
    pub const UNSPECIFIED: u8 = 0xFF;

    /// Encode to 4 bytes.
    pub fn encode(&self) -> [u8; 4] {
        [self.hour, self.minute, self.second, self.hundredths]
    }

    /// Decode from 4 bytes.
    pub fn decode(data: &[u8]) -> Result<Self, Error> {
        if data.len() != 4 {
            return Err(Error::decoding(
                0,
                format!("Time expects exactly 4 bytes, got {}", data.len()),
            ));
        }
        Ok(Self {
            hour: data[0],
            minute: data[1],
            second: data[2],
            hundredths: data[3],
        })
    }
}

// ---------------------------------------------------------------------------
// BACnetTimeStamp (Clause 20.2.1.5)
// ---------------------------------------------------------------------------

/// BACnet timestamp -- a CHOICE of Time, sequence number, or DateTime.
#[derive(Debug, Clone, PartialEq)]
pub enum BACnetTimeStamp {
    /// Context tag 0: Time
    Time(Time),
    /// Context tag 1: Unsigned sequence number in the required 0..=65535 range.
    SequenceNumber(u16),
    /// Context tag 2: BACnetDateTime (Date + Time)
    DateTime { date: Date, time: Time },
}

// ---------------------------------------------------------------------------
// StatusFlags (Clause 12.X -- used by many object types)
// ---------------------------------------------------------------------------

bitflags::bitflags! {
    /// BACnet StatusFlags -- 4-bit bitstring present on most objects.
    #[derive(Clone, Copy, PartialEq, Eq, Hash)]
    pub struct StatusFlags: u8 {
        const IN_ALARM = 0b1000;
        const FAULT = 0b0100;
        const OVERRIDDEN = 0b0010;
        const OUT_OF_SERVICE = 0b0001;
    }
}

impl core::fmt::Display for StatusFlags {
    /// Renders the set flags by their Clause-21 names (`IN_ALARM | FAULT`), or
    /// `()` when none are set — never a raw number.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut first = true;
        for (name, _) in self.iter_names() {
            if !first {
                f.write_str(" | ")?;
            }
            f.write_str(name)?;
            first = false;
        }
        if first {
            f.write_str("()")?;
        }
        Ok(())
    }
}

impl core::fmt::Debug for StatusFlags {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(self, f)
    }
}
bitflags::bitflags! {
    /// BACnet DaysOfWeek -- 7-bit bitstring (Clause 21).
    ///
    /// Bit 0 (MSB=0x40) = Monday, Bit 6 (0x01) = Sunday.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct DaysOfWeek: u8 {
        const MONDAY    = 0b0100_0000;
        const TUESDAY   = 0b0010_0000;
        const WEDNESDAY = 0b0001_0000;
        const THURSDAY  = 0b0000_1000;
        const FRIDAY    = 0b0000_0100;
        const SATURDAY  = 0b0000_0010;
        const SUNDAY    = 0b0000_0001;
        const ALL       = 0b0111_1111;
    }
}

// ---------------------------------------------------------------------------
// PropertyValue -- sum type for BACnet property values
// ---------------------------------------------------------------------------

/// A BACnet application-layer value.
///
/// This enum covers all primitive value types that can appear as property
/// values in BACnet objects. Constructed types (lists, sequences) are
/// represented as nested structures.
#[derive(Debug, Clone, PartialEq)]
pub enum PropertyValue {
    /// Null value.
    Null,
    /// Boolean value.
    Boolean(bool),
    /// Unsigned integer (up to 64-bit for BACnet Unsigned64).
    Unsigned(u64),
    /// Signed integer.
    Signed(i32),
    /// IEEE 754 single-precision float.
    Real(f32),
    /// IEEE 754 double-precision float.
    Double(f64),
    /// Octet string (raw bytes).
    OctetString(Vec<u8>),
    /// Character string (UTF-8).
    CharacterString(String),
    /// Bit string (variable length).
    BitString {
        /// Number of unused bits in the last byte.
        unused_bits: u8,
        /// The bit data bytes.
        data: Vec<u8>,
    },
    /// Enumerated value.
    Enumerated(u32),
    /// Date value.
    Date(Date),
    /// Time value.
    Time(Time),
    /// Object identifier.
    ObjectIdentifier(ObjectIdentifier),
    /// A sequence (array) of property values.
    ///
    /// Used when reading an entire array property with `arrayIndex` absent
    /// (Clause 15.5.1). Each element is encoded as its own application-tagged
    /// value, concatenated in order.
    List(Vec<PropertyValue>),
    /// Raw, already-encoded application-layer bytes for a property whose wire
    /// form is a context-tagged (CHOICE/SEQUENCE) production that the flat
    /// application-tagged model above cannot express — e.g. a framed
    /// `BACnetEventParameter` or a `Recipient_List` of `BACnetDestination`.
    ///
    /// The bytes are emitted verbatim by
    /// `bacnet_encoding::primitives::encode_property_value` and are produced
    /// by `decode_application_value` when it encounters a context-tagged
    /// element; they always span exactly one complete tagged element,
    /// including its context tag header(s). The same convention as
    /// [`crate::constructed::BACnetTimeValue::value`]'s raw bytes. Objects
    /// that serve structured properties decode these with the matching
    /// framed codec in `bacnet-encoding`; a property writer that is not
    /// expecting this variant should reject it as `INVALID_DATA_TYPE`.
    ApplicationData(Vec<u8>),
}

// ---------------------------------------------------------------------------
// Formatting helper macro (works in both std and no_std+alloc)
// ---------------------------------------------------------------------------

/// Format a string using either std or alloc.
#[cfg(feature = "std")]
macro_rules! alloc_or_std_format {
    ($($arg:tt)*) => { format!($($arg)*) }
}

#[cfg(not(feature = "std"))]
macro_rules! alloc_or_std_format {
    ($($arg:tt)*) => { alloc::format!($($arg)*) }
}

use alloc_or_std_format;

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

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

    #[test]
    fn object_identifier_encode_decode_round_trip() {
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 1).unwrap();
        let bytes = oid.encode();
        let decoded = ObjectIdentifier::decode(&bytes).unwrap();
        assert_eq!(oid, decoded);
    }

    #[test]
    fn object_identifier_wire_format() {
        // AnalogInput (type=0) instance=1: (0 << 22) | 1 = 0x00000001
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 1).unwrap();
        assert_eq!(oid.encode(), [0x00, 0x00, 0x00, 0x01]);

        // Device (type=8) instance=1234: (8 << 22) | 1234 = 0x020004D2
        let oid = ObjectIdentifier::new(ObjectType::DEVICE, 1234).unwrap();
        let expected = ((8u32 << 22) | 1234u32).to_be_bytes();
        assert_eq!(oid.encode(), expected);
    }

    #[test]
    fn object_identifier_max_instance() {
        let oid =
            ObjectIdentifier::new(ObjectType::DEVICE, ObjectIdentifier::MAX_INSTANCE).unwrap();
        assert_eq!(oid.instance_number(), 0x3F_FFFF);
        let bytes = oid.encode();
        let decoded = ObjectIdentifier::decode(&bytes).unwrap();
        assert_eq!(decoded.instance_number(), 0x3F_FFFF);
    }

    #[test]
    fn object_identifier_invalid_instance() {
        let result = ObjectIdentifier::new(ObjectType::DEVICE, ObjectIdentifier::MAX_INSTANCE + 1);
        assert!(result.is_err());
    }

    #[test]
    fn object_identifier_buffer_too_short() {
        let result = ObjectIdentifier::decode(&[0x00, 0x00]);
        assert!(result.is_err());
    }

    #[test]
    fn object_identifier_overlong_errors() {
        assert!(ObjectIdentifier::decode(&[0x00, 0x00, 0x00, 0x01, 0xFF]).is_err());
    }

    #[test]
    fn date_encode_decode_round_trip() {
        let date = Date {
            year: 124, // 2024
            month: 6,
            day: 15,
            day_of_week: 6, // Saturday
        };
        let bytes = date.encode();
        let decoded = Date::decode(&bytes).unwrap();
        assert_eq!(date, decoded);
        assert_eq!(decoded.actual_year(), Some(2024));
    }

    #[test]
    fn date_unspecified_year() {
        let date = Date {
            year: Date::UNSPECIFIED,
            month: 1,
            day: 1,
            day_of_week: Date::UNSPECIFIED,
        };
        assert_eq!(date.actual_year(), None);
    }

    #[test]
    fn date_overlong_errors() {
        assert!(Date::decode(&[124, 6, 15, 6, 0]).is_err());
    }

    #[test]
    fn time_encode_decode_round_trip() {
        let time = Time {
            hour: 14,
            minute: 30,
            second: 45,
            hundredths: 50,
        };
        let bytes = time.encode();
        let decoded = Time::decode(&bytes).unwrap();
        assert_eq!(time, decoded);
    }

    #[test]
    fn time_overlong_errors() {
        assert!(Time::decode(&[14, 30, 45, 50, 0]).is_err());
    }

    #[test]
    fn status_flags_operations() {
        let flags = StatusFlags::IN_ALARM | StatusFlags::OUT_OF_SERVICE;
        assert!(flags.contains(StatusFlags::IN_ALARM));
        assert!(flags.contains(StatusFlags::OUT_OF_SERVICE));
        assert!(!flags.contains(StatusFlags::FAULT));
        assert!(!flags.contains(StatusFlags::OVERRIDDEN));
    }

    // --- OID edge cases ---

    #[test]
    fn object_identifier_instance_zero() {
        // Instance 0 is valid and commonly used (e.g., Device,0)
        let oid = ObjectIdentifier::new(ObjectType::DEVICE, 0).unwrap();
        assert_eq!(oid.instance_number(), 0);
        let bytes = oid.encode();
        let decoded = ObjectIdentifier::decode(&bytes).unwrap();
        assert_eq!(decoded.instance_number(), 0);
        assert_eq!(decoded.object_type(), ObjectType::DEVICE);
    }

    #[test]
    fn object_identifier_all_types_instance_zero() {
        // Instance 0 for each common type should round-trip correctly
        for type_raw in [0u32, 1, 2, 3, 4, 5, 6, 8, 10, 13, 14, 17, 19] {
            let obj_type = ObjectType::from_raw(type_raw);
            let oid = ObjectIdentifier::new(obj_type, 0).unwrap();
            let bytes = oid.encode();
            let decoded = ObjectIdentifier::decode(&bytes).unwrap();
            assert_eq!(decoded.object_type(), obj_type, "type {type_raw} failed");
            assert_eq!(
                decoded.instance_number(),
                0,
                "type {type_raw} instance failed"
            );
        }
    }

    #[test]
    fn object_identifier_wildcard_instance() {
        let oid =
            ObjectIdentifier::new(ObjectType::DEVICE, ObjectIdentifier::WILDCARD_INSTANCE).unwrap();
        assert_eq!(oid.instance_number(), ObjectIdentifier::MAX_INSTANCE);
        let bytes = oid.encode();
        let decoded = ObjectIdentifier::decode(&bytes).unwrap();
        assert_eq!(decoded.instance_number(), ObjectIdentifier::MAX_INSTANCE);

        let raw_wire_value = ((ObjectType::DEVICE.to_raw() << 22)
            | ObjectIdentifier::WILDCARD_INSTANCE)
            .to_be_bytes();
        let decoded = ObjectIdentifier::decode(&raw_wire_value).unwrap();
        assert_eq!(decoded.object_type(), ObjectType::DEVICE);
        assert_eq!(
            decoded.instance_number(),
            ObjectIdentifier::WILDCARD_INSTANCE
        );
    }

    #[test]
    fn object_identifier_new_addressable_rejects_wildcard() {
        assert_eq!(
            ObjectIdentifier::MAX_ADDRESSABLE_INSTANCE,
            ObjectIdentifier::WILDCARD_INSTANCE - 1
        );

        let oid = ObjectIdentifier::new_addressable(
            ObjectType::DEVICE,
            ObjectIdentifier::MAX_ADDRESSABLE_INSTANCE,
        )
        .unwrap();
        assert_eq!(
            oid.instance_number(),
            ObjectIdentifier::MAX_ADDRESSABLE_INSTANCE
        );

        let analog_input = ObjectIdentifier::new_addressable(
            ObjectType::ANALOG_INPUT,
            ObjectIdentifier::MAX_ADDRESSABLE_INSTANCE,
        )
        .unwrap();
        assert_eq!(analog_input.object_type(), ObjectType::ANALOG_INPUT);
        assert_eq!(
            analog_input.instance_number(),
            ObjectIdentifier::MAX_ADDRESSABLE_INSTANCE
        );

        let wildcard =
            ObjectIdentifier::new_addressable(ObjectType::DEVICE, ObjectIdentifier::MAX_INSTANCE)
                .unwrap_err();
        assert!(wildcard.to_string().contains("wildcard"));

        let too_large = ObjectIdentifier::new_addressable(
            ObjectType::DEVICE,
            ObjectIdentifier::MAX_INSTANCE + 1,
        );
        assert!(too_large.is_err());
    }

    #[test]
    fn object_identifier_decode_extra_bytes_errors() {
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 42).unwrap();
        let mut bytes = oid.encode().to_vec();
        bytes.extend_from_slice(&[0xFF, 0xFF]);
        assert!(ObjectIdentifier::decode(&bytes).is_err());
    }

    #[test]
    #[cfg_attr(debug_assertions, should_panic(expected = "exceeds 10-bit field"))]
    fn object_identifier_type_overflow_round_trip() {
        // In debug builds, encode() asserts type <= 1023.
        // In release builds, types > 1023 are silently masked to 10 bits.
        let oid = ObjectIdentifier::new_unchecked(ObjectType::from_raw(1024), 0);
        let bytes = oid.encode();
        let decoded = ObjectIdentifier::decode(&bytes).unwrap();
        assert_eq!(decoded.object_type(), ObjectType::from_raw(0));
    }

    #[test]
    fn property_value_variants() {
        let null = PropertyValue::Null;
        let boolean = PropertyValue::Boolean(true);
        let real = PropertyValue::Real(72.5);
        let string = PropertyValue::CharacterString("test".into());

        assert_eq!(null, PropertyValue::Null);
        assert_eq!(boolean, PropertyValue::Boolean(true));
        assert_ne!(real, PropertyValue::Real(73.0));
        assert_eq!(string, PropertyValue::CharacterString("test".into()));
    }
}