bacnet-objects 0.11.0

BACnet object model: traits, database, and standard object types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Extended value object types (ASHRAE 135-2020 Clause 12).
//!
//! The 12 "value" object types share a common structure: present_value, status_flags,
//! out_of_service, reliability, and (for commandable types) a 16-level priority array.
//!
//! A `define_value_object!` macro generates the struct + BACnetObject impl for each type.

use bacnet_types::enums::{ObjectType, PropertyIdentifier};
use bacnet_types::error::Error;
use bacnet_types::primitives::{Date, ObjectIdentifier, PropertyValue, StatusFlags, Time};
use std::borrow::Cow;

use crate::common::{self, read_common_properties};
use crate::property_metadata::{
    PropertyConformance, PropertyMetadata, PropertyPresenceCondition, PropertyWriteCapability,
};
use crate::traits::BACnetObject;

// ---------------------------------------------------------------------------
// Macro: define_value_object! (commandable variant)
// ---------------------------------------------------------------------------

/// Generate a commandable value object type with a 16-level priority array.
///
/// Copy types use the existing `recalculate_from_priority_array` helper;
/// non-Copy types (String, Vec, tuples containing Vec) use a Clone-based
/// inline recalculation.
///
/// `rd_validate` performs any post-extraction validation for a
/// Relinquish_Default value (#270); `rd_access` selects whether the
/// `RELINQUISH_DEFAULT` network write arm exists (`writable`) or remains
/// denied (`readonly` — no current users; kept for a type whose wire form
/// needs something the service decode cannot deliver). The local
/// `set_relinquish_default` setter is generated either way.
macro_rules! define_value_object_commandable {
    (
        name: $struct_name:ident,
        doc: $doc:expr,
        object_type: $obj_type:expr,
        value_type: $val_type:ty,
        default_value: $default:expr,
        pv_to_property: $pv_to_prop:expr,
        property_to_pv: $prop_to_pv:expr,
        pa_wrap: $pa_wrap:expr,
        rd_wrap: $rd_wrap:expr,
        rd_validate: $rd_validate:expr,
        rd_access: $rd_access:ident,
        copy_type: $is_copy:tt
        $(, property_metadata: $property_metadata:expr)?
        $(,)?
    ) => {
        #[doc = $doc]
        pub struct $struct_name {
            oid: ObjectIdentifier,
            name: String,
            description: String,
            present_value: $val_type,
            out_of_service: bool,
            status_flags: StatusFlags,
            reliability: u32,
            /// 16-level priority array. `None` = no command at that level.
            priority_array: [Option<$val_type>; 16],
            relinquish_default: $val_type,
        }

        impl $struct_name {
            /// Create a new instance of this value object.
            pub fn new(instance: u32, name: impl Into<String>) -> Result<Self, Error> {
                let oid = ObjectIdentifier::new($obj_type, instance)?;
                Ok(Self {
                    oid,
                    name: name.into(),
                    description: String::new(),
                    present_value: $default,
                    out_of_service: false,
                    status_flags: StatusFlags::empty(),
                    reliability: 0,
                    priority_array: Default::default(),
                    relinquish_default: $default,
                })
            }

            /// Recalculate present_value from the priority array.
            fn recalculate_present_value(&mut self) {
                define_value_object_commandable!(@recalc self, $is_copy);
            }

            /// Set the Relinquish_Default (#270).
            ///
            /// Validated the same way a commanded Present_Value is, then
            /// Present_Value is resolved anew from the priority array so an
            /// empty array falls back to the new default immediately. The
            /// standard permits Relinquish_Default writability on commandable
            /// types; the service decode's multi-element support (#182) makes
            /// the datetime-paired wire form (a date+time pair) deliverable,
            /// so every commandable value type takes network writes now.
            pub fn set_relinquish_default(&mut self, value: $val_type) -> Result<(), Error> {
                ($rd_validate)(&value)?;
                self.relinquish_default = value;
                self.recalculate_present_value();
                Ok(())
            }
        }

        impl BACnetObject for $struct_name {
            fn object_identifier(&self) -> ObjectIdentifier {
                self.oid
            }

            fn object_name(&self) -> &str {
                &self.name
            }

            fn property_metadata(&self) -> Cow<'_, [PropertyMetadata]> {
                define_value_object_commandable!(@property_metadata $($property_metadata)?)
            }

            fn read_property(
                &self,
                property: PropertyIdentifier,
                array_index: Option<u32>,
            ) -> Result<PropertyValue, Error> {
                if let Some(result) = read_common_properties!(self, property, array_index) {
                    return result;
                }
                match property {
                    p if p == PropertyIdentifier::OBJECT_TYPE => {
                        Ok(PropertyValue::Enumerated($obj_type.to_raw()))
                    }
                    p if p == PropertyIdentifier::PRESENT_VALUE => {
                        Ok(($pv_to_prop)(&self.present_value))
                    }
                    p if p == PropertyIdentifier::PRIORITY_ARRAY => {
                        define_value_object_commandable!(@read_pa self, array_index, $pa_wrap, $is_copy)
                    }
                    p if p == PropertyIdentifier::RELINQUISH_DEFAULT => {
                        Ok(($rd_wrap)(&self.relinquish_default))
                    }
                    _ => Err(common::unknown_property_error()),
                }
            }

            fn write_property(
                &mut self,
                property: PropertyIdentifier,
                array_index: Option<u32>,
                value: PropertyValue,
                priority: Option<u8>,
            ) -> Result<(), Error> {
                // Handle PRIORITY_ARRAY direct writes. Index validation
                // follows Clause 12.1.5.1: an omitted index means whole-array
                // access, and whole-array writes are not supported here, so
                // it is PROPERTY / WRITE_ACCESS_DENIED (Clause 15.9.1.3).
                if property == PropertyIdentifier::PRIORITY_ARRAY {
                    let idx = match array_index {
                        Some(n) if (1..=16).contains(&n) => (n - 1) as usize,
                        Some(_) => return Err(common::invalid_array_index_error()),
                        None => return Err(common::write_access_denied_error()),
                    };
                    match value {
                        PropertyValue::Null => {
                            self.priority_array[idx] = None;
                        }
                        other => {
                            let extracted = ($prop_to_pv)(other)?;
                            self.priority_array[idx] = Some(extracted);
                        }
                    }
                    self.recalculate_present_value();
                    return Ok(());
                }
                // Handle PRESENT_VALUE via priority array
                if property == PropertyIdentifier::PRESENT_VALUE {
                    let prio = priority.unwrap_or(16);
                    if !(1..=16).contains(&prio) {
                        return Err(common::value_out_of_range_error());
                    }
                    let idx = (prio - 1) as usize;
                    match value {
                        PropertyValue::Null => {
                            self.priority_array[idx] = None;
                        }
                        other => {
                            let extracted = ($prop_to_pv)(other)?;
                            self.priority_array[idx] = Some(extracted);
                        }
                    }
                    self.recalculate_present_value();
                    return Ok(());
                }
                // RELINQUISH_DEFAULT — network-writable only for the types
                // that select `rd_access: writable` (#270).
                define_value_object_commandable!(@rd_write self, property, value, $prop_to_pv, $rd_access);
                if let Some(result) =
                    common::write_out_of_service(&mut self.out_of_service, property, &value)
                {
                    return result;
                }
                if let Some(result) =
                    common::write_object_name(&mut self.name, property, &value)
                {
                    return result;
                }
                if let Some(result) =
                    common::write_description(&mut self.description, property, &value)
                {
                    return result;
                }
                Err(common::write_access_denied_error())
            }

            fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
                static PROPS: &[PropertyIdentifier] = &[
                    PropertyIdentifier::OBJECT_IDENTIFIER,
                    PropertyIdentifier::OBJECT_NAME,
                    PropertyIdentifier::DESCRIPTION,
                    PropertyIdentifier::OBJECT_TYPE,
                    PropertyIdentifier::PRESENT_VALUE,
                    PropertyIdentifier::STATUS_FLAGS,
                    PropertyIdentifier::OUT_OF_SERVICE,
                    PropertyIdentifier::RELIABILITY,
                    PropertyIdentifier::PRIORITY_ARRAY,
                    PropertyIdentifier::RELINQUISH_DEFAULT,
                ];
                let metadata = self.property_metadata();
                if metadata.is_empty() {
                    Cow::Borrowed(PROPS)
                } else {
                    crate::property_metadata::property_list_from_metadata(metadata.as_ref())
                }
            }

            fn supports_cov(&self) -> bool {
                true
            }

            define_value_object_commandable!(@is_writable $rd_access, $($property_metadata)?);
        }
    };

    (@property_metadata) => {
        Cow::Borrowed(&[])
    };
    (@property_metadata $metadata:expr) => {
        Cow::Borrowed($metadata)
    };

    // RELINQUISH_DEFAULT write arm for `rd_access: writable`: extract through
    // the shared closure, then reuse the validated setter (#270).
    (@rd_write $self:ident, $property:ident, $value:ident, $prop_to_pv:expr, writable) => {
        if $property == PropertyIdentifier::RELINQUISH_DEFAULT {
            let extracted = ($prop_to_pv)($value)?;
            return $self.set_relinquish_default(extracted);
        }
    };
    // `rd_access: readonly`: no arm — the default WRITE_ACCESS_DENIED at the
    // end of write_property stands (no current users).
    (@rd_write $self:ident, $property:ident, $value:ident, $prop_to_pv:expr, readonly) => {};

    // PICS writability mirrors the arms: common + commandable for every
    // commandable value type, RELINQUISH_DEFAULT only when the arm exists.
    (@is_writable writable,) => {
        fn is_writable_property(&self, property: PropertyIdentifier) -> bool {
            common::is_common_writable(property)
                || property == PropertyIdentifier::PRESENT_VALUE
                || property == PropertyIdentifier::PRIORITY_ARRAY
                || property == PropertyIdentifier::RELINQUISH_DEFAULT
        }
    };
    (@is_writable readonly,) => {
        fn is_writable_property(&self, property: PropertyIdentifier) -> bool {
            common::is_common_writable(property)
                || property == PropertyIdentifier::PRESENT_VALUE
                || property == PropertyIdentifier::PRIORITY_ARRAY
        }
    };
    (@is_writable $rd_access:ident, $metadata:expr) => {
        fn is_writable_property(&self, property: PropertyIdentifier) -> bool {
            crate::property_metadata::is_writable_in_metadata($metadata, property)
        }
    };

    // --- Internal helper arms ---

    // Recalculate for Copy types: use the common helper.
    (@recalc $self:ident, copy) => {
        $self.present_value = common::recalculate_from_priority_array(
            &$self.priority_array,
            $self.relinquish_default,
        );
    };
    // Recalculate for Clone (non-Copy) types.
    (@recalc $self:ident, clone) => {
        $self.present_value = $self
            .priority_array
            .iter()
            .find_map(|slot| slot.as_ref().cloned())
            .unwrap_or_else(|| $self.relinquish_default.clone());
    };

    // Read priority array for Copy types: use the common macro.
    (@read_pa $self:ident, $array_index:ident, $wrap:expr, copy) => {{
        common::read_priority_array!($self, $array_index, $wrap)
    }};
    // Read priority array for Clone (non-Copy) types.
    (@read_pa $self:ident, $array_index:ident, $wrap:expr, clone) => {{
        let wrap_fn = $wrap;
        match $array_index {
            None => {
                let elements = $self
                    .priority_array
                    .iter()
                    .map(|slot| match slot {
                        Some(v) => wrap_fn(v),
                        None => PropertyValue::Null,
                    })
                    .collect();
                Ok(PropertyValue::List(elements))
            }
            Some(0) => Ok(PropertyValue::Unsigned(16)),
            Some(idx) if (1..=16).contains(&idx) => {
                match &$self.priority_array[(idx - 1) as usize] {
                    Some(v) => Ok(wrap_fn(v)),
                    None => Ok(PropertyValue::Null),
                }
            }
            _ => Err(common::invalid_array_index_error()),
        }
    }};
}

