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
//! Regression tests for issue #116: WriteProperty / WritePropertyMultiple /
//! local-write routing of `OBJECT_NAME` through the `ObjectDatabase` name
//! index.
//!
//! Before the fix, `write_property(OBJECT_NAME, …)` mutated the object's name
//! field in place without touching the database secondary name index, so:
//!   - lookups still resolved the old name and missed the new name, and
//!   - a duplicate name could be introduced via WriteProperty.
//!
//! These tests pin the index invariants: uniqueness is enforced on write, a
//! successful rename frees the old name and reserves the new one, and a failed
//! WritePropertyMultiple restores the pre-transaction index state.

use super::*;
use bacnet_objects::binary::BinaryValueObject;
use bacnet_objects::event_enrollment::EventEnrollmentObject;
use bacnet_types::error::RemoteError;
use bacnet_types::primitives::PropertyValue;

/// Build a `WritePropertyRequest` body for `OBJECT_NAME` on `oid` set to `name`.
fn encode_name_write(oid: ObjectIdentifier, name: &str) -> Vec<u8> {
    let mut value_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut value_buf, name).unwrap();
    let request = WritePropertyRequest {
        object_identifier: oid,
        property_identifier: PropertyIdentifier::OBJECT_NAME,
        property_array_index: None,
        property_value: value_buf.to_vec(),
        priority: None,
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();
    buf.to_vec()
}

/// A name another object holds is PROPERTY / DUPLICATE_NAME, the pair the
/// WriteProperty and WritePropertyMultiple error tables give (Clauses
/// 15.9.1.3.1 and 15.10.1.3.1).
fn assert_duplicate_name<T: std::fmt::Debug>(result: Result<T, Error>) {
    match result {
        Err(Error::Remote(RemoteError::Error { class, code })) => assert_eq!(
            (class, code),
            (ErrorClass::PROPERTY, ErrorCode::DUPLICATE_NAME)
        ),
        other => panic!("expected PROPERTY / DUPLICATE_NAME, got {other:?}"),
    }
}

/// Two objects with distinct names live in the database.
fn db_with_two_bvs() -> (ObjectDatabase, ObjectIdentifier, ObjectIdentifier) {
    let mut db = ObjectDatabase::new();
    let a = BinaryValueObject::new(1, "BV-A").unwrap();
    let b = BinaryValueObject::new(2, "BV-B").unwrap();
    db.add(Box::new(a)).unwrap();
    db.add(Box::new(b)).unwrap();
    let oid_a = ObjectIdentifier::new(ObjectType::BINARY_VALUE, 1).unwrap();
    let oid_b = ObjectIdentifier::new(ObjectType::BINARY_VALUE, 2).unwrap();
    (db, oid_a, oid_b)
}

#[test]
fn write_object_name_rejects_duplicate() {
    let (mut db, oid_a, _oid_b) = db_with_two_bvs();

    // Renaming A to "BV-B" (owned by B) must be rejected up front.
    let buf = encode_name_write(oid_a, "BV-B");
    assert_duplicate_name(handle_write_property(&mut db, &buf));

    // Index untouched: A is still "BV-A", B still owns "BV-B".
    assert!(db.find_by_name("BV-A").is_some());
    assert!(db.find_by_name("BV-B").is_some());
    assert_eq!(
        db.get(&oid_a).unwrap().object_name(),
        "BV-A",
        "rejected write must not mutate the object name"
    );
}

#[test]
fn write_object_name_rename_refreshes_index() {
    let (mut db, oid_a, oid_b) = db_with_two_bvs();

    // Rename A from "BV-A" to "BV-A2".
    let buf = encode_name_write(oid_a, "BV-A2");
    handle_write_property(&mut db, &buf).unwrap();

    // Old name freed, new name resolves to A.
    assert!(db.find_by_name("BV-A").is_none(), "old name must be freed");
    let found = db.find_by_name("BV-A2").expect("new name must resolve");
    assert_eq!(found.object_identifier(), oid_a);
    assert_eq!(db.get(&oid_a).unwrap().object_name(), "BV-A2");

    // A third object can now reclaim the freed old name.
    let c = BinaryValueObject::new(3, "BV-A").unwrap();
    db.add(Box::new(c)).unwrap();
    assert!(db.find_by_name("BV-A").is_some());

    // B was untouched by the rename.
    assert_eq!(db.get(&oid_b).unwrap().object_name(), "BV-B");
}

