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
//! Wire-level proof that CHANGE_OF_STATE alarm commissioning and each
//! `Event_Enable` bit reach notification distribution.
//!
//! `event_notifications_tests.rs` pins the TO_OFFNORMAL half of this gate for
//! AnalogInput and has little headroom left under the 700-LOC cap, so the
//! Multi-state Input cases live here alongside Binary Input and Multi-state
//! Value proofs that Alarm_Value(s) can be commissioned through working
//! network routes.
//!
//! Both directions are covered on purpose. A gate written `event_enable & 0x01`
//! instead of `event_enable & transition_bit` distributes TO_OFFNORMAL correctly
//! and every other transition wrongly, so asserting only the off-normal
//! direction leaves that mistake invisible.

use super::*;
use crate::handlers::{handle_add_list_element, handle_remove_list_element};
use crate::server::test_transport::{SendLog, TestTransport};
use bacnet_encoding::apdu::decode_apdu;
use bacnet_encoding::constructed::decode_event_notification;
use bacnet_encoding::npdu::decode_npdu;
use bacnet_objects::binary::{BinaryInputObject, BinaryValueObject};
use bacnet_objects::device::{DeviceConfig, DeviceObject};
use bacnet_objects::multistate::{MultiStateInputObject, MultiStateValueObject};
use bacnet_objects::traits::BACnetObject;
use bacnet_services::alarm_event::NotificationParameters;
use bacnet_services::list_manipulation::ListElementRequest;
use bacnet_types::bitstring::EventTransitionBits;
use bacnet_types::enums::{EventState, EventType, NotifyType};
use bacnet_types::primitives::StatusFlags;
use bytes::{Bytes, BytesMut};

/// The state value the fixture treats as an alarm, and the one it does not.
const ALARM_STATE: u64 = 2;
const NORMAL_STATE: u64 = 1;

#[tokio::test]
async fn analog_event_enable_set_delivers_committed_event_values() {
    use super::event_notifications_tests::{
        broadcasts_from_per_write_path, db_with_high_limit_transition,
        decode_broadcast_notification,
    };

    let db = db_with_high_limit_transition(0x80);
    db.write()
        .await
        .get_mut(&ObjectIdentifier::new(ObjectType::ANALOG_INPUT, 1).unwrap())
        .unwrap()
        .write_property(
            PropertyIdentifier::NOTIFY_TYPE,
            None,
            PropertyValue::Enumerated(NotifyType::EVENT.to_raw()),
            None,
        )
        .unwrap();
    let sent = broadcasts_from_per_write_path(&db, DccState::Enable).await;

    assert_eq!(sent.len(), 1);
    let notification = decode_broadcast_notification(&sent);
    assert_eq!(notification.notify_type, NotifyType::EVENT);
    assert_eq!(notification.event_type, EventType::OUT_OF_RANGE);
    assert_eq!(
        notification.event_values,
        Some(NotificationParameters::OutOfRange {
            exceeding_value: 81.0,
            status_flags: StatusFlags::IN_ALARM,
            deadband: 2.0,
            exceeded_limit: 80.0,
        })
    );
}

/// A Multi-state Input in a one-object database, plus what the per-write
/// notification path needs to run against it.
struct Fixture {
    db: Arc<RwLock<ObjectDatabase>>,
    network: Arc<NetworkLayer<TestTransport>>,
    comm_state: Arc<CommState>,
    learned_routers: Arc<Mutex<LearnedRouterCache>>,
    notification_transactions: Arc<NotificationTransactions>,
    sent: SendLog,
    oid: ObjectIdentifier,
}

