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
//! Encoded indexed writes distinguish an absent row from a served non-array.

use super::*;
use bacnet_objects::network_port::{BipPortConfig, NetworkPortObject};
use bacnet_objects::staging::{StagingConfig, StagingObject};
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;

const VENDOR: PropertyIdentifier = PropertyIdentifier::from_raw(5555);

#[path = "indexed_write_effects.rs"]
mod effects;

fn staging(names: bool) -> StagingObject {
    StagingObject::new(
        1,
        "stages",
        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![true],
                    deadband: 0.0,
                },
            ],
            target_references: vec![BACnetDeviceObjectReference {
                device_identifier: None,
                object_identifier: ObjectIdentifier::new(ObjectType::BINARY_OUTPUT, 1).unwrap(),
            }],
            stage_names: names.then(|| vec!["low".into(), "high".into()]),
        },
    )
    .unwrap()
}

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

fn write(
    db: &mut ObjectDatabase,
    oid: ObjectIdentifier,
    property: PropertyIdentifier,
    index: u32,
    value: Vec<u8>,
    multiple: bool,
) -> Result<(), Error> {
    let mut bytes = BytesMut::new();
    if multiple {
        WritePropertyMultipleRequest {
            list_of_write_access_specs: vec![WriteAccessSpecification {
                object_identifier: oid,
                list_of_properties: vec![BACnetPropertyValue {
                    property_identifier: property,
                    property_array_index: Some(index),
                    value,
                    priority: None,
                }],
            }],
        }
        .encode(&mut bytes)
        .unwrap();
        handle_write_property_multiple(db, &bytes).map(|_| ())
    } else {
        WritePropertyRequest {
            object_identifier: oid,
            property_identifier: property,
            property_array_index: Some(index),
            property_value: value,
            priority: None,
        }
        .encode(&mut bytes)
        .unwrap();
        handle_write_property(db, &bytes).map(|_| ())
    }
}

fn assert_error(result: Result<(), Error>, expected: ErrorCode) {
    assert!(
        matches!(result, Err(Error::Remote(RemoteError::Error { class, code }))
        if class == ErrorClass::PROPERTY && code == expected),
        "expected PROPERTY/{expected:?}, got {result:?}"
    );
}

fn assert_absent(object: Box<dyn BACnetObject>, property: PropertyIdentifier) {
    let oid = object.object_identifier();
    let watched = if oid.object_type() == ObjectType::STAGING {
        vec![
            PropertyIdentifier::STAGES,
            PropertyIdentifier::TARGET_REFERENCES,
            PropertyIdentifier::PRESENT_VALUE,
            PropertyIdentifier::PRESENT_STAGE,
        ]
    } else {
        vec![PropertyIdentifier::DESCRIPTION]
    };
    // Present_Stage is deliberately uninitialized in this standalone fixture.
    // Preserve both values and protocol errors instead of initializing it here.
    let snapshot = |object: &dyn BACnetObject| {
        watched
            .iter()
            .map(|property| {
                object
                    .read_property(*property, None)
                    .map_err(|error| match error {
                        Error::Remote(RemoteError::Error { class, code }) => (class, code),
                        other => panic!("unexpected snapshot error: {other:?}"),
                    })
            })
            .collect::<Vec<_>>()
    };
    let before = snapshot(object.as_ref());
    let mut db = ObjectDatabase::new();
    db.add(object).unwrap();
    let mut results = Vec::new();
    for multiple in [false, true] {
        // REAL with a one-octet payload is framed correctly but not a valid
        // application value. The indexed presence gate must run before decode.
        for input in [value(PropertyValue::Unsigned(1)), vec![0x41, 0]] {
            results.push((
                multiple,
                input.clone(),
                write(&mut db, oid, property, 1, input, multiple),
            ));
            let after = snapshot(db.get(&oid).unwrap());
            assert_eq!(
                after, before,
                "absent writes must leave object state intact"
            );
        }
    }
    assert!(
        results.iter().all(|(_, _, result)| matches!(result,
        Err(Error::Remote(RemoteError::Error { class, code })) if *class == ErrorClass::PROPERTY
            && *code == ErrorCode::UNKNOWN_PROPERTY)),
        "WP/WPM must report UNKNOWN_PROPERTY before value decode: {results:?}"
    );
}