// ---------------------------------------------------------------------------
// Macro: define_value_object! (non-commandable variant)
// ---------------------------------------------------------------------------

/// Generate a non-commandable value object type (simple read/write PV).
/// Currently unused — all value types are commandable.
#[allow(unused_macros)]
macro_rules! define_value_object_simple {
    (
        name: $struct_name:ident,
        doc: $doc:expr,
        object_type: $obj_type:expr,
        value_type: $val_type:ty,
        default_value: $default:expr,
        pv_to_property: $pv_to_prop:expr,
        property_to_pv: $prop_to_pv:expr
        $(,)?
    ) => {
        #[doc = $doc]
        pub struct $struct_name {
            oid: ObjectIdentifier,
            name: String,
            description: String,
            present_value: $val_type,
            out_of_service: bool,
            status_flags: StatusFlags,
            reliability: u32,
        }

        impl $struct_name {
            /// Create a new instance of this value object.
            pub fn new(instance: u32, name: impl Into<String>) -> Result<Self, Error> {
                let oid = ObjectIdentifier::new($obj_type, instance)?;
                Ok(Self {
                    oid,
                    name: name.into(),
                    description: String::new(),
                    present_value: $default,
                    out_of_service: false,
                    status_flags: StatusFlags::empty(),
                    reliability: 0,
                })
            }
        }

        impl BACnetObject for $struct_name {
            fn object_identifier(&self) -> ObjectIdentifier {
                self.oid
            }

            fn object_name(&self) -> &str {
                &self.name
            }

            fn read_property(
                &self,
                property: PropertyIdentifier,
                array_index: Option<u32>,
            ) -> Result<PropertyValue, Error> {
                if let Some(result) = read_common_properties!(self, property, array_index) {
                    return result;
                }
                match property {
                    p if p == PropertyIdentifier::OBJECT_TYPE => {
                        Ok(PropertyValue::Enumerated($obj_type.to_raw()))
                    }
                    p if p == PropertyIdentifier::PRESENT_VALUE => {
                        Ok(($pv_to_prop)(&self.present_value))
                    }
                    _ => Err(common::unknown_property_error()),
                }
            }

            fn write_property(
                &mut self,
                property: PropertyIdentifier,
                _array_index: Option<u32>,
                value: PropertyValue,
                _priority: Option<u8>,
            ) -> Result<(), Error> {
                if property == PropertyIdentifier::PRESENT_VALUE {
                    let extracted = ($prop_to_pv)(value)?;
                    self.present_value = extracted;
                    return Ok(());
                }
                if let Some(result) =
                    common::write_out_of_service(&mut self.out_of_service, property, &value)
                {
                    return result;
                }
                if let Some(result) = common::write_object_name(&mut self.name, property, &value) {
                    return result;
                }
                if let Some(result) =
                    common::write_description(&mut self.description, property, &value)
                {
                    return result;
                }
                Err(common::write_access_denied_error())
            }

            fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
                static PROPS: &[PropertyIdentifier] = &[
                    PropertyIdentifier::OBJECT_IDENTIFIER,
                    PropertyIdentifier::OBJECT_NAME,
                    PropertyIdentifier::DESCRIPTION,
                    PropertyIdentifier::OBJECT_TYPE,
                    PropertyIdentifier::PRESENT_VALUE,
                    PropertyIdentifier::STATUS_FLAGS,
                    PropertyIdentifier::OUT_OF_SERVICE,
                    PropertyIdentifier::RELIABILITY,
                ];
                Cow::Borrowed(PROPS)
            }

            fn supports_cov(&self) -> bool {
                true
            }
        }
    };
}