#[test]
fn event_enrollment_name_write_refreshes_index_and_rejects_duplicate() {
    let mut db = ObjectDatabase::new();
    let enrollment = EventEnrollmentObject::new(1, "EE-A", EventType::CHANGE_OF_BITSTRING).unwrap();
    let occupied = BinaryValueObject::new(1, "Occupied").unwrap();
    let oid = enrollment.object_identifier();
    db.add(Box::new(enrollment)).unwrap();
    db.add(Box::new(occupied)).unwrap();

    handle_write_property(&mut db, &encode_name_write(oid, "EE-Renamed")).unwrap();

    assert!(db.find_by_name("EE-A").is_none());
    assert_eq!(
        db.find_by_name("EE-Renamed").unwrap().object_identifier(),
        oid
    );

    assert_duplicate_name(handle_write_property(
        &mut db,
        &encode_name_write(oid, "Occupied"),
    ));
    assert_eq!(db.get(&oid).unwrap().object_name(), "EE-Renamed");
    assert_eq!(
        db.find_by_name("EE-Renamed").unwrap().object_identifier(),
        oid
    );
}

#[test]
fn write_object_name_empty_or_wrong_type_still_rejected() {
    let (mut db, oid_a, _oid_b) = db_with_two_bvs();

    // Empty name → VALUE_OUT_OF_RANGE (the object's own write route rejects it).
    let buf = encode_name_write(oid_a, "");
    assert!(handle_write_property(&mut db, &buf).is_err());
    assert_eq!(db.get(&oid_a).unwrap().object_name(), "BV-A");

    // Wrong type (Unsigned) → INVALID_DATA_TYPE, and the name index is left
    // intact (no spurious mapping created).
    let mut value_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_unsigned(&mut value_buf, 7);
    let request = WritePropertyRequest {
        object_identifier: oid_a,
        property_identifier: PropertyIdentifier::OBJECT_NAME,
        property_array_index: None,
        property_value: value_buf.to_vec(),
        priority: None,
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();
    assert!(handle_write_property(&mut db, &buf).is_err());
    assert_eq!(db.get(&oid_a).unwrap().object_name(), "BV-A");
    assert!(db.find_by_name("BV-A").is_some());
}

#[test]
fn write_property_multiple_name_rename_refreshes_index() {
    let (mut db, oid_a, _oid_b) = db_with_two_bvs();

    // One spec renaming A to "BV-A2". A second spec writes a benign prop on the
    // same object so the multi-write path exercises commit + index refresh.
    let mut name_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut name_buf, "BV-A2").unwrap();
    let mut desc_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut desc_buf, "renamed").unwrap();

    let request = WritePropertyMultipleRequest {
        list_of_write_access_specs: vec![bacnet_services::wpm::WriteAccessSpecification {
            object_identifier: oid_a,
            list_of_properties: vec![
                bacnet_services::common::BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::OBJECT_NAME,
                    property_array_index: None,
                    value: name_buf.to_vec(),
                    priority: None,
                },
                bacnet_services::common::BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::DESCRIPTION,
                    property_array_index: None,
                    value: desc_buf.to_vec(),
                    priority: None,
                },
            ],
        }],
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();

    handle_write_property_multiple(&mut db, &buf).unwrap();

    assert!(db.find_by_name("BV-A").is_none());
    assert_eq!(db.get(&oid_a).unwrap().object_name(), "BV-A2");
    let desc = db
        .get(&oid_a)
        .unwrap()
        .read_property(PropertyIdentifier::DESCRIPTION, None)
        .unwrap();
    match desc {
        PropertyValue::CharacterString(s) => assert_eq!(s, "renamed"),
        other => panic!("expected CharacterString, got {other:?}"),
    }
}

#[test]
fn write_property_multiple_failed_attempt_is_mutation_free_and_prefix_index_stays_committed() {
    let (mut db, oid_a, oid_b) = db_with_two_bvs();

    // First spec renames A to "BV-B" — but B already owns "BV-B", so the
    // duplicate-name check must reject the *whole* transaction before any
    // mutation. The object name and index are left as before.
    let mut name_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut name_buf, "BV-B").unwrap();

    let request = WritePropertyMultipleRequest {
        list_of_write_access_specs: vec![bacnet_services::wpm::WriteAccessSpecification {
            object_identifier: oid_a,
            list_of_properties: vec![bacnet_services::common::BACnetPropertyValue {
                property_identifier: PropertyIdentifier::OBJECT_NAME,
                property_array_index: None,
                value: name_buf.to_vec(),
                priority: None,
            }],
        }],
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();

    assert_duplicate_name(handle_write_property_multiple(&mut db, &buf));
    assert_eq!(db.get(&oid_a).unwrap().object_name(), "BV-A");
    assert_eq!(db.get(&oid_b).unwrap().object_name(), "BV-B");
    assert!(db.find_by_name("BV-A").is_some());
    assert!(db.find_by_name("BV-B").is_some());

    // Rename A to a free name, then fail on a read-only property. The rename
    // and its database index update are the successful committed prefix.
    let mut good_name_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut good_name_buf, "BV-A2").unwrap();
    // OBJECT_TYPE is read-only → write_property returns WRITE_ACCESS_DENIED.
    let mut bad_type_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_enumerated(&mut bad_type_buf, 5);

    let request = WritePropertyMultipleRequest {
        list_of_write_access_specs: vec![bacnet_services::wpm::WriteAccessSpecification {
            object_identifier: oid_a,
            list_of_properties: vec![
                bacnet_services::common::BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::OBJECT_NAME,
                    property_array_index: None,
                    value: good_name_buf.to_vec(),
                    priority: None,
                },
                bacnet_services::common::BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::OBJECT_TYPE,
                    property_array_index: None,
                    value: bad_type_buf.to_vec(),
                    priority: None,
                },
            ],
        }],
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();

    assert!(
        handle_write_property_multiple(&mut db, &buf).is_err(),
        "read-only write must fail the transaction"
    );

    assert_eq!(
        db.get(&oid_a).unwrap().object_name(),
        "BV-A2",
        "the successful rename remains committed"
    );
    assert!(
        db.find_by_name("BV-A2").is_some(),
        "the committed new name stays indexed"
    );
    assert!(
        db.find_by_name("BV-A").is_none(),
        "the committed rename keeps the old name free"
    );
}