#[test]
fn indexed_write_absent_analog_input_property_is_unknown() {
    assert_absent(
        Box::new(AnalogInputObject::new(1, "input", EngineeringUnits::DEGREES_CELSIUS).unwrap()),
        VENDOR,
    );
}

#[test]
fn indexed_write_absent_bip_network_port_property_is_unknown() {
    assert_absent(
        Box::new(NetworkPortObject::new_bip(1, "port", BipPortConfig::default()).unwrap()),
        VENDOR,
    );
}

#[test]
fn indexed_write_unprovisioned_stage_names_is_unknown() {
    assert_absent(Box::new(staging(false)), PropertyIdentifier::STAGE_NAMES);
}

#[test]
fn indexed_write_present_array_preserves_element_count_and_range_rules() {
    let object = staging(true);
    let oid = object.object_identifier();
    let mut db = ObjectDatabase::new();
    db.add(Box::new(object)).unwrap();
    for multiple in [false, true] {
        let text = if multiple { "multiple" } else { "single" };
        write(
            &mut db,
            oid,
            PropertyIdentifier::STAGE_NAMES,
            1,
            value(PropertyValue::CharacterString(text.into())),
            multiple,
        )
        .unwrap();
        let before = db
            .get(&oid)
            .unwrap()
            .read_property(PropertyIdentifier::STAGE_NAMES, None)
            .unwrap();
        assert_eq!(
            before,
            PropertyValue::List(vec![
                PropertyValue::CharacterString(text.into()),
                PropertyValue::CharacterString("high".into())
            ])
        );
        for (index, input, error) in [
            (
                0,
                value(PropertyValue::Unsigned(3)),
                ErrorCode::WRITE_ACCESS_DENIED,
            ),
            (
                3,
                value(PropertyValue::CharacterString("out of range".into())),
                ErrorCode::INVALID_ARRAY_INDEX,
            ),
            (1, vec![0x41, 0], ErrorCode::INVALID_DATA_ENCODING),
        ] {
            assert_error(
                write(
                    &mut db,
                    oid,
                    PropertyIdentifier::STAGE_NAMES,
                    index,
                    input,
                    multiple,
                ),
                error,
            );
            assert_eq!(
                db.get(&oid)
                    .unwrap()
                    .read_property(PropertyIdentifier::STAGE_NAMES, None)
                    .unwrap(),
                before
            );
        }
    }
}

#[test]
fn indexed_write_served_scalar_and_list_keep_predecode_not_array_error() {
    let objects: Vec<(Box<dyn BACnetObject>, PropertyIdentifier)> = vec![
        (
            Box::new(
                AnalogInputObject::new(1, "input", EngineeringUnits::DEGREES_CELSIUS).unwrap(),
            ),
            PropertyIdentifier::OBJECT_IDENTIFIER,
        ),
        (
            Box::new(bacnet_objects::schedule::CalendarObject::new(1, "calendar").unwrap()),
            PropertyIdentifier::DATE_LIST,
        ),
    ];
    for (object, property) in objects {
        let oid = object.object_identifier();
        let before = object.read_property(property, None).unwrap();
        let mut db = ObjectDatabase::new();
        db.add(object).unwrap();
        for multiple in [false, true] {
            for input in [value(PropertyValue::Unsigned(1)), vec![0x41, 0]] {
                assert_error(
                    write(&mut db, oid, property, 1, input, multiple),
                    ErrorCode::PROPERTY_IS_NOT_AN_ARRAY,
                );
                assert_eq!(
                    db.get(&oid).unwrap().read_property(property, None).unwrap(),
                    before
                );
            }
        }
    }
}

#[test]
fn indexed_write_bip_dns_array_remains_read_only() {
    let object = NetworkPortObject::new_bip(1, "port", BipPortConfig::default()).unwrap();
    let oid = object.object_identifier();
    let before = object
        .read_property(PropertyIdentifier::IP_DNS_SERVER, None)
        .unwrap();
    let mut db = ObjectDatabase::new();
    db.add(Box::new(object)).unwrap();
    for multiple in [false, true] {
        // The read-only object dispatch, not a new service range policy, owns
        // both count and element writes (including the out-of-range element).
        for index in [0, 1, 2] {
            assert_error(
                write(
                    &mut db,
                    oid,
                    PropertyIdentifier::IP_DNS_SERVER,
                    index,
                    value(PropertyValue::OctetString(vec![192, 0, 2, 1])),
                    multiple,
                ),
                ErrorCode::WRITE_ACCESS_DENIED,
            );
        }
        assert_eq!(
            db.get(&oid)
                .unwrap()
                .read_property(PropertyIdentifier::IP_DNS_SERVER, None)
                .unwrap(),
            before
        );
    }
}

