bacnet-rs 0.3.0

BACnet protocol stack implementation in Rust
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
//! BACnet Object Types and Property Management
//!
//! This module defines BACnet object types and their properties according to ASHRAE Standard 135.
//! Objects are the fundamental modeling concept in BACnet, representing physical and logical
//! entities in building automation systems such as sensors, actuators, controllers, and data points.
//!
//! # Overview
//!
//! BACnet objects are the core abstraction for all entities in a BACnet system. Each object consists of:
//!
//! - **Object Identifier**: A unique 32-bit identifier combining object type and instance number
//! - **Properties**: A collection of named values that describe the object's state, configuration, and behavior
//! - **Required Properties**: Properties that must be present in all instances of an object type
//! - **Optional Properties**: Properties that may be present depending on the implementation
//!
//! # Object Hierarchy
//!
//! Objects are organized into categories based on their function:
//!
//! ## Input Objects
//! - [`AnalogInput`](ObjectType::AnalogInput): Represents analog sensor readings (temperature, pressure, etc.)
//! - [`BinaryInput`](ObjectType::BinaryInput): Represents digital sensor states (on/off, open/closed)
//! - [`MultiStateInput`](ObjectType::MultiStateInput): Represents enumerated sensor states
//!
//! ## Output Objects  
//! - [`AnalogOutput`](ObjectType::AnalogOutput): Controls analog actuators (valve position, damper angle)
//! - [`BinaryOutput`](ObjectType::BinaryOutput): Controls digital actuators (pumps, fans, lights)
//! - [`MultiStateOutput`](ObjectType::MultiStateOutput): Controls multi-position actuators
//!
//! ## Value Objects
//! - [`AnalogValue`](ObjectType::AnalogValue): Software variables for calculations and setpoints
//! - [`BinaryValue`](ObjectType::BinaryValue): Software flags and status indicators
//! - [`MultiStateValue`](ObjectType::MultiStateValue): Software enumerated values
//!
//! ## System Objects
//! - [`Device`](ObjectType::Device): Represents a BACnet device (required in every device)
//! - [`Schedule`](ObjectType::Schedule): Time-based control schedules
//! - [`Calendar`](ObjectType::Calendar): Date-based event definitions
//! - [`TrendLog`](ObjectType::TrendLog): Historical data logging
//!
//! # Property System
//!
//! Properties are the attributes that describe an object's state and behavior. Common properties include:
//!
//! - **Present Value**: The current value or state of the object
//! - **Object Name**: A human-readable name for the object
//! - **Description**: Additional descriptive text
//! - **Units**: Engineering units for analog values
//! - **Reliability**: Indicates if the value is reliable
//!
//! # Examples
//!
//! ## Creating Object Identifiers
//!
//! ```rust
//! use bacnet_rs::object::{ObjectIdentifier, ObjectType};
//!
//! // Create an object identifier for analog input #1
//! let temp_sensor = ObjectIdentifier::new(ObjectType::AnalogInput, 1);
//! assert_eq!(temp_sensor.object_type, ObjectType::AnalogInput);
//! assert_eq!(temp_sensor.instance, 1);
//!
//! // Create device object (instance 123456)
//! let device = ObjectIdentifier::new(ObjectType::Device, 123456);
//! assert!(device.is_valid());
//! ```
//!
//! ## Working with Properties
//!
//! ```rust
//! use bacnet_rs::object::{PropertyIdentifier, PropertyValue};
//!
//! // Property identifiers for common properties
//! let present_value = PropertyIdentifier::PresentValue;
//! let object_name = PropertyIdentifier::ObjectName;
//! let units = PropertyIdentifier::OutputUnits;
//!
//! // Property values can represent different data types
//! let temperature = PropertyValue::Real(23.5);
//! let name = PropertyValue::CharacterString("Temperature Sensor".to_string());
//! let unit_enum = PropertyValue::Enumerated(64); // Degrees Celsius
//! ```
//!
//! ## Object Database Usage
//!
//! ```rust,no_run
//! use bacnet_rs::object::{database::ObjectDatabase, ObjectIdentifier, ObjectType, PropertyIdentifier, PropertyValue, analog::AnalogInput, Device};
//!
//! // Create a device and object database
//! let device = Device::new(12345, "BACnet Device".to_string());
//! let mut db = ObjectDatabase::new(device);
//!
//! // Create an analog input object
//! let mut ai = AnalogInput::new(1, "Room Temperature".to_string());
//! ai.set_present_value(23.5);
//! let obj_id = ai.identifier;
//!
//! // Add the object to the database
//! db.add_object(Box::new(ai)).expect("Failed to add object");
//!
//! // Set properties
//! db.set_property(obj_id, PropertyIdentifier::ObjectName,
//!     PropertyValue::CharacterString("Room Temperature".to_string()))
//!     .expect("Failed to set property");
//!
//! // Read properties
//! let name = db.get_property(obj_id, PropertyIdentifier::ObjectName)
//!     .expect("Property not found");
//! ```
//!
//! # Standards Compliance
//!
//! This implementation follows ASHRAE Standard 135-2020 and includes:
//!
//! - All standard object types defined in the specification
//! - Complete property identifier enumeration
//! - Proper object identifier encoding/decoding
//! - Thread-safe object database implementation