impl Fixture {
    /// Build a Multi-state Input holding `bits` in `Event_Enable`, with
    /// [`ALARM_STATE`] as its only alarm value and `Out_Of_Service` TRUE so that
    /// `Present_Value` accepts network writes.
    ///
    /// Scalar commissioning uses object dispatch. Alarm_Values uses
    /// AddListElement through its handler, the only working network route
    /// today; whole-list WriteProperty remains blocked by decoder issue #182.
    async fn new(bits: EventTransitionBits) -> Self {
        let mut msi = MultiStateInputObject::new(1, "MSI-1", 3).unwrap();
        for (property, value) in [
            (
                PropertyIdentifier::OUT_OF_SERVICE,
                PropertyValue::Boolean(true),
            ),
            (
                PropertyIdentifier::EVENT_ENABLE,
                PropertyValue::BitString {
                    unused_bits: 5,
                    data: vec![bits.to_bacnet()],
                },
            ),
            // EVENT, not the default ALARM: the send site falls back to ALARM
            // when it cannot read Notify_Type, so a fixture left at the default
            // would assert nothing about the property actually reaching the wire.
            (
                PropertyIdentifier::NOTIFY_TYPE,
                PropertyValue::Enumerated(NotifyType::EVENT.to_raw()),
            ),
        ] {
            msi.write_property_from(
                property,
                None,
                value,
                None,
                &crate::command_source::test_origin(),
            )
            .unwrap_or_else(|e| panic!("{property:?} must be writable since #229: {e:?}"));
        }
        let fixture = Self::from_object(Box::new(msi)).await;
        fixture.add_alarm_value(ALARM_STATE as u8).await;
        fixture
    }

    async fn from_object(object: Box<dyn BACnetObject>) -> Self {
        let oid = object.object_identifier();

        let mut db = clocked_test_database();
        db.add(object).unwrap();
        db.add(Box::new(
            DeviceObject::new(DeviceConfig {
                identity: bacnet_objects::DeviceIdentity::default().with_name("Dev"),
                ..DeviceConfig::default()
            })
            .unwrap(),
        ))
        .unwrap();
        // These objects leave Notification_Class at its default of 0, so class
        // 0 has to exist and name a recipient for anything to be distributed.
        db.add(Box::new(
            super::event_notifications_tests::notification_class_0_broadcasting(),
        ))
        .unwrap();

        let (transport, sent) = super::event_notifications_tests::recording_transport();
        Self {
            db: Arc::new(RwLock::new(db)),
            network: Arc::new(NetworkLayer::new(transport)),
            comm_state: Arc::new(CommState::default()), // DCC not blocking
            learned_routers: Arc::new(Mutex::new(LearnedRouterCache::new())),
            notification_transactions: NotificationTransactions::new(),
            sent,
            oid,
        }
    }

    /// Write `Present_Value` and run the per-write notification path once, the
    /// same two steps a WriteProperty request performs.
    async fn write_present_value(&self, value: u64) {
        self.write_present_value_as(PropertyValue::Unsigned(value))
            .await;
    }

    async fn write_present_value_as(&self, value: PropertyValue) {
        self.db
            .write()
            .await
            .get_mut(&self.oid)
            .expect("the MSI is in the database")
            .write_property_from(
                PropertyIdentifier::PRESENT_VALUE,
                None,
                value,
                None,
                &crate::command_source::test_origin(),
            )
            .expect("Out_Of_Service is TRUE, so Present_Value must be writable");

        BACnetServer::<TestTransport>::fire_event_notifications_with_bindings(
            &crate::server::event_delivery::EventDelivery {
                db: &self.db,
                network: &self.network,
                comm_state: &self.comm_state,
                learned_routers: &self.learned_routers,
                notification_transactions: &self.notification_transactions,
                device_bindings: &Arc::new(RwLock::new(
                    crate::server::device_bindings::DeviceBindingTable::new(),
                )),
                suppressions: &Default::default(),
                retry_timeout_ms: 1000,
                local_apdu_capacity: 1476,
            },
            &Arc::new(RwLock::new(crate::cov::CovSubscriptionTable::new())),
            &self.oid,
        )
        .await;
    }