#[test]
fn indexed_write_staging_structured_arrays_retain_object_dispatch() {
    use bacnet_encoding::constructed::{encode_device_object_reference, encode_stage_limit_value};
    let mut stage = BytesMut::new();
    encode_stage_limit_value(
        &mut stage,
        &BACnetStageLimitValue {
            limit: 0.5,
            values: vec![true],
            deadband: 0.0,
        },
    );
    let mut target = BytesMut::new();
    encode_device_object_reference(
        &mut target,
        &BACnetDeviceObjectReference {
            device_identifier: None,
            object_identifier: ObjectIdentifier::new(ObjectType::BINARY_OUTPUT, 2).unwrap(),
        },
    );
    for multiple in [false, true] {
        let object = staging(false);
        let oid = object.object_identifier();
        let mut db = ObjectDatabase::new();
        db.add(Box::new(object)).unwrap();
        for (property, input, past_end) in [
            (PropertyIdentifier::STAGES, stage.to_vec(), 3),
            (PropertyIdentifier::TARGET_REFERENCES, target.to_vec(), 2),
        ] {
            write(&mut db, oid, property, 1, input.clone(), multiple).unwrap();
            assert_eq!(
                db.get(&oid)
                    .unwrap()
                    .read_property(property, Some(1))
                    .unwrap(),
                PropertyValue::ApplicationData(input.clone())
            );
            let before = db.get(&oid).unwrap().read_property(property, None).unwrap();
            assert_error(
                write(
                    &mut db,
                    oid,
                    property,
                    0,
                    value(PropertyValue::Unsigned(3)),
                    multiple,
                ),
                ErrorCode::WRITE_ACCESS_DENIED,
            );
            assert_error(
                write(&mut db, oid, property, past_end, input, multiple),
                ErrorCode::INVALID_ARRAY_INDEX,
            );
            assert_eq!(
                db.get(&oid).unwrap().read_property(property, None).unwrap(),
                before
            );
        }
    }
}

struct VendorArray {
    value: PropertyValue,
}

impl BACnetObject for VendorArray {
    fn object_identifier(&self) -> ObjectIdentifier {
        ObjectIdentifier::new(ObjectType::from_raw(128), 1).unwrap()
    }
    fn object_name(&self) -> &str {
        "vendor-array"
    }
    fn read_property(
        &self,
        property: PropertyIdentifier,
        index: Option<u32>,
    ) -> Result<PropertyValue, Error> {
        assert_eq!((property, index), (VENDOR, Some(1)));
        Ok(self.value.clone())
    }
    fn write_property(
        &mut self,
        property: PropertyIdentifier,
        index: Option<u32>,
        value: PropertyValue,
        _: Option<u8>,
    ) -> Result<(), Error> {
        assert_eq!((property, index), (VENDOR, Some(1)));
        self.value = value;
        Ok(())
    }
    fn property_list(&self) -> std::borrow::Cow<'static, [PropertyIdentifier]> {
        std::borrow::Cow::Owned(vec![VENDOR])
    }
    fn is_array_property(&self, property: PropertyIdentifier) -> bool {
        property == VENDOR
    }
    // The optional metadata default remains empty; it is not an absence claim.
}

#[test]
fn indexed_write_empty_metadata_vendor_array_delegates_to_custom_writer() {
    let object = VendorArray {
        value: PropertyValue::Unsigned(0),
    };
    let oid = object.object_identifier();
    let mut db = ObjectDatabase::new();
    db.add(Box::new(object)).unwrap();
    for (multiple, number) in [(false, 17), (true, 29)] {
        write(
            &mut db,
            oid,
            VENDOR,
            1,
            value(PropertyValue::Unsigned(number)),
            multiple,
        )
        .unwrap();
        assert_eq!(
            db.get(&oid)
                .unwrap()
                .read_property(VENDOR, Some(1))
                .unwrap(),
            PropertyValue::Unsigned(number)
        );
        assert_error(
            write(
                &mut db,
                oid,
                PropertyIdentifier::DESCRIPTION,
                1,
                value(PropertyValue::Unsigned(1)),
                multiple,
            ),
            ErrorCode::PROPERTY_IS_NOT_AN_ARRAY,
        );
    }
}