use bitflags::bitflags;
use core::fmt::Display;
#[cfg(feature = "std")]
use std::error::Error;

#[cfg(feature = "std")]
use std::fmt;

#[cfg(not(feature = "std"))]
use core::fmt;

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

/// Result type for object operations
#[cfg(feature = "std")]
pub type Result<T> = std::result::Result<T, ObjectError>;

#[cfg(not(feature = "std"))]
pub type Result<T> = core::result::Result<T, ObjectError>;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Errors that can occur with object operations
#[derive(Debug)]
pub enum ObjectError {
    /// Object not found
    NotFound,
    /// Object instance not found
    InstanceNotFound,
    /// Object type not supported
    TypeNotSupported,
    /// Property not found
    PropertyNotFound,
    /// Unknown property
    UnknownProperty,
    /// Property not writable
    PropertyNotWritable,
    /// Invalid property type
    InvalidPropertyType,
    /// Invalid property value
    InvalidValue(String),
    /// Write access denied
    WriteAccessDenied,
    /// Invalid object configuration
    InvalidConfiguration(String),
}

impl fmt::Display for ObjectError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ObjectError::NotFound => write!(f, "Object not found"),
            ObjectError::InstanceNotFound => write!(f, "Object instance not found"),
            ObjectError::TypeNotSupported => write!(f, "Object type not supported"),
            ObjectError::PropertyNotFound => write!(f, "Property not found"),
            ObjectError::UnknownProperty => write!(f, "Unknown property"),
            ObjectError::PropertyNotWritable => write!(f, "Property not writable"),
            ObjectError::InvalidPropertyType => write!(f, "Invalid property type"),
            ObjectError::InvalidValue(msg) => write!(f, "Invalid value: {}", msg),
            ObjectError::WriteAccessDenied => write!(f, "Write access denied"),
            ObjectError::InvalidConfiguration(msg) => write!(f, "Invalid configuration: {}", msg),
        }
    }
}

#[cfg(feature = "std")]
impl Error for ObjectError {}

/// Object identifier (type + instance number)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ObjectIdentifier {
    pub object_type: ObjectType,
    pub instance: u32,
}

impl ObjectIdentifier {
    /// Create a new object identifier
    pub fn new(object_type: ObjectType, instance: u32) -> Self {
        Self {
            object_type,
            instance,
        }
    }

    /// Check if instance number is valid (0-4194302)
    pub fn is_valid(&self) -> bool {
        self.instance <= 0x3FFFFF
    }
}