    /// Commission one Alarm_Values element through the AddListElement handler.
    async fn add_alarm_value(&self, value: u8) {
        let request = ListElementRequest {
            object_identifier: self.oid,
            property_identifier: PropertyIdentifier::ALARM_VALUES,
            property_array_index: None,
            list_of_elements: vec![0x21, value],
        };
        let mut encoded = BytesMut::new();
        request.encode(&mut encoded).unwrap();
        let mut db = self.db.write().await;
        handle_add_list_element(&mut db, &encoded)
            .expect("AddListElement is the working network Alarm_Values route");
    }

    async fn remove_alarm_value(&self, value: u8) {
        let request = ListElementRequest {
            object_identifier: self.oid,
            property_identifier: PropertyIdentifier::ALARM_VALUES,
            property_array_index: None,
            list_of_elements: vec![0x21, value],
        };
        let mut encoded = BytesMut::new();
        request.encode(&mut encoded).unwrap();
        let mut db = self.db.write().await;
        handle_remove_list_element(&mut db, &encoded)
            .expect("RemoveListElement must remove the commissioned alarm value");
    }

    /// Take the broadcasts recorded since the last call.
    fn drain(&self) -> Vec<Bytes> {
        self.sent
            .take()
            .into_iter()
            .map(|frame| frame.npdu)
            .collect()
    }

    async fn event_state(&self) -> PropertyValue {
        self.db
            .read()
            .await
            .get(&self.oid)
            .unwrap()
            .read_property(PropertyIdentifier::EVENT_STATE, None)
            .unwrap()
    }
}

/// Decode the one broadcast expected in `sent` and assert it is a CHANGE_OF_STATE
/// notification for the fixture's MSI describing `from` -> `to`, carrying the
/// `Notify_Type` the fixture commissioned.
fn assert_sole_notification(
    sent: Vec<Bytes>,
    oid: ObjectIdentifier,
    from: EventState,
    to: EventState,
    context: &str,
) {
    assert_eq!(
        sent.len(),
        1,
        "{context}: expected exactly one broadcast EventNotification"
    );
    let npdu = decode_npdu(sent[0].clone()).expect("decode NPDU");
    let notif = match decode_apdu(npdu.payload).expect("decode APDU") {
        Apdu::UnconfirmedRequest(req) => {
            assert_eq!(
                req.service_choice,
                UnconfirmedServiceChoice::UNCONFIRMED_EVENT_NOTIFICATION
            );
            decode_event_notification(&req.service_request).expect("decode EventNotification")
        }
        other => panic!("{context}: expected UnconfirmedRequest, got {other:?}"),
    };

    assert_eq!(
        notif.event_object_identifier, oid,
        "{context}: notification must name the commissioned object"
    );
    assert_eq!(
        notif.event_type,
        EventType::CHANGE_OF_STATE,
        "{context}: the detector's CHANGE_OF_STATE algorithm must reach the wire"
    );
    assert_eq!(notif.from_state, from, "{context}: from_state on the wire");
    assert_eq!(notif.to_state, to, "{context}: to_state on the wire");
    assert_eq!(
        notif.notify_type,
        NotifyType::EVENT,
        "{context}: the commissioned Notify_Type must reach the wire, not the ALARM fallback"
    );
}

/// TO_OFFNORMAL alone distributes the entry into OFFNORMAL; every other single
/// bit leaves it undistributed while the transition itself still happens.
#[tokio::test]
async fn msi_to_offnormal_bit_alone_distributes_the_offnormal_transition() {
    let enabled = Fixture::new(EventTransitionBits::TO_OFFNORMAL).await;
    enabled.write_present_value(ALARM_STATE).await;
    assert_sole_notification(
        enabled.drain(),
        enabled.oid,
        EventState::NORMAL,
        EventState::OFFNORMAL,
        "TO_OFFNORMAL set",
    );

    for bits in [
        EventTransitionBits::TO_FAULT,
        EventTransitionBits::TO_NORMAL,
        EventTransitionBits::empty(),
    ] {
        let suppressed = Fixture::new(bits).await;
        suppressed.write_present_value(ALARM_STATE).await;
        assert!(
            suppressed.drain().is_empty(),
            "Event_Enable {bits} must not distribute a TO_OFFNORMAL notification"
        );
        assert_eq!(
            suppressed.event_state().await,
            PropertyValue::Enumerated(EventState::OFFNORMAL.to_raw()),
            "Event_Enable {bits}: the transition must still occur, only distribution is withheld"
        );
    }
}

