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
use super::*;

use bacnet_types::enums::{LifeSafetyState, SilencedState};

// ---------------------------------------------------------------------------
// PR-0803 sub-slice 1 (R1 outcome b): operation -> property -> COV pins.
// Event_State is intrinsic-only, so LSO dispatches fan out exactly the
// Silenced / Operation_Expected / Present_Value / Tracking_Value deltas with
// one appended Status_Flags each — no coarse PV blast, no duplicated
// Status_Flags and no Event_State payload. The Zone's Tracking_Value (#1092)
// notifies only when a reset commit changes it.
// ---------------------------------------------------------------------------

/// Decode one unconfirmed COV notification, keeping the subscriber handle so
/// tests can attribute each payload to its subscription.
fn decode_cov_notification(apdu: &Apdu) -> COVNotificationRequest {
    let Apdu::UnconfirmedRequest(request) = apdu else {
        panic!("expected unconfirmed COV notification, got {apdu:?}");
    };
    assert_eq!(
        request.service_choice,
        UnconfirmedServiceChoice::UNCONFIRMED_COV_NOTIFICATION
    );
    COVNotificationRequest::decode(&request.service_request).unwrap()
}

/// Assert a single-notification payload carries its property plus exactly one
/// Status_Flags, and never Event_State.
fn assert_exact_single_payload(
    notification: &COVNotificationRequest,
    property: PropertyIdentifier,
) {
    let properties: Vec<_> = notification
        .list_of_values
        .iter()
        .map(|value| value.property_identifier)
        .collect();
    assert_eq!(
        properties,
        vec![property, PropertyIdentifier::STATUS_FLAGS],
        "exact payload must be [property, Status_Flags] with no duplication"
    );
    assert!(
        !properties.contains(&PropertyIdentifier::EVENT_STATE),
        "Event_State is never part of an LSO COV payload"
    );
}

fn encode_life_safety_operation(
    operation: bacnet_types::enums::LifeSafetyOperation,
    object: ObjectIdentifier,
) -> Bytes {
    let request = LifeSafetyOperationRequest {
        requesting_process_identifier: 9,
        requesting_source: "operator".into(),
        request: operation,
        object_identifier: Some(object),
    };
    let mut encoded = BytesMut::new();
    request.encode(&mut encoded).unwrap();
    encoded.freeze()
}

#[tokio::test]
async fn silence_unsilence_dispatch_fans_out_exact_property_deltas() {
    use bacnet_types::enums::LifeSafetyOperation;

    let cases = [
        (
            SilencedState::UNSILENCED,
            LifeSafetyOperation::SILENCE,
            SilencedState::ALL_SILENCED,
        ),
        (
            SilencedState::UNSILENCED,
            LifeSafetyOperation::SILENCE_AUDIBLE,
            SilencedState::AUDIBLE_SILENCED,
        ),
        (
            SilencedState::UNSILENCED,
            LifeSafetyOperation::SILENCE_VISUAL,
            SilencedState::VISIBLE_SILENCED,
        ),
        (
            SilencedState::ALL_SILENCED,
            LifeSafetyOperation::UNSILENCE,
            SilencedState::UNSILENCED,
        ),
        (
            SilencedState::ALL_SILENCED,
            LifeSafetyOperation::UNSILENCE_AUDIBLE,
            SilencedState::VISIBLE_SILENCED,
        ),
        (
            SilencedState::ALL_SILENCED,
            LifeSafetyOperation::UNSILENCE_VISUAL,
            SilencedState::AUDIBLE_SILENCED,
        ),
    ];

    for (initial, operation, expected) in cases {
        let mut point = LifeSafetyPointObject::new(1, "point").unwrap();
        point.set_silenced(initial);
        point.set_operation_expected(operation);
        let mut db = clocked_test_database();
        db.add(Box::new(point)).unwrap();
        let fixture = DispatchFixture::new(
            db,
            [
                subscription(
                    Some(PropertyIdentifier::SILENCED),
                    CovNotificationKind::Single,
                    1,
                ),
                subscription(
                    Some(PropertyIdentifier::OPERATION_EXPECTED),
                    CovNotificationKind::Single,
                    2,
                ),
                subscription(None, CovNotificationKind::Single, 3),
            ],
        )
        .await;

        fixture
            .dispatch(
                0x40,
                ConfirmedServiceChoice::LIFE_SAFETY_OPERATION,
                encode_life_safety_operation(operation, point_oid()),
            )
            .await;
        let apdus = fixture.take_apdus();

        // Exact post-state: Silenced moved, Event_State still NORMAL.
        {
            let db = fixture.db.read().await;
            let object = db.get(&point_oid()).unwrap();
            assert_eq!(
                object
                    .read_property(PropertyIdentifier::SILENCED, None)
                    .unwrap(),
                PropertyValue::Enumerated(expected.to_raw()),
                "operation {} from state {}",
                operation.to_raw(),
                initial.to_raw()
            );
            assert_eq!(
                object
                    .read_property(PropertyIdentifier::EVENT_STATE, None)
                    .unwrap(),
                PropertyValue::Enumerated(0)
            );
        }

        // ACK first, then exactly the two matching property notifications —
        // the whole-object subscription stays silent (no PV/Status_Flags
        // change means no coarse PV blast).
        assert!(
            matches!(apdus[0], Apdu::SimpleAck(_)),
            "operation {} must ACK first",
            operation.to_raw()
        );
        let notifications: Vec<_> = apdus[1..].iter().map(decode_cov_notification).collect();
        assert_eq!(
            notifications.len(),
            2,
            "operation {} must notify only the two matching property subs",
            operation.to_raw()
        );
        for notification in &notifications {
            assert_eq!(notification.monitored_object_identifier, point_oid());
            assert!(
                !notification
                    .list_of_values
                    .iter()
                    .any(|value| value.property_identifier == PropertyIdentifier::PRESENT_VALUE),
                "Silenced/OE-only operation must not blast Present_Value"
            );
        }
        let by_subscriber: std::collections::HashMap<u32, &COVNotificationRequest> = notifications
            .iter()
            .map(|n| (n.subscriber_process_identifier, n))
            .collect();
        assert_exact_single_payload(by_subscriber[&1], PropertyIdentifier::SILENCED);
        assert_exact_single_payload(by_subscriber[&2], PropertyIdentifier::OPERATION_EXPECTED);
        assert!(
            !by_subscriber.contains_key(&3),
            "whole-object subscription must stay silent without a PV/Status change"
        );
    }
}

