bacnet-server 0.15.0

BACnet server: APDU dispatch and service handlers
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
//! Array-index gating across the object-access services (#190, #260).
//!
//! Every service that carries a `property_array_index` — ReadProperty,
//! ReadPropertyMultiple, WriteProperty, WritePropertyMultiple — gates the
//! index on the object's `is_array_property` classification and rejects an
//! index on a BACnetLIST property with PROPERTY / PROPERTY_IS_NOT_AN_ARRAY
//! (Clause 15.5.1.3 / 15.9.1.3; Clause 12.1.5.2 makes ReadRange the only
//! positional access to a BACnetLIST). Properties that are true BACnetARRAY
//! datatypes (Clause 12.1.5.1) pass the gate unchanged.

use super::*;
use bacnet_objects::analog::{AnalogInputObject, AnalogOutputObject};
use bacnet_objects::command::CommandObject;
use bacnet_objects::device::{DeviceConfig, DeviceObject};
use bacnet_objects::event_log::EventLogObject;
use bacnet_objects::group::{GlobalGroupObject, GroupObject, StructuredViewObject};
use bacnet_objects::multistate::MultiStateInputObject;
use bacnet_objects::notification_class::NotificationClass;
use bacnet_objects::schedule::{CalendarObject, ScheduleObject};
use bacnet_objects::staging::{StagingConfig, StagingObject};
use bacnet_objects::value_types::CharacterStringValueObject;
use bacnet_services::common::BACnetPropertyValue;
use bacnet_services::wpm::WriteAccessSpecification;
use bacnet_types::constructed::{BACnetDeviceObjectReference, BACnetStageLimitValue};
use bacnet_types::enums::EngineeringUnits;
use bacnet_types::error::RemoteError;

fn oid(object_type: ObjectType, instance: u32) -> ObjectIdentifier {
    ObjectIdentifier::new(object_type, instance).unwrap()
}

fn staging(instance: u32, name: &str) -> StagingObject {
    StagingObject::new(
        instance,
        name,
        StagingConfig {
            present_value: 0.0,
            min_present_value: -1.0,
            units: EngineeringUnits::DEGREES_CELSIUS,
            priority_for_writing: 8,
            stages: vec![
                BACnetStageLimitValue {
                    limit: 1.0,
                    values: vec![false],
                    deadband: 0.0,
                },
                BACnetStageLimitValue {
                    limit: 2.0,
                    values: vec![false],
                    deadband: 0.0,
                },
                BACnetStageLimitValue {
                    limit: 3.0,
                    values: vec![false],
                    deadband: 0.0,
                },
            ],
            target_references: vec![BACnetDeviceObjectReference {
                device_identifier: None,
                object_identifier: oid(ObjectType::BINARY_OUTPUT, ObjectIdentifier::MAX_INSTANCE),
            }],
            stage_names: Some(vec!["Low".into(), "Middle".into(), "High".into()]),
        },
    )
    .unwrap()
}