/// TO_NORMAL alone distributes the return to NORMAL and nothing else, and a
/// TO_OFFNORMAL-only object stays silent on that same return.
///
/// This is the direction that catches a gate keyed to a fixed bit rather than to
/// the transition being reported.
#[tokio::test]
async fn msi_to_normal_bit_alone_distributes_the_return_to_normal() {
    let enabled = Fixture::new(EventTransitionBits::TO_NORMAL).await;
    enabled.write_present_value(ALARM_STATE).await;
    assert!(
        enabled.drain().is_empty(),
        "TO_NORMAL set alone must not distribute the entry into OFFNORMAL"
    );
    assert_eq!(
        enabled.event_state().await,
        PropertyValue::Enumerated(EventState::OFFNORMAL.to_raw()),
        "the object must be in OFFNORMAL for the next write to be a return to normal"
    );

    enabled.write_present_value(NORMAL_STATE).await;
    assert_sole_notification(
        enabled.drain(),
        enabled.oid,
        EventState::OFFNORMAL,
        EventState::NORMAL,
        "TO_NORMAL set",
    );

    let offnormal_only = Fixture::new(EventTransitionBits::TO_OFFNORMAL).await;
    offnormal_only.write_present_value(ALARM_STATE).await;
    assert_eq!(
        offnormal_only.drain().len(),
        1,
        "TO_OFFNORMAL set must distribute the entry into OFFNORMAL"
    );
    offnormal_only.write_present_value(NORMAL_STATE).await;
    assert!(
        offnormal_only.drain().is_empty(),
        "TO_OFFNORMAL set alone must not distribute the return to NORMAL"
    );
    assert_eq!(
        offnormal_only.event_state().await,
        PropertyValue::Enumerated(EventState::NORMAL.to_raw()),
        "the return to NORMAL must still have happened internally"
    );
}