#[tokio::test]
async fn reset_dispatch_fans_out_exact_pv_delta_without_event_state_blast() {
    use bacnet_types::enums::{LifeSafetyOperation, LifeSafetyState};

    for operation in [
        LifeSafetyOperation::RESET,
        LifeSafetyOperation::RESET_ALARM,
        LifeSafetyOperation::RESET_FAULT,
    ] {
        let mut point = LifeSafetyPointObject::new(1, "point").unwrap();
        point.set_present_value(LifeSafetyState::ALARM);
        point.set_operation_expected(operation);
        point.set_reset_executor(Arc::new(|_| {
            Ok(LifeSafetyPointResetCommit {
                present_value: Some(LifeSafetyState::QUIET),
                ..Default::default()
            })
        }));
        let mut db = clocked_test_database();
        db.add(Box::new(point)).unwrap();
        let fixture = DispatchFixture::new(
            db,
            [
                subscription(
                    Some(PropertyIdentifier::PRESENT_VALUE),
                    CovNotificationKind::Single,
                    1,
                ),
                subscription(None, CovNotificationKind::Single, 2),
                subscription(
                    Some(PropertyIdentifier::SILENCED),
                    CovNotificationKind::Single,
                    3,
                ),
            ],
        )
        .await;

        fixture
            .dispatch(
                0x41,
                ConfirmedServiceChoice::LIFE_SAFETY_OPERATION,
                encode_life_safety_operation(operation, point_oid()),
            )
            .await;
        let apdus = fixture.take_apdus();

        {
            let db = fixture.db.read().await;
            let object = db.get(&point_oid()).unwrap();
            assert_eq!(
                object
                    .read_property(PropertyIdentifier::PRESENT_VALUE, None)
                    .unwrap(),
                PropertyValue::Enumerated(LifeSafetyState::QUIET.to_raw())
            );
            assert_eq!(
                object
                    .read_property(PropertyIdentifier::EVENT_STATE, None)
                    .unwrap(),
                PropertyValue::Enumerated(0)
            );
        }

        assert!(matches!(apdus[0], Apdu::SimpleAck(_)));
        let notifications: Vec<_> = apdus[1..].iter().map(decode_cov_notification).collect();
        // PV property sub + whole-object sub fire; the untouched SILENCED
        // property sub stays silent.
        assert_eq!(
            notifications.len(),
            2,
            "reset {operation:?} must notify exactly the PV and whole-object subs"
        );
        for notification in &notifications {
            assert_exact_single_payload(notification, PropertyIdentifier::PRESENT_VALUE);
        }
        let subscribers: Vec<u32> = notifications
            .iter()
            .map(|n| n.subscriber_process_identifier)
            .collect();
        assert!(subscribers.contains(&1));
        assert!(subscribers.contains(&2));
        assert!(
            !subscribers.contains(&3),
            "untouched SILENCED property sub must stay silent"
        );
    }
}

fn zone_subscription(property: Option<PropertyIdentifier>, process_id: u32) -> CovSubscription {
    let mut sub = subscription(property, CovNotificationKind::Single, process_id);
    sub.monitored_object_identifier =
        ObjectIdentifier::new(ObjectType::LIFE_SAFETY_ZONE, 1).unwrap();
    sub
}