#[test]
fn remove_after_rename_frees_current_name_only() {
    let (mut db, oid_a, _oid_b) = db_with_two_bvs();

    // Rename A → "BV-A2", then remove A. Only the *current* name should be
    // freed (the old name was already freed at rename time).
    let buf = encode_name_write(oid_a, "BV-A2");
    handle_write_property(&mut db, &buf).unwrap();
    assert!(db.find_by_name("BV-A").is_none());
    assert!(db.find_by_name("BV-A2").is_some());

    db.remove(&oid_a).unwrap();
    assert!(
        db.find_by_name("BV-A2").is_none(),
        "remove frees current name"
    );
    // The freed old name stays free.
    assert!(db.find_by_name("BV-A").is_none());
}

#[test]
fn write_object_name_noop_rename_to_same_name_succeeds() {
    // Renaming an object to its own current name is a no-op that must succeed:
    // check_name_available treats a name already owned by `oid` as available.
    let (mut db, oid_a, _oid_b) = db_with_two_bvs();
    let buf = encode_name_write(oid_a, "BV-A");
    handle_write_property(&mut db, &buf).unwrap();
    assert_eq!(db.get(&oid_a).unwrap().object_name(), "BV-A");
    assert!(db.find_by_name("BV-A").is_some());
    // B is unaffected.
    assert!(db.find_by_name("BV-B").is_some());
}

#[test]
fn write_property_multiple_cross_object_name_move() {
    // A single WPM that renames A → "BV-A2" and B → "BV-A" (B takes A's freed
    // old name). This must succeed because each check runs inside the commit
    // loop AFTER prior writes have refreshed the index, so B's check sees
    // "BV-A" as free.
    let (mut db, oid_a, oid_b) = db_with_two_bvs();

    let mut a_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut a_buf, "BV-A2").unwrap();
    let mut b_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut b_buf, "BV-A").unwrap();

    let request = WritePropertyMultipleRequest {
        list_of_write_access_specs: vec![
            bacnet_services::wpm::WriteAccessSpecification {
                object_identifier: oid_a,
                list_of_properties: vec![bacnet_services::common::BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::OBJECT_NAME,
                    property_array_index: None,
                    value: a_buf.to_vec(),
                    priority: None,
                }],
            },
            bacnet_services::wpm::WriteAccessSpecification {
                object_identifier: oid_b,
                list_of_properties: vec![bacnet_services::common::BACnetPropertyValue {
                    property_identifier: PropertyIdentifier::OBJECT_NAME,
                    property_array_index: None,
                    value: b_buf.to_vec(),
                    priority: None,
                }],
            },
        ],
    };
    let mut buf = BytesMut::new();
    request.encode(&mut buf).unwrap();

    handle_write_property_multiple(&mut db, &buf).unwrap();
    assert_eq!(db.get(&oid_a).unwrap().object_name(), "BV-A2");
    assert_eq!(db.get(&oid_b).unwrap().object_name(), "BV-A");
    assert_eq!(db.find_by_name("BV-A").unwrap().object_identifier(), oid_b);
    assert_eq!(db.find_by_name("BV-A2").unwrap().object_identifier(), oid_a);
    // B's old name is freed.
    assert!(db.find_by_name("BV-B").is_none());
}