impl From<u32> for ObjectIdentifier {
    /// Convert from 32-bit object identifier.
    /// See clause 20.2.14 of the BACnet specification.
    fn from(value: u32) -> Self {
        let object_type = (value >> 22) & 0x3FF;
        let object_type = object_type.into();
        let instance = value & 0x3FFFFF;
        Self::new(object_type, instance)
    }
}

impl TryFrom<ObjectIdentifier> for u32 {
    type Error = EncodingError;

    fn try_from(value: ObjectIdentifier) -> std::result::Result<Self, Self::Error> {
        let object_type: u32 = value.object_type.into();

        if object_type > 0x3FF || value.instance > 0x3FFFFF {
            Err(EncodingError::ValueOutOfRange)
        } else {
            Ok((object_type << 22) | (value.instance & 0x3FFFFF))
        }
    }
}

/// Trait for all BACnet objects
pub trait BacnetObject: Send + Sync {
    /// Get the object identifier
    fn identifier(&self) -> ObjectIdentifier;

    /// Get a property value
    fn get_property(&self, property: PropertyIdentifier) -> Result<PropertyValue>;

    /// Set a property value
    fn set_property(&mut self, property: PropertyIdentifier, value: PropertyValue) -> Result<()>;

    /// Check if property is writable
    fn is_property_writable(&self, property: PropertyIdentifier) -> bool;

    /// Get list of all properties
    fn property_list(&self) -> Vec<PropertyIdentifier>;
}

/// Property values can be of various types
#[derive(Debug, Clone)]
pub enum PropertyValue {
    Null,
    Boolean(bool),
    UnsignedInteger(u32),
    SignedInt(i32),
    Real(f32),
    Double(f64),
    OctetString(Vec<u8>),
    CharacterString(String),
    BitString(Vec<bool>),
    Enumerated(u32),
    Date(Date),
    Time(Time),
    ObjectIdentifier(ObjectIdentifier),
    Array(Vec<PropertyValue>),
    List(Vec<PropertyValue>),
}

/// BACnet date representation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Date {
    pub year: u16,   // 1900-2155, 255 = unspecified
    pub month: u8,   // 1-12, 13 = odd months, 14 = even months, 255 = unspecified
    pub day: u8,     // 1-31, 32 = last day of month, 255 = unspecified
    pub weekday: u8, // 1-7 (Mon-Sun), 255 = unspecified
}

/// BACnet time representation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Time {
    pub hour: u8,       // 0-23, 255 = unspecified
    pub minute: u8,     // 0-59, 255 = unspecified
    pub second: u8,     // 0-59, 255 = unspecified
    pub hundredths: u8, // 0-99, 255 = unspecified
}

/// Device object implementation
#[derive(Debug, Clone)]
pub struct Device {
    /// Object identifier
    pub identifier: ObjectIdentifier,
    /// Object name (required property)
    pub object_name: String,
    /// Object type (always Device)
    pub object_type: ObjectType,
    /// System status
    pub system_status: DeviceStatus,
    /// Vendor name
    pub vendor_name: String,
    /// Vendor identifier
    pub vendor_identifier: u16,
    /// Model name
    pub model_name: String,
    /// Firmware revision
    pub firmware_revision: String,
    /// Application software version
    pub application_software_version: String,
    /// Protocol version (always 1)
    pub protocol_version: u8,
    /// Protocol revision
    pub protocol_revision: u8,
    /// Protocol services supported
    pub protocol_services_supported: ProtocolServicesSupported,
    /// Object types supported
    pub object_types_supported: Vec<ObjectType>,
    /// Maximum APDU length accepted
    pub max_apdu_length_accepted: u16,
    /// Segmentation support
    pub segmentation_supported: Segmentation,
    /// Device address binding (for routing)
    pub device_address_binding: Vec<AddressBinding>,
    /// Database revision
    pub database_revision: u32,
}