/// Database holding one instance of every object type the matrix touches.
fn gating_db() -> ObjectDatabase {
    let mut db = ObjectDatabase::new();

    let mut device = DeviceObject::new(DeviceConfig {
        identity: bacnet_objects::DeviceIdentity::default().with_name("GateDevice"),
        ..Default::default()
    })
    .unwrap();
    // A deterministic OBJECT_LIST: [device, AI-1].
    device.set_object_list(vec![
        oid(ObjectType::DEVICE, 1),
        oid(ObjectType::ANALOG_INPUT, 1),
    ]);
    db.add(Box::new(device)).unwrap();

    db.add(Box::new(
        AnalogInputObject::new(1, "AI-1", EngineeringUnits::DEGREES_CELSIUS).unwrap(),
    ))
    .unwrap();
    db.add(Box::new(
        AnalogOutputObject::new(1, "AO-1", EngineeringUnits::DEGREES_CELSIUS).unwrap(),
    ))
    .unwrap();
    db.add(Box::new(MultiStateInputObject::new(1, "MSI-1", 3).unwrap()))
        .unwrap();
    db.add(Box::new(CalendarObject::new(1, "CAL-1").unwrap()))
        .unwrap();
    db.add(Box::new(GroupObject::new(1, "GRP-1").unwrap()))
        .unwrap();
    db.add(Box::new(NotificationClass::new(1, "NC-1").unwrap()))
        .unwrap();
    db.add(Box::new(EventLogObject::new(1, "ELG-1", 16).unwrap()))
        .unwrap();
    db.add(Box::new(
        ScheduleObject::new(1, "SCH-1", PropertyValue::Unsigned(0)).unwrap(),
    ))
    .unwrap();
    db.add(Box::new(
        CharacterStringValueObject::new(1, "CSV-1").unwrap(),
    ))
    .unwrap();
    db.add(Box::new(GlobalGroupObject::new(1, "GG-1").unwrap()))
        .unwrap();
    db.add(Box::new(StructuredViewObject::new(1, "SV-1").unwrap()))
        .unwrap();
    let mut command = CommandObject::new(1, "CMD-1").unwrap();
    command
        .set_action(vec![bacnet_types::constructed::BACnetActionList {
            commands: vec![bacnet_types::constructed::BACnetActionCommand {
                device_identifier: None,
                object_identifier: oid(ObjectType::ANALOG_OUTPUT, 1),
                property_identifier: PropertyIdentifier::PRESENT_VALUE,
                property_array_index: None,
                property_value: PropertyValue::Real(1.0),
                priority: None,
                post_delay: None,
                quit_on_failure: false,
                write_successful: true,
            }],
        }])
        .unwrap();
    db.add(Box::new(command)).unwrap();
    db.add(Box::new(staging(1, "STG-1"))).unwrap();
    db
}

/// The (object, property) rejection matrix: BACnetLIST on the object type
/// that defines it, so an index must be refused on all four services.
const LIST_TARGETS: &[(ObjectType, PropertyIdentifier)] = &[
    (ObjectType::CALENDAR, PropertyIdentifier::DATE_LIST),
    (ObjectType::GROUP, PropertyIdentifier::LIST_OF_GROUP_MEMBERS),
    (
        ObjectType::NOTIFICATION_CLASS,
        PropertyIdentifier::RECIPIENT_LIST,
    ),
    (ObjectType::EVENT_LOG, PropertyIdentifier::LOG_BUFFER),
    (
        ObjectType::DEVICE,
        PropertyIdentifier::ACTIVE_COV_SUBSCRIPTIONS,
    ),
    (
        ObjectType::SCHEDULE,
        PropertyIdentifier::LIST_OF_OBJECT_PROPERTY_REFERENCES,
    ),
    // BACnetLIST on the multi-state family (Table 12-21) — array only on
    // CharacterString/BitString Value.
    (
        ObjectType::MULTI_STATE_INPUT,
        PropertyIdentifier::ALARM_VALUES,
    ),
];

fn read_indexed(
    db: &ObjectDatabase,
    target_oid: ObjectIdentifier,
    property: PropertyIdentifier,
    index: u32,
) -> Result<(), Error> {
    let request = ReadPropertyRequest {
        object_identifier: target_oid,
        property_identifier: property,
        property_array_index: Some(index),
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf);
    let mut ack_buf = BytesMut::new();
    handle_read_property(db, &buf, &mut ack_buf).map(|_| ())
}

fn assert_not_an_array(result: Result<(), Error>, context: &str) {
    match result {
        Err(Error::Remote(RemoteError::Error { class, code })) => {
            assert_eq!(class, ErrorClass::PROPERTY, "{context}: wrong error class");
            assert_eq!(
                code,
                ErrorCode::PROPERTY_IS_NOT_AN_ARRAY,
                "{context}: wrong error code"
            );
        }
        other => panic!("{context}: expected PROPERTY/PROPERTY_IS_NOT_AN_ARRAY, got {other:?}"),
    }
}

fn assert_protocol_error(result: Result<(), Error>, expected_code: ErrorCode, context: &str) {
    match result {
        Err(Error::Remote(RemoteError::Error { class, code })) => {
            assert_eq!(class, ErrorClass::PROPERTY, "{context}: wrong error class");
            assert_eq!(code, expected_code, "{context}: wrong error code");
        }
        other => panic!("{context}: expected PROPERTY/{expected_code:?}, got {other:?}"),
    }
}