// ---------------------------------------------------------------------------
// Helper functions for value conversions
// ---------------------------------------------------------------------------

fn clone_string_to_pv(v: &str) -> PropertyValue {
    PropertyValue::CharacterString(v.to_owned())
}

fn clone_octetstring_to_pv(v: &[u8]) -> PropertyValue {
    PropertyValue::OctetString(v.to_owned())
}

fn clone_bitstring_to_pv(v: &(u8, Vec<u8>)) -> PropertyValue {
    PropertyValue::BitString {
        unused_bits: v.0,
        data: v.1.clone(),
    }
}

fn datetime_copy_to_pv(v: (Date, Time)) -> PropertyValue {
    PropertyValue::List(vec![PropertyValue::Date(v.0), PropertyValue::Time(v.1)])
}

fn datetime_to_pv(dt: &(Date, Time)) -> PropertyValue {
    PropertyValue::List(vec![PropertyValue::Date(dt.0), PropertyValue::Time(dt.1)])
}

fn pv_to_date(v: PropertyValue) -> Result<Date, Error> {
    if let PropertyValue::Date(d) = v {
        Ok(d)
    } else {
        Err(common::invalid_data_type_error())
    }
}

fn pv_to_time(v: PropertyValue) -> Result<Time, Error> {
    if let PropertyValue::Time(t) = v {
        Ok(t)
    } else {
        Err(common::invalid_data_type_error())
    }
}

