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
//! Loop (type 12) object per ASHRAE 135-2020 Clause 12.19.
//!
//! PID control loop. The application is responsible for running the PID
//! algorithm; this object stores configuration and current output.

use bacnet_types::constructed::BACnetObjectPropertyReference;
use bacnet_types::enums::{ErrorClass, ErrorCode, ObjectType, PropertyIdentifier};
use bacnet_types::error::Error;
use bacnet_types::primitives::{ObjectIdentifier, PropertyValue, StatusFlags};
use std::borrow::Cow;

use crate::common::{self, read_property_list_property};
use crate::traits::BACnetObject;

/// BACnet Loop object — PID control loop configuration and state.
pub struct LoopObject {
    oid: ObjectIdentifier,
    name: String,
    description: String,
    present_value: f32,
    setpoint: f32,
    proportional_constant: f32,
    integral_constant: f32,
    derivative_constant: f32,
    output_units: u32,
    update_interval: u32,
    out_of_service: bool,
    reliability: u32,
    /// Evaluated Reliability saved while a client simulation owns the property
    /// (Out_Of_Service TRUE); restored on the return to service.
    reliability_before_out_of_service: Option<u32>,
    status_flags: StatusFlags,
    controlled_variable_reference: Option<BACnetObjectPropertyReference>,
    manipulated_variable_reference: Option<BACnetObjectPropertyReference>,
    setpoint_reference: Option<BACnetObjectPropertyReference>,
}

impl LoopObject {
    pub fn new(instance: u32, name: impl Into<String>, output_units: u32) -> Result<Self, Error> {
        let oid = ObjectIdentifier::new(ObjectType::LOOP, instance)?;
        Ok(Self {
            oid,
            name: name.into(),
            description: String::new(),
            present_value: 0.0,
            setpoint: 0.0,
            proportional_constant: 1.0,
            integral_constant: 0.0,
            derivative_constant: 0.0,
            output_units,
            update_interval: 1000, // milliseconds
            out_of_service: false,
            reliability: 0,
            reliability_before_out_of_service: None,
            status_flags: StatusFlags::empty(),
            controlled_variable_reference: None,
            manipulated_variable_reference: None,
            setpoint_reference: None,
        })
    }

    /// Application sets the current output value after PID computation.
    pub fn set_present_value(&mut self, value: f32) {
        self.present_value = value;
    }

    /// Set the description string.
    pub fn set_description(&mut self, desc: impl Into<String>) {
        self.description = desc.into();
    }

    /// Set the controlled variable reference (the object whose present value is
    /// being controlled by this loop).
    pub fn set_controlled_variable_reference(&mut self, r: BACnetObjectPropertyReference) {
        self.controlled_variable_reference = Some(r);
    }

    /// Set the manipulated variable reference (the object that the loop output
    /// drives to achieve the setpoint).
    pub fn set_manipulated_variable_reference(&mut self, r: BACnetObjectPropertyReference) {
        self.manipulated_variable_reference = Some(r);
    }

    /// Set the setpoint reference (an alternative way to supply the setpoint
    /// from another object's property instead of the inline `SETPOINT` value).
    pub fn set_setpoint_reference(&mut self, r: BACnetObjectPropertyReference) {
        self.setpoint_reference = Some(r);
    }
}