fn encode_value(value: PropertyValue) -> Vec<u8> {
    let mut buf = BytesMut::new();
    encode_property_value(&mut buf, &value).unwrap();
    buf.to_vec()
}

fn write_indexed(
    db: &mut ObjectDatabase,
    target_oid: ObjectIdentifier,
    property: PropertyIdentifier,
    index: Option<u32>,
    value_bytes: Vec<u8>,
) -> Result<(), Error> {
    let request = WritePropertyRequest {
        object_identifier: target_oid,
        property_identifier: property,
        property_array_index: index,
        property_value: value_bytes,
        priority: None,
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();
    handle_write_property(db, &buf).map(|_| ())
}

fn wpm_single(
    db: &mut ObjectDatabase,
    target_oid: ObjectIdentifier,
    property: PropertyIdentifier,
    index: Option<u32>,
    value_bytes: Vec<u8>,
) -> Result<(), Error> {
    let request = WritePropertyMultipleRequest {
        list_of_write_access_specs: vec![WriteAccessSpecification {
            object_identifier: target_oid,
            list_of_properties: vec![BACnetPropertyValue {
                property_identifier: property,
                property_array_index: index,
                value: value_bytes,
                priority: None,
            }],
        }],
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();
    handle_write_property_multiple(db, &buf).map(|_| ())
}

#[test]
fn list_properties_reject_indexed_read_property() {
    let db = gating_db();
    for &(object_type, property) in LIST_TARGETS {
        assert_not_an_array(
            read_indexed(&db, oid(object_type, 1), property, 1),
            &format!("ReadProperty {object_type:?}.{property:?}"),
        );
    }
}

#[test]
fn list_properties_reject_indexed_read_property_multiple_inline() {
    use bacnet_types::constructed::{PropertyReference, ReadAccessSpecification};

    let db = gating_db();
    for &(object_type, property) in LIST_TARGETS {
        // Sibling reference (OBJECT_NAME, scalar) succeeds while the indexed
        // list reference fails inline — per-reference isolation.
        let request = ReadPropertyMultipleRequest {
            list_of_read_access_specs: vec![ReadAccessSpecification {
                object_identifier: oid(object_type, 1),
                list_of_property_references: vec![
                    PropertyReference {
                        property_identifier: PropertyIdentifier::OBJECT_NAME,
                        property_array_index: None,
                    },
                    PropertyReference {
                        property_identifier: property,
                        property_array_index: Some(1),
                    },
                ],
            }],
        };
        let mut buf = BytesMut::new();
        request.encode(&mut buf).unwrap();
        let mut ack_buf = BytesMut::new();
        handle_read_property_multiple(&db, &buf, &mut ack_buf).unwrap();
        let ack = ReadPropertyMultipleACK::decode(&ack_buf).unwrap();
        let results = &ack.list_of_read_access_results[0].list_of_results;
        assert!(
            results[0].property_value.is_some(),
            "{object_type:?}.OBJECT_NAME: sibling read must succeed"
        );
        assert_eq!(
            results[1].error,
            Some((ErrorClass::PROPERTY, ErrorCode::PROPERTY_IS_NOT_AN_ARRAY)),
            "{object_type:?}.{property:?}: indexed list read must fail inline"
        );
        // Clause 15.7.3.2.2.2 omits the index for a non-array property.
        assert_eq!(results[1].property_array_index, None);
    }
}

#[test]
fn list_properties_reject_indexed_write_property_and_write_property_multiple() {
    for &(object_type, property) in LIST_TARGETS {
        let mut db = gating_db();
        let value = encode_value(PropertyValue::OctetString(vec![0]));
        assert_not_an_array(
            write_indexed(
                &mut db,
                oid(object_type, 1),
                property,
                Some(1),
                value.clone(),
            ),
            &format!("WriteProperty {object_type:?}.{property:?}"),
        );
        assert_not_an_array(
            wpm_single(&mut db, oid(object_type, 1), property, Some(1), value),
            &format!("WritePropertyMultiple {object_type:?}.{property:?}"),
        );
    }
}

#[test]
fn true_arrays_pass_the_gate_on_read_property() {
    let db = gating_db();

    // OBJECT_LIST index 0 = element count, index 1..N = the Nth member.
    let mut buf = BytesMut::new();
    ReadPropertyRequest {
        object_identifier: oid(ObjectType::DEVICE, 1),
        property_identifier: PropertyIdentifier::OBJECT_LIST,
        property_array_index: Some(0),
    }
    .encode(&mut buf);
    let mut ack_buf = BytesMut::new();
    handle_read_property(&db, &buf, &mut ack_buf).unwrap();
    let ack = ReadPropertyACK::decode(&ack_buf).unwrap();
    let (count, _) =
        bacnet_encoding::primitives::decode_application_value(&ack.property_value, 0).unwrap();
    assert_eq!(count, PropertyValue::Unsigned(2));

    read_indexed(
        &db,
        oid(ObjectType::DEVICE, 1),
        PropertyIdentifier::OBJECT_LIST,
        1,
    )
    .unwrap();
    read_indexed(
        &db,
        oid(ObjectType::DEVICE, 1),
        PropertyIdentifier::OBJECT_LIST,
        2,
    )
    .unwrap();

    // PROPERTY_LIST index 0 / 1..N.
    for index in [0, 1, 3] {
        read_indexed(
            &db,
            oid(ObjectType::ANALOG_INPUT, 1),
            PropertyIdentifier::PROPERTY_LIST,
            index,
        )
        .unwrap();
    }

    // STATE_TEXT on a multi-state input.
    for index in [0, 1, 3] {
        read_indexed(
            &db,
            oid(ObjectType::MULTI_STATE_INPUT, 1),
            PropertyIdentifier::STATE_TEXT,
            index,
        )
        .unwrap();
    }

    // WEEKLY_SCHEDULE / EXCEPTION_SCHEDULE on a Schedule.
    read_indexed(
        &db,
        oid(ObjectType::SCHEDULE, 1),
        PropertyIdentifier::WEEKLY_SCHEDULE,
        0,
    )
    .unwrap();
    read_indexed(
        &db,
        oid(ObjectType::SCHEDULE, 1),
        PropertyIdentifier::WEEKLY_SCHEDULE,
        1,
    )
    .unwrap();
    read_indexed(
        &db,
        oid(ObjectType::SCHEDULE, 1),
        PropertyIdentifier::EXCEPTION_SCHEDULE,
        0,
    )
    .unwrap();

    // PRIORITY_ARRAY slots 1..=16 on a commandable analog output.
    for index in [1, 8, 16] {
        read_indexed(
            &db,
            oid(ObjectType::ANALOG_OUTPUT, 1),
            PropertyIdentifier::PRIORITY_ARRAY,
            index,
        )
        .unwrap();
    }
}

#[test]
fn modeled_arrays_on_command_and_staging_pass_the_gate() {
    // Review FIX 1: ACTION (Table 12-12) and STAGES / STAGE_NAMES /
    // TARGET_REFERENCES (Table 12-80) are BACnetARRAY[N]. The pin is that the
    // gate ADMITS the index instead of rejecting PROPERTY_IS_NOT_AN_ARRAY;
    // read_rpm::command and the Staging tests pin the element octets.
    let db = gating_db();
    for &(property, object_type) in &[
        (PropertyIdentifier::ACTION, ObjectType::COMMAND),
        (PropertyIdentifier::STAGES, ObjectType::STAGING),
        (PropertyIdentifier::STAGE_NAMES, ObjectType::STAGING),
        (PropertyIdentifier::TARGET_REFERENCES, ObjectType::STAGING),
    ] {
        for index in [0, 1] {
            read_indexed(&db, oid(object_type, 1), property, index).unwrap_or_else(|e| {
                panic!("{object_type:?}.{property:?} index {index} must pass the gate: {e:?}")
            });
        }
    }
}

#[test]
fn event_time_stamps_accepts_index_range_via_event_history() {
    // EVENT_TIME_STAMPS is BACnetARRAY[3]; element semantics delegate to
    // EventHistory::read; this test pins the server gate pass-through while
    // read_event_arrays pins the element payloads and CHOICE encoding.
    let db = gating_db();
    let msi = oid(ObjectType::MULTI_STATE_INPUT, 1);

    // No index → whole array; index 0 → count; 1..=3 → element.
    for index in [None, Some(0), Some(1), Some(2), Some(3)] {
        let request = ReadPropertyRequest {
            object_identifier: msi,
            property_identifier: PropertyIdentifier::EVENT_TIME_STAMPS,
            property_array_index: index,
        };
        let mut buf = BytesMut::new();
        request.encode(&mut buf);
        let mut ack_buf = BytesMut::new();
        handle_read_property(&db, &buf, &mut ack_buf)
            .unwrap_or_else(|e| panic!("EVENT_TIME_STAMPS index {index:?} must be served: {e:?}"));
    }

    // Out of range → INVALID_ARRAY_INDEX from the object layer.
    assert_protocol_error(
        read_indexed(&db, msi, PropertyIdentifier::EVENT_TIME_STAMPS, 4),
        ErrorCode::INVALID_ARRAY_INDEX,
        "EVENT_TIME_STAMPS index 4",
    );
}

#[test]
fn alarm_values_gate_varies_by_object_type() {
    let db = gating_db();

    // Multi-state input: ALARM_VALUES is a BACnetLIST (Table 12-21) → reject.
    assert_not_an_array(
        read_indexed(
            &db,
            oid(ObjectType::MULTI_STATE_INPUT, 1),
            PropertyIdentifier::ALARM_VALUES,
            1,
        ),
        "ReadProperty MULTI_STATE_INPUT.ALARM_VALUES",
    );

    // CharacterString Value: ALARM_VALUES is BACnetARRAY[N] (Table 12-44),
    // so the gate admits the index. The property is not yet modeled on the
    // object, which surfaces UNKNOWN_PROPERTY — a different, later failure
    // stage than the gate's PROPERTY_IS_NOT_AN_ARRAY.
    assert_protocol_error(
        read_indexed(
            &db,
            oid(ObjectType::CHARACTERSTRING_VALUE, 1),
            PropertyIdentifier::ALARM_VALUES,
            1,
        ),
        ErrorCode::UNKNOWN_PROPERTY,
        "ReadProperty CHARACTERSTRING_VALUE.ALARM_VALUES must NOT be gated",
    );
}

#[test]
fn schedule_list_of_object_property_references_rejects_indexed_read_and_write() {
    let db = gating_db();
    let sched = oid(ObjectType::SCHEDULE, 1);

    assert_not_an_array(
        read_indexed(
            &db,
            sched,
            PropertyIdentifier::LIST_OF_OBJECT_PROPERTY_REFERENCES,
            1,
        ),
        "ReadProperty SCHEDULE.LIST_OF_OBJECT_PROPERTY_REFERENCES",
    );

    let mut db = gating_db();
    let value = encode_value(PropertyValue::OctetString(vec![0]));
    assert_not_an_array(
        write_indexed(
            &mut db,
            sched,
            PropertyIdentifier::LIST_OF_OBJECT_PROPERTY_REFERENCES,
            Some(1),
            value,
        ),
        "WriteProperty SCHEDULE.LIST_OF_OBJECT_PROPERTY_REFERENCES",
    );
}

#[test]
fn object_level_classification_matrix() {
    // Classification truth source: identifier-stable arrays (Table 12-17/…),
    // identifier-stable lists, and the type-dependent identifiers.
    use bacnet_objects::traits::BACnetObject;
    use bacnet_types::enums::EngineeringUnits;

    let nc = NotificationClass::new(9, "NC-9").unwrap();
    // PRIORITY is BACnetARRAY[3] on Notification Class (Table 12-24).
    assert!(nc.is_array_property(PropertyIdentifier::PRIORITY));
    assert!(!nc.is_array_property(PropertyIdentifier::RECIPIENT_LIST));
    assert!(!nc.is_array_property(PropertyIdentifier::ACK_REQUIRED));

    let schedule = ScheduleObject::new(9, "SCH-9", PropertyValue::Unsigned(0)).unwrap();
    // LIST_OF_OBJECT_PROPERTY_REFERENCES is a BACnetLIST on Schedule (Table 12-28).
    assert!(!schedule.is_array_property(PropertyIdentifier::LIST_OF_OBJECT_PROPERTY_REFERENCES));
    assert!(schedule.is_array_property(PropertyIdentifier::WEEKLY_SCHEDULE));
    assert!(schedule.is_array_property(PropertyIdentifier::EXCEPTION_SCHEDULE));
    assert!(!schedule.is_array_property(PropertyIdentifier::PRESENT_VALUE));

    let calendar = CalendarObject::new(9, "CAL-9").unwrap();
    assert!(!calendar.is_array_property(PropertyIdentifier::DATE_LIST));

    let event_log = EventLogObject::new(9, "ELG-9", 16).unwrap();
    assert!(!event_log.is_array_property(PropertyIdentifier::LOG_BUFFER));

    let gg = GlobalGroupObject::new(9, "GG-9").unwrap();
    // Global Group (Table 12-57): GROUP_MEMBERS, GROUP_MEMBER_NAMES and
    // PRESENT_VALUE are BACnetARRAY — PRESENT_VALUE is scalar elsewhere.
    assert!(gg.is_array_property(PropertyIdentifier::GROUP_MEMBERS));
    assert!(gg.is_array_property(PropertyIdentifier::GROUP_MEMBER_NAMES));
    assert!(gg.is_array_property(PropertyIdentifier::PRESENT_VALUE));

    let sv = StructuredViewObject::new(9, "SV-9").unwrap();
    // Structured View (Table 12-34): BACnetARRAY subordinate properties.
    assert!(sv.is_array_property(PropertyIdentifier::SUBORDINATE_LIST));
    assert!(sv.is_array_property(PropertyIdentifier::SUBORDINATE_ANNOTATIONS));

    let ai = AnalogInputObject::new(9, "AI-9", EngineeringUnits::DEGREES_CELSIUS).unwrap();
    assert!(!ai.is_array_property(PropertyIdentifier::PRESENT_VALUE));
    assert!(ai.is_array_property(PropertyIdentifier::PROPERTY_LIST));

    let csv = CharacterStringValueObject::new(9, "CSV-9").unwrap();
    assert!(csv.is_array_property(PropertyIdentifier::ALARM_VALUES));
    assert!(csv.is_array_property(PropertyIdentifier::FAULT_VALUES));
    assert!(csv.is_array_property(PropertyIdentifier::PRIORITY_ARRAY));

    let ao = AnalogOutputObject::new(9, "AO-9", EngineeringUnits::DEGREES_CELSIUS).unwrap();
    assert!(ao.is_array_property(PropertyIdentifier::PRIORITY_ARRAY));
    assert!(!ao.is_array_property(PropertyIdentifier::PRESENT_VALUE));

    let cmd = CommandObject::new(9, "CMD-9").unwrap();
    // Command (Table 12-12): ACTION and its parallel ACTION_TEXT are both
    // BACnetARRAY[N] (#1150).
    assert!(cmd.is_array_property(PropertyIdentifier::ACTION));
    assert!(cmd.is_array_property(PropertyIdentifier::ACTION_TEXT));
    assert!(!cmd.is_array_property(PropertyIdentifier::PRESENT_VALUE));

    let stg = staging(9, "STG-9");
    // Staging (Table 12-80): all three collection properties are arrays.
    assert!(stg.is_array_property(PropertyIdentifier::STAGES));
    assert!(stg.is_array_property(PropertyIdentifier::STAGE_NAMES));
    assert!(stg.is_array_property(PropertyIdentifier::TARGET_REFERENCES));
    assert!(!stg.is_array_property(PropertyIdentifier::PRESENT_STAGE));
}

// ── #266: omitted-index PRIORITY_ARRAY writes are protocol errors ─────────

#[test]
fn wpm_omitted_index_priority_array_write_is_write_access_denied() {
    // Clause 12.1.5.1: an omitted index means whole-array access; commandable
    // objects do not support whole-array writes, so Result(-) carries
    // PROPERTY / WRITE_ACCESS_DENIED (Clause 15.9.1.3) — not an opaque
    // encoding error the service layer cannot map.
    let mut db = gating_db();
    let ao = oid(ObjectType::ANALOG_OUTPUT, 1);
    let value = encode_value(PropertyValue::Real(1.0));
    assert_protocol_error(
        wpm_single(&mut db, ao, PropertyIdentifier::PRIORITY_ARRAY, None, value),
        ErrorCode::WRITE_ACCESS_DENIED,
        "WPM PRIORITY_ARRAY without index",
    );
}

#[test]
fn write_property_omitted_index_priority_array_is_write_access_denied() {
    let mut db = gating_db();
    let ao = oid(ObjectType::ANALOG_OUTPUT, 1);
    let value = encode_value(PropertyValue::Real(1.0));
    assert_protocol_error(
        write_indexed(&mut db, ao, PropertyIdentifier::PRIORITY_ARRAY, None, value),
        ErrorCode::WRITE_ACCESS_DENIED,
        "WriteProperty PRIORITY_ARRAY without index",
    );
}

#[test]
fn priority_array_count_and_out_of_range_write_are_read_only() {
    // Index 0 is the count; 17 is beyond the slots. Read-only denial precedes
    // property-specific range validation for both (§19.2.1).
    let mut db = gating_db();
    let ao = oid(ObjectType::ANALOG_OUTPUT, 1);
    for index in [Some(0), Some(17)] {
        let value = encode_value(PropertyValue::Real(1.0));
        assert_protocol_error(
            wpm_single(
                &mut db,
                ao,
                PropertyIdentifier::PRIORITY_ARRAY,
                index,
                value.clone(),
            ),
            ErrorCode::WRITE_ACCESS_DENIED,
            &format!("WPM PRIORITY_ARRAY index {index:?}"),
        );
        assert_protocol_error(
            write_indexed(
                &mut db,
                ao,
                PropertyIdentifier::PRIORITY_ARRAY,
                index,
                value,
            ),
            ErrorCode::WRITE_ACCESS_DENIED,
            &format!("WriteProperty PRIORITY_ARRAY index {index:?}"),
        );
    }
}

#[test]
fn indexed_access_to_recipient_list_rejected_with_not_an_array() {
    // Recipient_List is a BACnetLIST (Table 12-24): indexed reads AND writes
    // hit the same PROPERTY / PROPERTY_IS_NOT_AN_ARRAY classification
    // (Tranche J's INVALID_DATA_TYPE stopgap is replaced by the gate).
    let db = gating_db();
    let nc = oid(ObjectType::NOTIFICATION_CLASS, 1);
    assert_not_an_array(
        read_indexed(&db, nc, PropertyIdentifier::RECIPIENT_LIST, 2),
        "ReadProperty NOTIFICATION_CLASS.RECIPIENT_LIST",
    );

    let mut db = gating_db();
    let value = encode_value(PropertyValue::OctetString(vec![0]));
    assert_not_an_array(
        write_indexed(
            &mut db,
            nc,
            PropertyIdentifier::RECIPIENT_LIST,
            Some(2),
            value,
        ),
        "WriteProperty NOTIFICATION_CLASS.RECIPIENT_LIST",
    );

    // The unindexed whole-list write is unaffected: Recipient_List stays
    // writable at the list level (tranche J's framed tests pin the wire form).
    let mut framed = BytesMut::new();
    bacnet_encoding::constructed::encode_destination_list(&mut framed, &[]).unwrap();
    let mut db = gating_db();
    write_indexed(
        &mut db,
        nc,
        PropertyIdentifier::RECIPIENT_LIST,
        None,
        framed.to_vec(),
    )
    .unwrap();
}

#[test]
fn notification_class_priority_accepts_index_range() {
    // PRIORITY is BACnetARRAY[3] of Unsigned (Table 12-24). The old
    // identifier whitelist wrongly rejected it; the trait gate must admit
    // index 0 (count) and 1..=3 (elements).
    let db = gating_db();
    let nc = oid(ObjectType::NOTIFICATION_CLASS, 1);

    let mut buf = BytesMut::new();
    ReadPropertyRequest {
        object_identifier: nc,
        property_identifier: PropertyIdentifier::PRIORITY,
        property_array_index: Some(0),
    }
    .encode(&mut buf);
    let mut ack_buf = BytesMut::new();
    handle_read_property(&db, &buf, &mut ack_buf).unwrap();
    let ack = ReadPropertyACK::decode(&ack_buf).unwrap();
    assert_eq!(ack.property_array_index, Some(0));
    let (count, _) =
        bacnet_encoding::primitives::decode_application_value(&ack.property_value, 0).unwrap();
    assert_eq!(count, PropertyValue::Unsigned(3));

    for index in 1..=3 {
        read_indexed(&db, nc, PropertyIdentifier::PRIORITY, index).unwrap();
    }
}

#[test]
fn wpm_gate_rejection_keeps_valid_prefix() {
    let mut db = gating_db();
    let nc = oid(ObjectType::NOTIFICATION_CLASS, 1);
    let request = WritePropertyMultipleRequest {
        list_of_write_access_specs: vec![WriteAccessSpecification {
            object_identifier: nc,
            list_of_properties: vec![
                BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::DESCRIPTION,
                    property_array_index: None,
                    value: encode_value(PropertyValue::CharacterString("MUTATED".into())),
                    priority: None,
                },
                BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::RECIPIENT_LIST,
                    property_array_index: Some(1),
                    value: encode_value(PropertyValue::OctetString(vec![0])),
                    priority: None,
                },
            ],
        }],
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();
    assert_not_an_array(
        handle_write_property_multiple(&mut db, &buf).map(|_| ()),
        "WPM with one gated reference",
    );

    assert_eq!(
        db.get(&nc)
            .unwrap()
            .read_property(PropertyIdentifier::DESCRIPTION, None)
            .unwrap(),
        PropertyValue::CharacterString("MUTATED".into()),
        "the valid prefix remains applied when a sibling hits the gate"
    );
}

// --- #182: structured reference properties are scalar-typed -------------

/// The BACnetObjectPropertyReference-typed properties (Loop Clause 12.17,
/// Pulse Converter Clause 12.23, Averaging Clause 12.5 — the last typed
/// BACnetDeviceObjectPropertyReference) are scalars, not BACnetARRAY: an
/// indexed ReadProperty hits the same gate as any other scalar (#260).
#[test]
fn reference_properties_reject_indexed_read_property() {
    use bacnet_objects::accumulator::PulseConverterObject;
    use bacnet_objects::averaging::AveragingObject;
    use bacnet_objects::loop_obj::LoopObject;
    use bacnet_types::enums::EngineeringUnits;

    let mut db = ObjectDatabase::new();
    db.add(Box::new(
        LoopObject::new(1, "LOOP-1", EngineeringUnits::DEGREES_CELSIUS).unwrap(),
    ))
    .unwrap();
    db.add(Box::new(
        PulseConverterObject::new(1, "PC-1", EngineeringUnits::DEGREES_CELSIUS).unwrap(),
    ))
    .unwrap();
    db.add(Box::new(AveragingObject::new(1, "AVG-1").unwrap()))
        .unwrap();

    let targets: &[(ObjectIdentifier, PropertyIdentifier)] = &[
        (
            oid(ObjectType::LOOP, 1),
            PropertyIdentifier::CONTROLLED_VARIABLE_REFERENCE,
        ),
        (
            oid(ObjectType::LOOP, 1),
            PropertyIdentifier::MANIPULATED_VARIABLE_REFERENCE,
        ),
        (
            oid(ObjectType::LOOP, 1),
            PropertyIdentifier::SETPOINT_REFERENCE,
        ),
        (
            oid(ObjectType::PULSE_CONVERTER, 1),
            PropertyIdentifier::INPUT_REFERENCE,
        ),
        (
            oid(ObjectType::AVERAGING, 1),
            PropertyIdentifier::OBJECT_PROPERTY_REFERENCE,
        ),
    ];
    for &(target, property) in targets {
        assert_not_an_array(
            read_indexed(&db, target, property, 2),
            &format!("ReadProperty {target:?}.{property:?}[2]"),
        );
    }
}