impl Device {
    /// Create a new Device object
    pub fn new(instance: u32, object_name: String) -> Self {
        Self {
            identifier: ObjectIdentifier::new(ObjectType::Device, instance),
            object_name,
            object_type: ObjectType::Device,
            system_status: DeviceStatus::Operational,
            vendor_name: String::from("BACnet-RS"),
            vendor_identifier: 999, // Reserved for ASHRAE - appropriate for open-source implementations
            model_name: String::from("Rust BACnet Device"),
            firmware_revision: String::from("1.0.0"),
            application_software_version: String::from("0.2.1"),
            protocol_version: 1,
            protocol_revision: 22, // Current BACnet protocol revision
            protocol_services_supported: ProtocolServicesSupported::default(),
            object_types_supported: vec![ObjectType::Device],
            max_apdu_length_accepted: 1476,
            segmentation_supported: Segmentation::Both,
            device_address_binding: Vec::new(),
            database_revision: 1,
        }
    }

    /// Add an object type to the supported list
    pub fn add_supported_object_type(&mut self, object_type: ObjectType) {
        if !self.object_types_supported.contains(&object_type) {
            self.object_types_supported.push(object_type);
        }
    }

    /// Get the vendor information for this device
    pub fn get_vendor_info(&self) -> Option<crate::vendor::VendorInfo> {
        crate::vendor::get_vendor_info(self.vendor_identifier)
    }

    /// Get the official vendor name from the vendor ID
    pub fn get_official_vendor_name(&self) -> Option<&'static str> {
        crate::vendor::get_vendor_name(self.vendor_identifier)
    }

    /// Set vendor information using an official vendor ID
    pub fn set_vendor_by_id(&mut self, vendor_id: u16) -> Result<()> {
        if let Some(vendor_info) = crate::vendor::get_vendor_info(vendor_id) {
            self.vendor_identifier = vendor_id;
            self.vendor_name = vendor_info.name.to_string();
            Ok(())
        } else {
            Err(ObjectError::InvalidPropertyType)
        }
    }

    /// Set vendor information with custom name (preserves vendor ID)
    pub fn set_vendor_name(&mut self, name: String) {
        self.vendor_name = name;
    }

    /// Check if the current vendor ID is officially assigned
    pub fn is_vendor_id_official(&self) -> bool {
        crate::vendor::is_vendor_id_assigned(self.vendor_identifier)
            && !crate::vendor::is_vendor_id_reserved(self.vendor_identifier)
    }

    /// Check if the current vendor ID is reserved for testing
    pub fn is_vendor_id_test(&self) -> bool {
        crate::vendor::is_vendor_id_reserved(self.vendor_identifier)
    }

    /// Get a formatted string showing vendor information
    pub fn format_vendor_display(&self) -> String {
        crate::vendor::format_vendor_display(self.vendor_identifier)
    }
}

impl BacnetObject for Device {
    fn identifier(&self) -> ObjectIdentifier {
        self.identifier
    }

    fn get_property(&self, property: PropertyIdentifier) -> Result<PropertyValue> {
        match property {
            PropertyIdentifier::ObjectIdentifier => {
                Ok(PropertyValue::ObjectIdentifier(self.identifier))
            }
            PropertyIdentifier::ObjectName => {
                Ok(PropertyValue::CharacterString(self.object_name.clone()))
            }
            PropertyIdentifier::ObjectType => {
                Ok(PropertyValue::Enumerated(u32::from(self.object_type)))
            }
            PropertyIdentifier::SystemStatus => {
                Ok(PropertyValue::Enumerated(self.system_status as u32))
            }
            PropertyIdentifier::VendorName => {
                Ok(PropertyValue::CharacterString(self.vendor_name.clone()))
            }
            PropertyIdentifier::VendorIdentifier => Ok(PropertyValue::UnsignedInteger(
                self.vendor_identifier as u32,
            )),
            PropertyIdentifier::ModelName => {
                Ok(PropertyValue::CharacterString(self.model_name.clone()))
            }
            PropertyIdentifier::FirmwareRevision => Ok(PropertyValue::CharacterString(
                self.firmware_revision.clone(),
            )),
            PropertyIdentifier::ApplicationSoftwareVersion => Ok(PropertyValue::CharacterString(
                self.application_software_version.clone(),
            )),
            PropertyIdentifier::ProtocolVersion => {
                Ok(PropertyValue::UnsignedInteger(self.protocol_version as u32))
            }
            PropertyIdentifier::ProtocolRevision => Ok(PropertyValue::UnsignedInteger(
                self.protocol_revision as u32,
            )),
            PropertyIdentifier::MaxApduLengthAccepted => Ok(PropertyValue::UnsignedInteger(
                self.max_apdu_length_accepted as u32,
            )),
            PropertyIdentifier::SegmentationSupported => Ok(PropertyValue::Enumerated(
                self.segmentation_supported as u32,
            )),
            PropertyIdentifier::DatabaseRevision => {
                Ok(PropertyValue::UnsignedInteger(self.database_revision))
            }
            _ => Err(ObjectError::UnknownProperty),
        }
    }