impl BACnetObject for LoopObject {
    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> {
        match property {
            p if p == PropertyIdentifier::OBJECT_IDENTIFIER => {
                Ok(PropertyValue::ObjectIdentifier(self.oid))
            }
            p if p == PropertyIdentifier::OBJECT_NAME => {
                Ok(PropertyValue::CharacterString(self.name.clone()))
            }
            p if p == PropertyIdentifier::DESCRIPTION => {
                Ok(PropertyValue::CharacterString(self.description.clone()))
            }
            p if p == PropertyIdentifier::OBJECT_TYPE => {
                Ok(PropertyValue::Enumerated(ObjectType::LOOP.to_raw()))
            }
            p if p == PropertyIdentifier::PRESENT_VALUE => {
                Ok(PropertyValue::Real(self.present_value))
            }
            p if p == PropertyIdentifier::SETPOINT => Ok(PropertyValue::Real(self.setpoint)),
            p if p == PropertyIdentifier::PROPORTIONAL_CONSTANT => {
                Ok(PropertyValue::Real(self.proportional_constant))
            }
            p if p == PropertyIdentifier::INTEGRAL_CONSTANT => {
                Ok(PropertyValue::Real(self.integral_constant))
            }
            p if p == PropertyIdentifier::DERIVATIVE_CONSTANT => {
                Ok(PropertyValue::Real(self.derivative_constant))
            }
            p if p == PropertyIdentifier::OUTPUT_UNITS => {
                Ok(PropertyValue::Enumerated(self.output_units))
            }
            p if p == PropertyIdentifier::UPDATE_INTERVAL => {
                Ok(PropertyValue::Unsigned(self.update_interval as u64))
            }
            p if p == PropertyIdentifier::STATUS_FLAGS => Ok(PropertyValue::BitString {
                unused_bits: 4,
                data: vec![self.status_flags.bits() << 4],
            }),
            p if p == PropertyIdentifier::EVENT_STATE => Ok(PropertyValue::Enumerated(0)),
            p if p == PropertyIdentifier::RELIABILITY => {
                Ok(PropertyValue::Enumerated(self.reliability))
            }
            p if p == PropertyIdentifier::OUT_OF_SERVICE => {
                Ok(PropertyValue::Boolean(self.out_of_service))
            }
            p if p == PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE => Ok(
                crate::reference::reference_read_value(&self.controlled_variable_reference),
            ),
            p if p == PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE => Ok(
                crate::reference::reference_read_value(&self.manipulated_variable_reference),
            ),
            p if p == PropertyIdentifier::SETPOINT_REFERENCE => Ok(
                crate::reference::reference_read_value(&self.setpoint_reference),
            ),
            p if p == PropertyIdentifier::PROPERTY_LIST => {
                read_property_list_property(&self.property_list(), array_index)
            }
            _ => Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::UNKNOWN_PROPERTY.to_raw() as u32,
            }),
        }
    }

    fn write_property(
        &mut self,
        property: PropertyIdentifier,
        _array_index: Option<u32>,
        value: PropertyValue,
        _priority: Option<u8>,
    ) -> Result<(), Error> {
        if let Some(result) = common::write_out_of_service_with_reliability_restore(
            &mut self.out_of_service,
            &mut self.reliability,
            &mut self.reliability_before_out_of_service,
            property,
            &value,
        ) {
            return result;
        }
        match property {
            p if p == PropertyIdentifier::SETPOINT => {
                if let PropertyValue::Real(v) = value {
                    common::reject_non_finite(v)?;
                    self.setpoint = v;
                    return Ok(());
                }
                Err(Error::Protocol {
                    class: ErrorClass::PROPERTY.to_raw() as u32,
                    code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
                })
            }
            p if p == PropertyIdentifier::PROPORTIONAL_CONSTANT => {
                if let PropertyValue::Real(v) = value {
                    common::reject_non_finite(v)?;
                    self.proportional_constant = v;
                    return Ok(());
                }
                Err(Error::Protocol {
                    class: ErrorClass::PROPERTY.to_raw() as u32,
                    code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
                })
            }
            p if p == PropertyIdentifier::INTEGRAL_CONSTANT => {
                if let PropertyValue::Real(v) = value {
                    common::reject_non_finite(v)?;
                    self.integral_constant = v;
                    return Ok(());
                }
                Err(Error::Protocol {
                    class: ErrorClass::PROPERTY.to_raw() as u32,
                    code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
                })
            }
            p if p == PropertyIdentifier::DERIVATIVE_CONSTANT => {
                if let PropertyValue::Real(v) = value {
                    common::reject_non_finite(v)?;
                    self.derivative_constant = v;
                    return Ok(());
                }
                Err(Error::Protocol {
                    class: ErrorClass::PROPERTY.to_raw() as u32,
                    code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
                })
            }
            p if p == PropertyIdentifier::UPDATE_INTERVAL => {
                if let PropertyValue::Unsigned(v) = value {
                    self.update_interval = common::u64_to_u32(v)?;
                    return Ok(());
                }
                Err(Error::Protocol {
                    class: ErrorClass::PROPERTY.to_raw() as u32,
                    code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
                })
            }
            // Clause 12.17 Table 12-20 lists Reliability O7, whose footnote reads
            // "These properties are required to be writable when Out_Of_Service
            // is TRUE", and the Out_Of_Service property text then narrows the grant:
            // while TRUE, "the Present_Value property and the Reliability property,
            // if present and capable of taking on values other than
            // NO_FAULT_DETECTED, shall be writable to allow simulating specific
            // conditions or for testing purposes". In service the property is owned
            // by the algorithm, so a network write is refused here; the internal
            // evaluator route is `set_reliability_internal` with the complementary
            // guard, and Out_Of_Service saves/restores the evaluated value (handled
            // above the match).
            p if p == PropertyIdentifier::RELIABILITY => {
                if !self.out_of_service {
                    return Err(common::write_access_denied_error());
                }
                if let PropertyValue::Enumerated(v) = value {
                    if !common::is_reliability_value_valid(v) {
                        return Err(common::value_out_of_range_error());
                    }
                    self.reliability = v;
                    return Ok(());
                }
                Err(Error::Protocol {
                    class: ErrorClass::PROPERTY.to_raw() as u32,
                    code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
                })
            }
            p if p == PropertyIdentifier::DESCRIPTION => {
                if let PropertyValue::CharacterString(s) = value {
                    self.description = s;
                    return Ok(());
                }
                Err(Error::Protocol {
                    class: ErrorClass::PROPERTY.to_raw() as u32,
                    code: ErrorCode::INVALID_DATA_TYPE.to_raw() as u32,
                })
            }
            // Clause 12.17 / Clause 21 BACnetObjectPropertyReference: the
            // write value decodes via the shared arm helper — legacy local
            // List and framed network (context-tagged members) forms both
            // land strictly; see reference.rs.
            p if p == PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE => {
                self.controlled_variable_reference = crate::reference::decode_reference_write(
                    &value,
                    crate::reference::ReferenceFrame::Bare,
                )?;
                Ok(())
            }
            p if p == PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE => {
                self.manipulated_variable_reference = crate::reference::decode_reference_write(
                    &value,
                    crate::reference::ReferenceFrame::Bare,
                )?;
                Ok(())
            }
            // Setpoint_Reference is typed BACnetSetpointReference (Clause
            // 12.17): the reference may additionally arrive inside the
            // production's opening/closing tag [0] frame on the wire.
            p if p == PropertyIdentifier::SETPOINT_REFERENCE => {
                self.setpoint_reference = crate::reference::decode_reference_write(
                    &value,
                    crate::reference::ReferenceFrame::Setpoint,
                )?;
                Ok(())
            }
            _ => Err(Error::Protocol {
                class: ErrorClass::PROPERTY.to_raw() as u32,
                code: ErrorCode::WRITE_ACCESS_DENIED.to_raw() as u32,
            }),
        }
    }

    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::SETPOINT,
            PropertyIdentifier::PROPORTIONAL_CONSTANT,
            PropertyIdentifier::INTEGRAL_CONSTANT,
            PropertyIdentifier::DERIVATIVE_CONSTANT,
            PropertyIdentifier::OUTPUT_UNITS,
            PropertyIdentifier::UPDATE_INTERVAL,
            PropertyIdentifier::STATUS_FLAGS,
            PropertyIdentifier::EVENT_STATE,
            PropertyIdentifier::RELIABILITY,
            PropertyIdentifier::OUT_OF_SERVICE,
            PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
            PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE,
            PropertyIdentifier::SETPOINT_REFERENCE,
        ];
        Cow::Borrowed(PROPS)
    }

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

    fn set_reliability_internal(&mut self, reliability: u32) -> Result<(), Error> {
        // While Out_Of_Service is TRUE the client owns the simulated value;
        // an internal write would clobber the simulation (Clause 12.17
        // Out_Of_Service paragraph: Reliability is "decoupled from the
        // algorithm"), so it is refused until the object returns to service.
        if self.out_of_service {
            return Err(common::write_access_denied_error());
        }
        if !common::is_reliability_value_valid(reliability) {
            return Err(common::value_out_of_range_error());
        }
        self.reliability = reliability;
        Ok(())
    }

    fn is_writable_property(&self, property: PropertyIdentifier) -> bool {
        // Mirrors the LoopObject `write_property` arms so the PICS and
        // runtime dispatch share one truth source.
        matches!(
            property,
            PropertyIdentifier::SETPOINT
                | PropertyIdentifier::PROPORTIONAL_CONSTANT
                | PropertyIdentifier::INTEGRAL_CONSTANT
                | PropertyIdentifier::DERIVATIVE_CONSTANT
                | PropertyIdentifier::UPDATE_INTERVAL
                | PropertyIdentifier::RELIABILITY
                | PropertyIdentifier::OUT_OF_SERVICE
                | PropertyIdentifier::DESCRIPTION
                | PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE
                | PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE
                | PropertyIdentifier::SETPOINT_REFERENCE
        )
    }
}

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

    #[test]
    fn loop_read_defaults() {
        let lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        assert_eq!(
            lo.read_property(PropertyIdentifier::PRESENT_VALUE, None)
                .unwrap(),
            PropertyValue::Real(0.0)
        );
        assert_eq!(
            lo.read_property(PropertyIdentifier::SETPOINT, None)
                .unwrap(),
            PropertyValue::Real(0.0)
        );
        assert_eq!(
            lo.read_property(PropertyIdentifier::PROPORTIONAL_CONSTANT, None)
                .unwrap(),
            PropertyValue::Real(1.0)
        );
    }

    #[test]
    fn loop_write_pid_constants() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        lo.write_property(
            PropertyIdentifier::SETPOINT,
            None,
            PropertyValue::Real(72.0),
            None,
        )
        .unwrap();
        lo.write_property(
            PropertyIdentifier::PROPORTIONAL_CONSTANT,
            None,
            PropertyValue::Real(2.5),
            None,
        )
        .unwrap();
        lo.write_property(
            PropertyIdentifier::INTEGRAL_CONSTANT,
            None,
            PropertyValue::Real(0.1),
            None,
        )
        .unwrap();
        lo.write_property(
            PropertyIdentifier::DERIVATIVE_CONSTANT,
            None,
            PropertyValue::Real(0.05),
            None,
        )
        .unwrap();

        assert_eq!(
            lo.read_property(PropertyIdentifier::SETPOINT, None)
                .unwrap(),
            PropertyValue::Real(72.0)
        );
        assert_eq!(
            lo.read_property(PropertyIdentifier::PROPORTIONAL_CONSTANT, None)
                .unwrap(),
            PropertyValue::Real(2.5)
        );
        assert_eq!(
            lo.read_property(PropertyIdentifier::INTEGRAL_CONSTANT, None)
                .unwrap(),
            PropertyValue::Real(0.1)
        );
        assert_eq!(
            lo.read_property(PropertyIdentifier::DERIVATIVE_CONSTANT, None)
                .unwrap(),
            PropertyValue::Real(0.05)
        );
    }

    #[test]
    fn loop_set_present_value() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        lo.set_present_value(55.0);
        assert_eq!(
            lo.read_property(PropertyIdentifier::PRESENT_VALUE, None)
                .unwrap(),
            PropertyValue::Real(55.0)
        );
    }

    #[test]
    fn loop_read_object_type() {
        let lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let val = lo
            .read_property(PropertyIdentifier::OBJECT_TYPE, None)
            .unwrap();
        assert_eq!(val, PropertyValue::Enumerated(ObjectType::LOOP.to_raw()));
    }

    #[test]
    fn loop_write_wrong_type_rejected() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let result = lo.write_property(
            PropertyIdentifier::SETPOINT,
            None,
            PropertyValue::Unsigned(72),
            None,
        );
        assert!(result.is_err());
    }

    // --- Property reference tests ---

    #[test]
    fn loop_references_default_to_null() {
        let lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        assert_eq!(
            lo.read_property(PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE, None)
                .unwrap(),
            PropertyValue::Null
        );
        assert_eq!(
            lo.read_property(PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE, None)
                .unwrap(),
            PropertyValue::Null
        );
        assert_eq!(
            lo.read_property(PropertyIdentifier::SETPOINT_REFERENCE, None)
                .unwrap(),
            PropertyValue::Null
        );
    }

    #[test]
    fn loop_set_references_read_back() {
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 5).unwrap();
        let prop_raw = PropertyIdentifier::PRESENT_VALUE.to_raw();
        let expect = PropertyValue::List(vec![
            PropertyValue::ObjectIdentifier(oid),
            PropertyValue::Enumerated(prop_raw),
        ]);
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        lo.set_controlled_variable_reference(BACnetObjectPropertyReference::new(oid, prop_raw));
        lo.set_manipulated_variable_reference(BACnetObjectPropertyReference::new(oid, prop_raw));
        lo.set_setpoint_reference(BACnetObjectPropertyReference::new(oid, prop_raw));
        for property in [
            PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
            PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE,
            PropertyIdentifier::SETPOINT_REFERENCE,
        ] {
            assert_eq!(lo.read_property(property, None).unwrap(), expect);
        }
    }

    #[test]
    fn loop_references_in_property_list() {
        let lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let list = lo.property_list();
        assert!(list.contains(&PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE));
        assert!(list.contains(&PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE));
        assert!(list.contains(&PropertyIdentifier::SETPOINT_REFERENCE));
    }

    #[test]
    fn loop_write_reference_via_write_property() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 7).unwrap();
        let prop_raw = PropertyIdentifier::PRESENT_VALUE.to_raw();

        lo.write_property(
            PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
            None,
            PropertyValue::List(vec![
                PropertyValue::ObjectIdentifier(oid),
                PropertyValue::Enumerated(prop_raw),
            ]),
            None,
        )
        .unwrap();

        assert_eq!(
            lo.read_property(PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE, None)
                .unwrap(),
            PropertyValue::List(vec![
                PropertyValue::ObjectIdentifier(oid),
                PropertyValue::Enumerated(prop_raw),
            ])
        );
    }

    #[test]
    fn loop_write_null_clears_reference() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 1).unwrap();
        lo.set_controlled_variable_reference(BACnetObjectPropertyReference::new(
            oid,
            PropertyIdentifier::PRESENT_VALUE.to_raw(),
        ));

        // Verify it is set
        assert_ne!(
            lo.read_property(PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE, None)
                .unwrap(),
            PropertyValue::Null
        );

        // Write Null to clear
        lo.write_property(
            PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
            None,
            PropertyValue::Null,
            None,
        )
        .unwrap();

        assert_eq!(
            lo.read_property(PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE, None)
                .unwrap(),
            PropertyValue::Null
        );
    }

    #[test]
    fn loop_write_reference_wrong_type_rejected() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let result = lo.write_property(
            PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
            None,
            PropertyValue::Unsigned(42),
            None,
        );
        assert!(result.is_err());
    }

    // --- #182: framed (context-tagged) reference writes ---

    fn framed_reference(r: &BACnetObjectPropertyReference) -> PropertyValue {
        let mut buf = bytes::BytesMut::new();
        bacnet_encoding::constructed::encode_object_property_reference(&mut buf, r);
        PropertyValue::ApplicationData(buf.to_vec())
    }

    #[test]
    fn loop_write_framed_indexed_reference_reads_back_with_index() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 7).unwrap();
        let r = BACnetObjectPropertyReference::new_indexed(
            oid,
            PropertyIdentifier::PRESENT_VALUE.to_raw(),
            3,
        );
        lo.write_property(
            PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
            None,
            framed_reference(&r),
            None,
        )
        .unwrap();
        // The optional array-index member is carried through to the read form.
        assert_eq!(
            lo.read_property(PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE, None)
                .unwrap(),
            PropertyValue::List(vec![
                PropertyValue::ObjectIdentifier(oid),
                PropertyValue::Enumerated(PropertyIdentifier::PRESENT_VALUE.to_raw()),
                PropertyValue::Unsigned(3),
            ])
        );
    }

    #[test]
    fn loop_write_setpoint_reference_accepts_bacnetsetpointreference_frame() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_VALUE, 10).unwrap();
        let r = BACnetObjectPropertyReference::new(oid, PropertyIdentifier::PRESENT_VALUE.to_raw());
        let mut buf = bytes::BytesMut::new();
        bacnet_encoding::constructed::encode_setpoint_reference(&mut buf, &r);
        lo.write_property(
            PropertyIdentifier::SETPOINT_REFERENCE,
            None,
            PropertyValue::ApplicationData(buf.to_vec()),
            None,
        )
        .unwrap();
        assert_eq!(
            lo.read_property(PropertyIdentifier::SETPOINT_REFERENCE, None)
                .unwrap(),
            PropertyValue::List(vec![
                PropertyValue::ObjectIdentifier(oid),
                PropertyValue::Enumerated(PropertyIdentifier::PRESENT_VALUE.to_raw()),
            ])
        );
    }

    #[test]
    fn loop_write_device_qualified_reference_rejected_and_preserves() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 7).unwrap();
        let prop_raw = PropertyIdentifier::PRESENT_VALUE.to_raw();
        lo.set_controlled_variable_reference(BACnetObjectPropertyReference::new(oid, prop_raw));
        // [0] oid / [1] prop / [3] device: device qualification is not part of
        // the Loop reference production — INVALID_DATA_ENCODING, no change.
        let mut buf = bytes::BytesMut::new();
        bacnet_encoding::constructed::encode_object_property_reference(
            &mut buf,
            &BACnetObjectPropertyReference::new(oid, prop_raw),
        );
        bacnet_encoding::primitives::encode_ctx_object_id(
            &mut buf,
            3,
            &ObjectIdentifier::new(ObjectType::DEVICE, 77).unwrap(),
        );
        let err = lo
            .write_property(
                PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
                None,
                PropertyValue::ApplicationData(buf.to_vec()),
                None,
            )
            .unwrap_err();
        match err {
            Error::Protocol { class, code } => {
                assert_eq!(class, ErrorClass::PROPERTY.to_raw() as u32);
                assert_eq!(code, ErrorCode::INVALID_DATA_ENCODING.to_raw() as u32);
            }
            other => panic!("expected PROPERTY/INVALID_DATA_ENCODING, got {other:?}"),
        }
        assert_eq!(
            lo.read_property(PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE, None)
                .unwrap(),
            PropertyValue::List(vec![
                PropertyValue::ObjectIdentifier(oid),
                PropertyValue::Enumerated(prop_raw),
            ])
        );
    }

    #[test]
    fn loop_write_empty_setpoint_frame_clears_reference() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_VALUE, 10).unwrap();
        let r = BACnetObjectPropertyReference::new(oid, PropertyIdentifier::PRESENT_VALUE.to_raw());
        let mut buf = bytes::BytesMut::new();
        bacnet_encoding::constructed::encode_setpoint_reference(&mut buf, &r);
        lo.write_property(
            PropertyIdentifier::SETPOINT_REFERENCE,
            None,
            PropertyValue::ApplicationData(buf.to_vec()),
            None,
        )
        .unwrap();
        assert_ne!(
            lo.read_property(PropertyIdentifier::SETPOINT_REFERENCE, None)
                .unwrap(),
            PropertyValue::Null
        );

        // 0x0E 0x0F: BACnetSetpointReference with its OPTIONAL member absent —
        // Clause 12.17 defines the absence as "fixed setpoint", so a
        // conformant peer clearing the reference this way must be accepted,
        // exactly like a Null write (pinned over the wire in the server's
        // `reference_writes` tests).
        lo.write_property(
            PropertyIdentifier::SETPOINT_REFERENCE,
            None,
            PropertyValue::ApplicationData(vec![0x0E, 0x0F]),
            None,
        )
        .unwrap();
        assert_eq!(
            lo.read_property(PropertyIdentifier::SETPOINT_REFERENCE, None)
                .unwrap(),
            PropertyValue::Null
        );
    }

    #[test]
    fn loop_write_local_list_with_index_still_accepted() {
        let mut lo = LoopObject::new(1, "LOOP-1", 62).unwrap();
        let oid = ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 7).unwrap();
        let prop_raw = PropertyIdentifier::PRESENT_VALUE.to_raw();
        lo.write_property(
            PropertyIdentifier::SETPOINT_REFERENCE,
            None,
            PropertyValue::List(vec![
                PropertyValue::ObjectIdentifier(oid),
                PropertyValue::Enumerated(prop_raw),
                PropertyValue::Unsigned(9),
            ]),
            None,
        )
        .unwrap();
        assert_eq!(
            lo.read_property(PropertyIdentifier::SETPOINT_REFERENCE, None)
                .unwrap(),
            PropertyValue::List(vec![
                PropertyValue::ObjectIdentifier(oid),
                PropertyValue::Enumerated(prop_raw),
                PropertyValue::Unsigned(9),
            ])
        );
    }
}