bacnet-types 0.9.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
//! 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::{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`.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ObjectIdentifier {
    object_type: ObjectType,
    instance_number: u32,
}

impl ObjectIdentifier {
    /// Maximum valid instance number (2^22 - 1 = 4,194,303).
    pub const MAX_INSTANCE: u32 = 0x3F_FFFF;

    /// The "wildcard" instance number used in WhoIs/IAm (4,194,303).
    pub const WILDCARD_INSTANCE: u32 = Self::MAX_INSTANCE;

    /// Create a new ObjectIdentifier.
    ///
    /// # 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 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).
    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)
    SequenceNumber(u64),
    /// 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(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct StatusFlags: u8 {
        const IN_ALARM = 0b1000;
        const FAULT = 0b0100;
        const OVERRIDDEN = 0b0010;
        const OUT_OF_SERVICE = 0b0001;
    }
}

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>),
}

// ---------------------------------------------------------------------------
// 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);
    }

    #[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()));
    }
}