    fn set_property(&mut self, property: PropertyIdentifier, value: PropertyValue) -> Result<()> {
        match property {
            PropertyIdentifier::ObjectName => {
                if let PropertyValue::CharacterString(name) = value {
                    self.object_name = name;
                    Ok(())
                } else {
                    Err(ObjectError::InvalidPropertyType)
                }
            }
            PropertyIdentifier::VendorName => {
                if let PropertyValue::CharacterString(name) = value {
                    self.vendor_name = name;
                    Ok(())
                } else {
                    Err(ObjectError::InvalidPropertyType)
                }
            }
            PropertyIdentifier::ModelName => {
                if let PropertyValue::CharacterString(name) = value {
                    self.model_name = name;
                    Ok(())
                } else {
                    Err(ObjectError::InvalidPropertyType)
                }
            }
            PropertyIdentifier::FirmwareRevision => {
                if let PropertyValue::CharacterString(revision) = value {
                    self.firmware_revision = revision;
                    Ok(())
                } else {
                    Err(ObjectError::InvalidPropertyType)
                }
            }
            PropertyIdentifier::ApplicationSoftwareVersion => {
                if let PropertyValue::CharacterString(version) = value {
                    self.application_software_version = version;
                    Ok(())
                } else {
                    Err(ObjectError::InvalidPropertyType)
                }
            }
            PropertyIdentifier::DatabaseRevision => {
                if let PropertyValue::UnsignedInteger(revision) = value {
                    self.database_revision = revision;
                    Ok(())
                } else {
                    Err(ObjectError::InvalidPropertyType)
                }
            }
            _ => Err(ObjectError::PropertyNotWritable),
        }
    }

    fn is_property_writable(&self, property: PropertyIdentifier) -> bool {
        matches!(
            property,
            PropertyIdentifier::ObjectName
                | PropertyIdentifier::VendorName
                | PropertyIdentifier::ModelName
                | PropertyIdentifier::FirmwareRevision
                | PropertyIdentifier::ApplicationSoftwareVersion
                | PropertyIdentifier::DatabaseRevision
        )
    }

    fn property_list(&self) -> Vec<PropertyIdentifier> {
        vec![
            PropertyIdentifier::ObjectIdentifier,
            PropertyIdentifier::ObjectName,
            PropertyIdentifier::ObjectType,
            PropertyIdentifier::SystemStatus,
            PropertyIdentifier::VendorName,
            PropertyIdentifier::VendorIdentifier,
            PropertyIdentifier::ModelName,
            PropertyIdentifier::FirmwareRevision,
            PropertyIdentifier::ApplicationSoftwareVersion,
            PropertyIdentifier::ProtocolVersion,
            PropertyIdentifier::ProtocolRevision,
            PropertyIdentifier::MaxApduLengthAccepted,
            PropertyIdentifier::SegmentationSupported,
            PropertyIdentifier::DatabaseRevision,
        ]
    }
}

/// Device status enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum DeviceStatus {
    Operational = 0,
    OperationalReadOnly = 1,
    DownloadRequired = 2,
    DownloadInProgress = 3,
    NonOperational = 4,
    BackupInProgress = 5,
}