fn pv_to_datetime(v: PropertyValue) -> Result<(Date, Time), Error> {
    if let PropertyValue::List(items) = v {
        if items.len() == 2 {
            let d = if let PropertyValue::Date(d) = &items[0] {
                *d
            } else {
                return Err(common::invalid_data_type_error());
            };
            let t = if let PropertyValue::Time(t) = &items[1] {
                *t
            } else {
                return Err(common::invalid_data_type_error());
            };
            Ok((d, t))
        } else {
            Err(common::invalid_data_type_error())
        }
    } else {
        Err(common::invalid_data_type_error())
    }
}

// ---------------------------------------------------------------------------
// 9 Commandable value objects
// ---------------------------------------------------------------------------

define_value_object_commandable! {
    name: IntegerValueObject,
    doc: "BACnet Integer Value object (type 45).",
    object_type: ObjectType::INTEGER_VALUE,
    value_type: i32,
    default_value: 0,
    pv_to_property: (|v: &i32| PropertyValue::Signed(*v)),
    property_to_pv: (|v: PropertyValue| -> Result<i32, Error> {
        if let PropertyValue::Signed(n) = v { Ok(n) }
        else { Err(common::invalid_data_type_error()) }
    }),
    pa_wrap: PropertyValue::Signed,
    rd_wrap: (|v: &i32| PropertyValue::Signed(*v)),
    rd_validate: (|_: &i32| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
}

define_value_object_commandable! {
    name: PositiveIntegerValueObject,
    doc: "BACnet Positive Integer Value object (type 48).",
    object_type: ObjectType::POSITIVE_INTEGER_VALUE,
    value_type: u64,
    default_value: 0,
    pv_to_property: (|v: &u64| PropertyValue::Unsigned(*v)),
    property_to_pv: (|v: PropertyValue| -> Result<u64, Error> {
        if let PropertyValue::Unsigned(n) = v { Ok(n) }
        else { Err(common::invalid_data_type_error()) }
    }),
    pa_wrap: PropertyValue::Unsigned,
    rd_wrap: (|v: &u64| PropertyValue::Unsigned(*v)),
    rd_validate: (|_: &u64| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
}

define_value_object_commandable! {
    name: LargeAnalogValueObject,
    doc: "BACnet Large Analog Value object (type 46).",
    object_type: ObjectType::LARGE_ANALOG_VALUE,
    value_type: f64,
    default_value: 0.0,
    pv_to_property: (|v: &f64| PropertyValue::Double(*v)),
    property_to_pv: (|v: PropertyValue| -> Result<f64, Error> {
        if let PropertyValue::Double(n) = v { Ok(n) }
        else { Err(common::invalid_data_type_error()) }
    }),
    pa_wrap: PropertyValue::Double,
    rd_wrap: (|v: &f64| PropertyValue::Double(*v)),
    rd_validate: (|v: &f64| -> Result<(), Error> {
        if v.is_finite() {
            Ok(())
        } else {
            Err(common::value_out_of_range_error())
        }
    }),
    rd_access: writable,
    copy_type: copy,
}

define_value_object_commandable! {
    name: CharacterStringValueObject,
    doc: "BACnet CharacterString Value object (type 40).",
    object_type: ObjectType::CHARACTERSTRING_VALUE,
    value_type: String,
    default_value: String::new(),
    pv_to_property: (|v: &String| PropertyValue::CharacterString(v.clone())),
    property_to_pv: (|v: PropertyValue| -> Result<String, Error> {
        if let PropertyValue::CharacterString(s) = v { Ok(s) }
        else { Err(common::invalid_data_type_error()) }
    }),
    pa_wrap: clone_string_to_pv,
    rd_wrap: (|v: &String| PropertyValue::CharacterString(v.clone())),
    rd_validate: (|_: &String| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: clone,
}

define_value_object_commandable! {
    name: OctetStringValueObject,
    doc: "BACnet OctetString Value object (type 47).",
    object_type: ObjectType::OCTETSTRING_VALUE,
    value_type: Vec<u8>,
    default_value: Vec::new(),
    pv_to_property: (|v: &Vec<u8>| PropertyValue::OctetString(v.clone())),
    property_to_pv: (|v: PropertyValue| -> Result<Vec<u8>, Error> {
        if let PropertyValue::OctetString(b) = v { Ok(b) }
        else { Err(common::invalid_data_type_error()) }
    }),
    pa_wrap: clone_octetstring_to_pv,
    rd_wrap: (|v: &Vec<u8>| PropertyValue::OctetString(v.clone())),
    rd_validate: (|_: &Vec<u8>| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: clone,
}

define_value_object_commandable! {
    name: BitStringValueObject,
    doc: "BACnet BitString Value object (type 39).",
    object_type: ObjectType::BITSTRING_VALUE,
    value_type: (u8, Vec<u8>),
    default_value: (0, Vec::new()),
    pv_to_property: (|v: &(u8, Vec<u8>)| PropertyValue::BitString {
        unused_bits: v.0,
        data: v.1.clone(),
    }),
    property_to_pv: (|v: PropertyValue| -> Result<(u8, Vec<u8>), Error> {
        if let PropertyValue::BitString { unused_bits, data } = v { Ok((unused_bits, data)) }
        else { Err(common::invalid_data_type_error()) }
    }),
    pa_wrap: clone_bitstring_to_pv,
    rd_wrap: (|v: &(u8, Vec<u8>)| PropertyValue::BitString {
        unused_bits: v.0,
        data: v.1.clone(),
    }),
    rd_validate: (|_: &(u8, Vec<u8>)| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: clone,
}

define_value_object_commandable! {
    name: DateValueObject,
    doc: "BACnet Date Value object (type 42).",
    object_type: ObjectType::DATE_VALUE,
    value_type: Date,
    default_value: Date { year: 0xFF, month: 0xFF, day: 0xFF, day_of_week: 0xFF },
    pv_to_property: (|v: &Date| PropertyValue::Date(*v)),
    property_to_pv: pv_to_date,
    pa_wrap: PropertyValue::Date,
    rd_wrap: (|v: &Date| PropertyValue::Date(*v)),
    rd_validate: (|_: &Date| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
}

const TIME_VALUE_PROPERTY_METADATA: &[PropertyMetadata] = &[
    PropertyMetadata::new(
        PropertyIdentifier::OBJECT_IDENTIFIER,
        PropertyConformance::RequiredRead,
        None,
        PropertyWriteCapability::ReadOnly,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::OBJECT_NAME,
        PropertyConformance::RequiredRead,
        None,
        PropertyWriteCapability::Always,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::DESCRIPTION,
        PropertyConformance::Optional,
        None,
        PropertyWriteCapability::Always,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::OBJECT_TYPE,
        PropertyConformance::RequiredRead,
        None,
        PropertyWriteCapability::ReadOnly,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::PRESENT_VALUE,
        PropertyConformance::RequiredRead,
        None,
        PropertyWriteCapability::Always,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::STATUS_FLAGS,
        PropertyConformance::RequiredRead,
        None,
        PropertyWriteCapability::ReadOnly,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::OUT_OF_SERVICE,
        PropertyConformance::Optional,
        None,
        PropertyWriteCapability::Always,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::RELIABILITY,
        PropertyConformance::Optional,
        None,
        PropertyWriteCapability::ReadOnly,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::PRIORITY_ARRAY,
        PropertyConformance::Optional,
        Some(PropertyPresenceCondition::Commandable),
        PropertyWriteCapability::Always,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::RELINQUISH_DEFAULT,
        PropertyConformance::Optional,
        Some(PropertyPresenceCondition::Commandable),
        PropertyWriteCapability::Always,
    ),
    PropertyMetadata::new(
        PropertyIdentifier::PROPERTY_LIST,
        PropertyConformance::RequiredRead,
        None,
        PropertyWriteCapability::ReadOnly,
    ),
];

define_value_object_commandable! {
    name: TimeValueObject,
    doc: "BACnet Time Value object (type 50).",
    object_type: ObjectType::TIME_VALUE,
    value_type: Time,
    default_value: Time { hour: 0xFF, minute: 0xFF, second: 0xFF, hundredths: 0xFF },
    pv_to_property: (|v: &Time| PropertyValue::Time(*v)),
    property_to_pv: pv_to_time,
    pa_wrap: PropertyValue::Time,
    rd_wrap: (|v: &Time| PropertyValue::Time(*v)),
    rd_validate: (|_: &Time| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
    property_metadata: TIME_VALUE_PROPERTY_METADATA,
}

define_value_object_commandable! {
    name: DateTimeValueObject,
    doc: "BACnet DateTime Value object (type 44).",
    object_type: ObjectType::DATETIME_VALUE,
    value_type: (Date, Time),
    default_value: (
        Date { year: 0xFF, month: 0xFF, day: 0xFF, day_of_week: 0xFF },
        Time { hour: 0xFF, minute: 0xFF, second: 0xFF, hundredths: 0xFF },
    ),
    pv_to_property: (|v: &(Date, Time)| datetime_to_pv(v)),
    property_to_pv: pv_to_datetime,
    pa_wrap: datetime_copy_to_pv,
    rd_wrap: (|v: &(Date, Time)| datetime_to_pv(v)),
    rd_validate: (|_: &(Date, Time)| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
}

// ---------------------------------------------------------------------------
// 3 Commandable pattern value objects (with priority array)
// ---------------------------------------------------------------------------

define_value_object_commandable! {
    name: DatePatternValueObject,
    doc: "BACnet Date Pattern Value object (type 41).",
    object_type: ObjectType::DATEPATTERN_VALUE,
    value_type: Date,
    default_value: Date { year: 0xFF, month: 0xFF, day: 0xFF, day_of_week: 0xFF },
    pv_to_property: (|v: &Date| PropertyValue::Date(*v)),
    property_to_pv: pv_to_date,
    pa_wrap: PropertyValue::Date,
    rd_wrap: (|v: &Date| PropertyValue::Date(*v)),
    rd_validate: (|_: &Date| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
}

define_value_object_commandable! {
    name: TimePatternValueObject,
    doc: "BACnet Time Pattern Value object (type 49).",
    object_type: ObjectType::TIMEPATTERN_VALUE,
    value_type: Time,
    default_value: Time { hour: 0xFF, minute: 0xFF, second: 0xFF, hundredths: 0xFF },
    pv_to_property: (|v: &Time| PropertyValue::Time(*v)),
    property_to_pv: pv_to_time,
    pa_wrap: PropertyValue::Time,
    rd_wrap: (|v: &Time| PropertyValue::Time(*v)),
    rd_validate: (|_: &Time| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
}

define_value_object_commandable! {
    name: DateTimePatternValueObject,
    doc: "BACnet DateTime Pattern Value object (type 43).",
    object_type: ObjectType::DATETIMEPATTERN_VALUE,
    value_type: (Date, Time),
    default_value: (
        Date { year: 0xFF, month: 0xFF, day: 0xFF, day_of_week: 0xFF },
        Time { hour: 0xFF, minute: 0xFF, second: 0xFF, hundredths: 0xFF },
    ),
    pv_to_property: (|v: &(Date, Time)| datetime_to_pv(v)),
    property_to_pv: pv_to_datetime,
    pa_wrap: datetime_copy_to_pv,
    rd_wrap: (|v: &(Date, Time)| datetime_to_pv(v)),
    rd_validate: (|_: &(Date, Time)| -> Result<(), Error> { Ok(()) }),
    rd_access: writable,
    copy_type: copy,
}

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

#[cfg(test)]
mod tests;