#[tokio::test]
async fn zone_silence_dispatch_leaves_the_tracking_value_subscription_silent() {
    use bacnet_types::enums::LifeSafetyOperation;

    let zone_oid = ObjectIdentifier::new(ObjectType::LIFE_SAFETY_ZONE, 1).unwrap();
    let mut zone = bacnet_objects::life_safety::LifeSafetyZoneObject::new(1, "zone").unwrap();
    zone.set_silenced(SilencedState::UNSILENCED);
    zone.set_operation_expected(LifeSafetyOperation::SILENCE);
    let mut db = clocked_test_database();
    db.add(Box::new(zone)).unwrap();
    let fixture = DispatchFixture::new(
        db,
        [
            zone_subscription(Some(PropertyIdentifier::SILENCED), 1),
            zone_subscription(None, 2),
            zone_subscription(Some(PropertyIdentifier::TRACKING_VALUE), 3),
        ],
    )
    .await;

    fixture
        .dispatch(
            0x42,
            ConfirmedServiceChoice::LIFE_SAFETY_OPERATION,
            encode_life_safety_operation(LifeSafetyOperation::SILENCE, zone_oid),
        )
        .await;
    let apdus = fixture.take_apdus();

    {
        let db = fixture.db.read().await;
        let object = db.get(&zone_oid).unwrap();
        assert_eq!(
            object
                .read_property(PropertyIdentifier::SILENCED, None)
                .unwrap(),
            PropertyValue::Enumerated(SilencedState::ALL_SILENCED.to_raw())
        );
        assert_eq!(
            object
                .read_property(PropertyIdentifier::EVENT_STATE, None)
                .unwrap(),
            PropertyValue::Enumerated(0)
        );
        assert_eq!(
            object
                .read_property(PropertyIdentifier::TRACKING_VALUE, None)
                .unwrap(),
            PropertyValue::Enumerated(LifeSafetyState::QUIET.to_raw())
        );
    }

    assert!(matches!(apdus[0], Apdu::SimpleAck(_)));
    let notifications: Vec<_> = apdus[1..].iter().map(decode_cov_notification).collect();
    assert_eq!(
        notifications.len(),
        1,
        "zone Silenced-only change notifies only the SILENCED property sub"
    );
    assert_eq!(notifications[0].subscriber_process_identifier, 1);
    assert_exact_single_payload(&notifications[0], PropertyIdentifier::SILENCED);
}

#[tokio::test]
async fn zone_reset_dispatch_notifies_a_committed_tracking_value_change() {
    use bacnet_objects::life_safety::LifeSafetyZoneResetCommit;
    use bacnet_types::enums::LifeSafetyOperation;

    let zone_oid = ObjectIdentifier::new(ObjectType::LIFE_SAFETY_ZONE, 1).unwrap();
    let mut zone = bacnet_objects::life_safety::LifeSafetyZoneObject::new(1, "zone").unwrap();
    zone.set_present_value(LifeSafetyState::ALARM);
    zone.set_tracking_value(LifeSafetyState::ALARM);
    zone.set_operation_expected(LifeSafetyOperation::RESET);
    zone.set_reset_executor(Arc::new(|_| {
        Ok(LifeSafetyZoneResetCommit {
            tracking_value: Some(LifeSafetyState::QUIET),
            ..Default::default()
        })
    }));
    let mut db = clocked_test_database();
    db.add(Box::new(zone)).unwrap();
    let fixture = DispatchFixture::new(
        db,
        [
            zone_subscription(Some(PropertyIdentifier::TRACKING_VALUE), 1),
            zone_subscription(None, 2),
            zone_subscription(Some(PropertyIdentifier::SILENCED), 3),
        ],
    )
    .await;

    fixture
        .dispatch(
            0x43,
            ConfirmedServiceChoice::LIFE_SAFETY_OPERATION,
            encode_life_safety_operation(LifeSafetyOperation::RESET, zone_oid),
        )
        .await;
    let apdus = fixture.take_apdus();

    {
        let db = fixture.db.read().await;
        let object = db.get(&zone_oid).unwrap();
        assert_eq!(
            object
                .read_property(PropertyIdentifier::TRACKING_VALUE, None)
                .unwrap(),
            PropertyValue::Enumerated(LifeSafetyState::QUIET.to_raw())
        );
        // The latched Present_Value was not part of the commit.
        assert_eq!(
            object
                .read_property(PropertyIdentifier::PRESENT_VALUE, None)
                .unwrap(),
            PropertyValue::Enumerated(LifeSafetyState::ALARM.to_raw())
        );
    }

    assert!(matches!(apdus[0], Apdu::SimpleAck(_)));
    let notifications: Vec<_> = apdus[1..].iter().map(decode_cov_notification).collect();
    // Only the Tracking_Value sub fires: Present_Value and Silenced held.
    assert_eq!(notifications.len(), 1, "{notifications:?}");
    assert_eq!(notifications[0].subscriber_process_identifier, 1);
    assert_exact_single_payload(&notifications[0], PropertyIdentifier::TRACKING_VALUE);
}