/// Segmentation support enumeration
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum Segmentation {
    Both = 0,
    Transmit = 1,
    Receive = 2,
    NoSegmentation = 3,
}

impl TryFrom<u32> for Segmentation {
    type Error = ObjectError;

    fn try_from(value: u32) -> Result<Self> {
        match value {
            0 => Ok(Self::Both),
            1 => Ok(Self::Transmit),
            2 => Ok(Self::Receive),
            3 => Ok(Self::NoSegmentation),
            _ => Err(ObjectError::InvalidConfiguration(format!(
                "Unknown segmentation: {}",
                value
            ))),
        }
    }
}

impl Display for Segmentation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Both => write!(f, "Both"),
            Self::Transmit => write!(f, "Transmit"),
            Self::Receive => write!(f, "Receive"),
            Self::NoSegmentation => write!(f, "None"),
        }
    }
}

bitflags! {
    /// Protocol services supported bitfield
    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
    #[derive(Debug, Clone, Default, Eq, PartialEq)]
    pub struct ProtocolServicesSupported: u64 {
        const ACKNOWLEDGE_ALARM = 1 << 0;
        const CONFIRMED_COV_NOTIFICATION = 1 << 1;
        const CONFIRMED_EVENT_NOTIFICATION = 1 << 2;
        const GET_ALARM_SUMMARY = 1 << 3;
        const GET_ENROLLMENT_SUMMARY = 1 << 4;
        const SUBSCRIBE_COV = 1 << 5;
        const ATOMIC_READ_FILE = 1 << 6;
        const ATOMIC_WRITE_FILE = 1 << 7;
        const ADD_LIST_ELEMENT = 1 << 8;
        const REMOVE_LIST_ELEMENT = 1 << 9;
        const CREATE_OBJECT = 1 << 10;
        const DELETE_OBJECT = 1 << 11;
        const READ_PROPERTY = 1 << 12;
        const READ_PROPERTY_CONDITIONAL = 1 << 13;
        const READ_PROPERTY_MULTIPLE = 1 << 14;
        const WRITE_PROPERTY = 1 << 15;
        const WRITE_PROPERTY_MULTIPLE = 1 << 16;
        const DEVICE_COMMUNICATION_CONTROL = 1 << 17;
        const CONFIRMED_PRIVATE_TRANSFER = 1 << 18;
        const CONFIRMED_TEXT_MESSAGE = 1 << 19;
        const REINITIALIZE_DEVICE = 1 << 20;
        const VT_OPEN = 1 << 21;
        const VT_CLOSE = 1 << 22;
        const VT_DATA = 1 << 23;
        const AUTHENTICATE = 1 << 24;
        const REQUEST_KEY = 1 << 25;
        const I_AM = 1 << 26;
        const I_HAVE = 1 << 27;
        const UNCONFIRMED_COV_NOTIFICATION = 1 << 28;
        const UNCONFIRMED_EVENT_NOTIFICATION = 1 << 29;
        const UNCONFIRMED_PRIVATE_TRANSFER = 1 << 30;
        const UNCONFIRMED_TEXT_MESSAGE = 1 << 31;
        const TIME_SYNCHRONIZATION = 1 << 32;
        const WHO_HAS = 1 << 33;
        const WHO_IS = 1 << 34;
        const READ_RANGE = 1 << 35;
        const UTC_TIME_SYNCHRONIZATION = 1 << 36;
        const LIFE_SAFETY_OPERATION = 1 << 37;
        const SUBSCRIBE_COV_PROPERTY = 1 << 38;
        const GET_EVENT_INFORMATION = 1 << 39;
        const WRITE_GROUP = 1 << 40;
        const SUBSCRIBE_COV_PROPERTY_MULTIPLE = 1 << 41;
        const CONFIRMED_COV_NOTIFICATION_MULTIPLE = 1 << 42;
        const UNCONFIRMED_COV_NOTIFICATION_MULTIPLE = 1 << 43;
        const CONFIRMED_AUDIT_NOTIFICATION = 1 << 44;
        const AUDIT_LOG_QUERY = 1 << 45;
        const UNCONFIRMED_AUDIT_NOTIFICATION = 1 << 46;
        const WHO_AM_I = 1 << 47;
        const YOU_ARE = 1 << 48;
        const AUTH_REQUEST = 1 << 49;
    }
}