#[test]
fn create_object_with_object_name_initial_value_refreshes_index() {
    // CreateObject with an OBJECT_NAME initial value must route through the
    // database name index: the created object is added under a default name,
    // then the initial OBJECT_NAME write renames it and the index must follow.
    let mut db = ObjectDatabase::new();

    let mut name_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut name_buf, "Custom-Name").unwrap();

    let req = CreateObjectRequest {
        object_specifier: ObjectSpecifier::Type(ObjectType::BINARY_VALUE),
        list_of_initial_values: vec![bacnet_services::common::BACnetPropertyValue {
            property_identifier: PropertyIdentifier::OBJECT_NAME,
            property_array_index: None,
            value: name_buf.to_vec(),
            priority: None,
        }],
    };
    let mut buf = BytesMut::new();
    req.encode(&mut buf);

    let mut ack_buf = BytesMut::new();
    handle_create_object(&mut db, &buf, &mut ack_buf).unwrap();

    // The created object must be findable by its initial Object_Name, and the
    // default name must be freed.
    let obj = db
        .find_by_name("Custom-Name")
        .expect("initial name resolves");
    let created_oid = obj.object_identifier();
    assert_eq!(db.get(&created_oid).unwrap().object_name(), "Custom-Name");
    assert!(
        db.find_by_name("BINARY_VALUE-1").is_none(),
        "default name must be freed after rename"
    );
}

#[test]
fn create_object_duplicate_object_name_initial_value_rejected_and_rolled_back() {
    // CreateObject with an OBJECT_NAME initial value that collides with an
    // existing object must be rejected, and the created object removed (so the
    // index and object count are unchanged).
    let (mut db, _oid_a, _oid_b) = db_with_two_bvs();
    let before_len = db.len();

    let mut name_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut name_buf, "BV-B").unwrap();

    let req = CreateObjectRequest {
        object_specifier: ObjectSpecifier::Type(ObjectType::BINARY_VALUE),
        list_of_initial_values: vec![bacnet_services::common::BACnetPropertyValue {
            property_identifier: PropertyIdentifier::OBJECT_NAME,
            property_array_index: None,
            value: name_buf.to_vec(),
            priority: None,
        }],
    };
    let mut buf = BytesMut::new();
    req.encode(&mut buf);

    // CreateObject's table (15.3.1.3.1) has no row for a name in use; the
    // initial value is refused as WriteProperty refuses it, PROPERTY /
    // DUPLICATE_NAME, naming its position in the list.
    assert_eq!(
        super::list_refusal(handle_create_object(&mut db, &buf, &mut BytesMut::new())),
        (ErrorClass::PROPERTY, ErrorCode::DUPLICATE_NAME, 1)
    );
    assert_eq!(
        db.len(),
        before_len,
        "created object must be removed on failure"
    );
    // The colliding name still maps only to the original owner.
    assert!(db.find_by_name("BV-B").is_some());
}

#[test]
fn create_object_rename_then_later_failure_removes_renamed_object() {
    // An OBJECT_NAME initial value renames the created object (refreshing the
    // index), then a *subsequent* initial value fails. The created object must
    // be removed, and ObjectDatabase::remove must free the *current* (renamed)
    // name — not the stale default name — so the renamed name is reclaimable.
    let mut db = ObjectDatabase::new();
    let before_len = db.len();

    let mut name_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut name_buf, "Fresh-Name").unwrap();
    // OBJECT_TYPE is read-only → write_property returns WRITE_ACCESS_DENIED,
    // failing the transaction AFTER the OBJECT_NAME rename committed.
    let mut bad_type_buf = BytesMut::new();
    bacnet_encoding::primitives::encode_app_enumerated(&mut bad_type_buf, 5);

    let req = CreateObjectRequest {
        object_specifier: ObjectSpecifier::Type(ObjectType::BINARY_VALUE),
        list_of_initial_values: vec![
            bacnet_services::common::BACnetPropertyValue {
                property_identifier: PropertyIdentifier::OBJECT_NAME,
                property_array_index: None,
                value: name_buf.to_vec(),
                priority: None,
            },
            bacnet_services::common::BACnetPropertyValue {
                property_identifier: PropertyIdentifier::OBJECT_TYPE,
                property_array_index: None,
                value: bad_type_buf.to_vec(),
                priority: None,
            },
        ],
    };
    let mut buf = BytesMut::new();
    req.encode(&mut buf);

    assert!(
        handle_create_object(&mut db, &buf, &mut BytesMut::new()).is_err(),
        "read-only initial value must fail the create"
    );
    assert_eq!(
        db.len(),
        before_len,
        "created object must be removed on failure"
    );
    // The renamed name was freed by remove (not stranded in the index), and a
    // new object can reclaim it.
    assert!(
        db.find_by_name("Fresh-Name").is_none(),
        "remove must free the current (renamed) name"
    );
    db.add(Box::new(BinaryValueObject::new(9, "Fresh-Name").unwrap()))
        .unwrap();
    assert!(db.find_by_name("Fresh-Name").is_some());
}