#[tokio::test]
async fn bi_bv_and_msv_alarm_values_commission_and_reach_the_wire() {
    let mut bi = BinaryInputObject::new(1, "BI-1").unwrap();
    for (property, value) in [
        (
            PropertyIdentifier::ALARM_VALUE,
            PropertyValue::Enumerated(0),
        ),
        (
            PropertyIdentifier::OUT_OF_SERVICE,
            PropertyValue::Boolean(true),
        ),
        (
            PropertyIdentifier::EVENT_ENABLE,
            PropertyValue::BitString {
                unused_bits: 5,
                data: vec![EventTransitionBits::TO_OFFNORMAL.to_bacnet()],
            },
        ),
        (
            PropertyIdentifier::NOTIFY_TYPE,
            PropertyValue::Enumerated(NotifyType::EVENT.to_raw()),
        ),
        (
            PropertyIdentifier::PRESENT_VALUE,
            PropertyValue::Enumerated(1),
        ),
    ] {
        bi.write_property_from(
            property,
            None,
            value,
            None,
            &crate::command_source::test_origin(),
        )
        .unwrap();
    }
    let bi_fixture = Fixture::from_object(Box::new(bi)).await;
    bi_fixture
        .write_present_value_as(PropertyValue::Enumerated(0))
        .await;
    assert_sole_notification(
        bi_fixture.drain(),
        bi_fixture.oid,
        EventState::NORMAL,
        EventState::OFFNORMAL,
        "Binary Input non-default Alarm_Value",
    );

    let mut bv = BinaryValueObject::new(1, "BV-1").unwrap();
    for (property, value) in [
        (
            PropertyIdentifier::ALARM_VALUE,
            PropertyValue::Enumerated(0),
        ),
        (
            PropertyIdentifier::EVENT_ENABLE,
            PropertyValue::BitString {
                unused_bits: 5,
                data: vec![EventTransitionBits::TO_OFFNORMAL.to_bacnet()],
            },
        ),
        (
            PropertyIdentifier::NOTIFY_TYPE,
            PropertyValue::Enumerated(NotifyType::EVENT.to_raw()),
        ),
        (
            PropertyIdentifier::PRESENT_VALUE,
            PropertyValue::Enumerated(1),
        ),
    ] {
        bv.write_property_from(
            property,
            None,
            value,
            None,
            &crate::command_source::test_origin(),
        )
        .unwrap();
    }
    let bv_fixture = Fixture::from_object(Box::new(bv)).await;
    bv_fixture
        .write_present_value_as(PropertyValue::Enumerated(0))
        .await;
    assert_sole_notification(
        bv_fixture.drain(),
        bv_fixture.oid,
        EventState::NORMAL,
        EventState::OFFNORMAL,
        "Binary Value non-default Alarm_Value",
    );

    let mut msv = MultiStateValueObject::new(1, "MSV-1", 3).unwrap();
    for (property, value) in [
        (
            PropertyIdentifier::EVENT_ENABLE,
            PropertyValue::BitString {
                unused_bits: 5,
                data: vec![EventTransitionBits::TO_OFFNORMAL.to_bacnet()],
            },
        ),
        (
            PropertyIdentifier::NOTIFY_TYPE,
            PropertyValue::Enumerated(NotifyType::EVENT.to_raw()),
        ),
    ] {
        msv.write_property_from(
            property,
            None,
            value,
            None,
            &crate::command_source::test_origin(),
        )
        .unwrap();
    }
    let msv_fixture = Fixture::from_object(Box::new(msv)).await;
    msv_fixture.add_alarm_value(2).await;
    msv_fixture.write_present_value(2).await;
    assert_sole_notification(
        msv_fixture.drain(),
        msv_fixture.oid,
        EventState::NORMAL,
        EventState::OFFNORMAL,
        "Multi-state Value Alarm_Values",
    );
}

#[tokio::test]
async fn fresh_binary_input_active_is_offnormal_without_distribution() {
    let mut bi = BinaryInputObject::new(2, "BI-default").unwrap();
    bi.write_property(
        PropertyIdentifier::OUT_OF_SERVICE,
        None,
        PropertyValue::Boolean(true),
        None,
    )
    .unwrap();
    let fixture = Fixture::from_object(Box::new(bi)).await;
    fixture
        .write_present_value_as(PropertyValue::Enumerated(1))
        .await;
    assert_eq!(
        fixture.event_state().await,
        PropertyValue::Enumerated(EventState::OFFNORMAL.to_raw())
    );
    assert!(
        fixture.drain().is_empty(),
        "default Event_Enable must suppress distribution"
    );
}

#[tokio::test]
async fn remove_last_alarm_value_disarms_msi() {
    let fixture = Fixture::new(EventTransitionBits::TO_OFFNORMAL).await;
    fixture.remove_alarm_value(ALARM_STATE as u8).await;
    assert_eq!(
        fixture
            .db
            .read()
            .await
            .get(&fixture.oid)
            .unwrap()
            .read_property(PropertyIdentifier::ALARM_VALUES, None)
            .unwrap(),
        PropertyValue::List(vec![])
    );
    fixture.write_present_value(ALARM_STATE).await;
    assert_eq!(
        fixture.event_state().await,
        PropertyValue::Enumerated(EventState::NORMAL.to_raw())
    );
    assert!(
        fixture.drain().is_empty(),
        "an empty Alarm_Values list must not distribute"
    );
}