impl ProtocolServicesSupported {
    pub fn to_bool_vec(&self) -> Vec<bool> {
        let mut vec = Vec::new();
        for i in 0..64 {
            vec.push((self.bits() & (1 << i)) != 0);
        }
        vec
    }
}

impl From<Vec<bool>> for ProtocolServicesSupported {
    fn from(value: Vec<bool>) -> Self {
        let mut services = ProtocolServicesSupported::empty();
        for (v, f) in value.iter().zip(ProtocolServicesSupported::all().iter()) {
            if *v {
                services.insert(f);
            }
        }
        services
    }
}

/// Address binding for device routing
#[derive(Debug, Clone)]
pub struct AddressBinding {
    pub device_identifier: ObjectIdentifier,
    pub network_address: Vec<u8>,
}

/// Analog object types (AI, AO, AV)
pub mod analog;
/// Binary object types (BI, BO, BV)
pub mod binary;
/// Object database for managing BACnet objects
#[cfg(feature = "std")]
pub mod database;
/// Device object and object functions API
pub mod device;
/// Engineering units enumeration
pub mod engineering_units;
/// File object type
pub mod file;
/// Multi-state object types (MSI, MSO, MSV)
pub mod multistate;

pub mod event_state;
pub mod object_type;
pub mod reliability;
pub use object_type::ObjectType;
pub mod property_identifier;
pub use property_identifier::PropertyIdentifier;

pub use analog::{AnalogInput, AnalogOutput, AnalogValue};
pub use binary::{BinaryInput, BinaryOutput, BinaryPV, BinaryValue, Polarity};
pub use device::{DeviceObject, ObjectFunctions};
pub use engineering_units::EngineeringUnits;
pub use event_state::EventState;
pub use file::{File, FileAccessMethod};
pub use multistate::{MultiStateInput, MultiStateOutput, MultiStateValue};
pub use reliability::Reliability;

#[cfg(feature = "std")]
pub use database::{DatabaseBuilder, DatabaseStatistics, ObjectDatabase};

use crate::EncodingError;

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

    #[test]
    fn test_device_creation() {
        let device = Device::new(123, "Test Device".to_string());
        assert_eq!(device.identifier.instance, 123);
        assert_eq!(device.object_name, "Test Device");
        assert_eq!(device.object_type, ObjectType::Device);
    }

    #[test]
    fn test_device_properties() {
        let mut device = Device::new(456, "Property Test".to_string());

        // Test getting properties
        let name = device.get_property(PropertyIdentifier::ObjectName).unwrap();
        if let PropertyValue::CharacterString(n) = name {
            assert_eq!(n, "Property Test");
        } else {
            panic!("Expected CharacterString");
        }

        // Test setting properties
        device
            .set_property(
                PropertyIdentifier::ObjectName,
                PropertyValue::CharacterString("New Name".to_string()),
            )
            .unwrap();

        let name = device.get_property(PropertyIdentifier::ObjectName).unwrap();
        if let PropertyValue::CharacterString(n) = name {
            assert_eq!(n, "New Name");
        } else {
            panic!("Expected CharacterString");
        }
    }

    #[test]
    fn test_protocol_services_supported() {
        let services = ProtocolServicesSupported::ACKNOWLEDGE_ALARM
            | ProtocolServicesSupported::READ_PROPERTY
            | ProtocolServicesSupported::WRITE_PROPERTY;

        let bools = services.to_bool_vec();
        let services_new = ProtocolServicesSupported::from(bools);
        assert_eq!(services, services_new);
    }
}