bacnet-client 0.15.0

BACnet async client: TSM, segmentation, discovery, and service APIs
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
//! Device administration preserves routed service fields and unconfirmed delivery.
use super::*;
use crate::discovery::{DiscoveredDevice, RoutedDeviceConfig};
use bacnet_encoding::apdu::{self, Apdu, ConfirmedRequest, ErrorPdu, RejectPdu, SimpleAck};
use bacnet_encoding::npdu::{Npdu, NpduAddress, decode_npdu, encode_npdu};
use bacnet_services::device_mgmt::{
    DeviceCommunicationControlRequest, ReinitializeDeviceRequest, TimeSynchronizationRequest,
};
use bacnet_transport::loopback::LoopbackTransport;
use bacnet_transport::port::ReceivedNpdu;
use bacnet_types::MacAddr;
use bacnet_types::enums::{
    EnableDisable, ErrorClass, ErrorCode, ObjectType, ReinitializedState, RejectReason,
    Segmentation,
};
use bacnet_types::error::RemoteError;
use bacnet_types::primitives::{Date, ObjectIdentifier, Time};
use tokio::sync::mpsc;
use tokio::time::{Duration, timeout};

const INSTANCE: u32 = 1234;
const ROUTER: &[u8] = &[2];
const NETWORK: u16 = 100;
const STATION: &[u8] = &[5];

struct Peer {
    transport: LoopbackTransport,
    frames: mpsc::Receiver<ReceivedNpdu>,
    destinations: mpsc::UnboundedReceiver<MacAddr>,
    routed: bool,
    next_hop: &'static [u8],
}

async fn site(routed: bool) -> (BACnetClient<LoopbackTransport>, Peer) {
    let (mut local, mut remote) = LoopbackTransport::pair(&[1][..], ROUTER);
    local.set_broadcast_mac(&[0xff][..]);
    let destinations = local.record_unicast_destinations();
    let frames = remote.start().await.unwrap();
    let client = BACnetClient::generic_builder()
        .transport(local)
        .apdu_timeout_ms(1000)
        .apdu_retries(2)
        .build()
        .await
        .unwrap();
    if routed {
        client
            .add_routed_device(RoutedDeviceConfig {
                instance: INSTANCE,
                router_mac: ROUTER.to_vec(),
                remote_network: NETWORK,
                remote_mac: STATION.to_vec(),
                max_apdu_length: 1476,
                segmentation_supported: Segmentation::NONE,
                max_segments_accepted: None,
            })
            .await
            .unwrap();
    } else {
        client.add_device(INSTANCE, ROUTER).await.unwrap();
    }
    (
        client,
        Peer {
            transport: remote,
            frames,
            destinations,
            routed,
            next_hop: ROUTER,
        },
    )
}

impl Peer {
    async fn apdu(&mut self, expecting_reply: bool) -> Apdu {
        let frame = timeout(Duration::from_secs(5), self.frames.recv())
            .await
            .expect("request watchdog")
            .unwrap();
        assert!(!frame.link_layer_group);
        assert_eq!(
            self.destinations.recv().await.unwrap().as_slice(),
            self.next_hop
        );
        let npdu = decode_npdu(frame.npdu).unwrap();
        assert_eq!(
            npdu.expecting_reply, expecting_reply,
            "wrong expecting-reply flag"
        );
        assert_eq!(npdu.priority, NetworkPriority::Normal);
        if self.routed {
            let destination = npdu
                .destination
                .expect("administrative request lost DNET/DADR");
            assert_eq!(destination.network, NETWORK);
            assert_eq!(destination.mac_address.as_slice(), STATION);
        } else {
            assert!(npdu.destination.is_none());
        }
        apdu::decode_apdu(npdu.payload).unwrap()
    }
    async fn confirmed(&mut self, service: ConfirmedServiceChoice) -> ConfirmedRequest {
        let Apdu::ConfirmedRequest(request) = self.apdu(true).await else {
            panic!("expected confirmed request");
        };
        assert_eq!(request.service_choice, service);
        request
    }
    async fn send(&self, apdu: Apdu) {
        let mut payload = BytesMut::new();
        apdu::encode_apdu(&mut payload, &apdu).unwrap();
        let mut bytes = BytesMut::new();
        encode_npdu(
            &mut bytes,
            &Npdu {
                source: self.routed.then(|| NpduAddress {
                    network: NETWORK,
                    mac_address: MacAddr::from_slice(STATION),
                }),
                payload: payload.freeze(),
                ..Npdu::default()
            },
        )
        .unwrap();
        self.transport.send_unicast(&bytes, &[1]).await.unwrap();
    }
    async fn ack(&self, request: &ConfirmedRequest) {
        self.send(Apdu::SimpleAck(SimpleAck {
            invoke_id: request.invoke_id,
            service_choice: request.service_choice,
        }))
        .await;
    }
    fn empty(&mut self) {
        assert!(self.frames.try_recv().is_err());
        assert!(self.destinations.try_recv().is_err());
    }
}

fn date() -> Date {
    Date {
        year: 124,
        month: 7,
        day: 4,
        day_of_week: 4,
    }
}
fn time() -> Time {
    Time {
        hour: 13,
        minute: 27,
        second: 39,
        hundredths: 51,
    }
}

#[tokio::test(start_paused = true)]
async fn device_mgmt_confirmed_fields_and_discovered_local_fallback() {
    for routed in [true, false] {
        let (mut client, mut peer) = site(routed).await;
        for (state, duration, password) in [
            (EnableDisable::ENABLE, None, None),
            (EnableDisable::DISABLE, Some(0), None),
            (
                EnableDisable::DISABLE_INITIATION,
                Some(23),
                Some("control-key".to_owned()),
            ),
        ] {
            let (result, ()) = tokio::join!(
                client.device_communication_control_from_device(
                    INSTANCE,
                    state,
                    duration,
                    password.clone()
                ),
                async {
                    let request = peer
                        .confirmed(ConfirmedServiceChoice::DEVICE_COMMUNICATION_CONTROL)
                        .await;
                    assert_eq!(
                        DeviceCommunicationControlRequest::decode(&request.service_request)
                            .unwrap(),
                        DeviceCommunicationControlRequest {
                            time_duration: duration,
                            enable_disable: state,
                            password
                        }
                    );
                    peer.ack(&request).await;
                }
            );
            result.unwrap();
        }
        for (state, password) in [
            (ReinitializedState::WARMSTART, None),
            (
                ReinitializedState::START_BACKUP,
                Some("reinit-key".to_owned()),
            ),
        ] {
            let (result, ()) = tokio::join!(
                client.reinitialize_device_from_device(INSTANCE, state, password.clone()),
                async {
                    let request = peer
                        .confirmed(ConfirmedServiceChoice::REINITIALIZE_DEVICE)
                        .await;
                    assert_eq!(
                        ReinitializeDeviceRequest::decode(&request.service_request).unwrap(),
                        ReinitializeDeviceRequest {
                            reinitialized_state: state,
                            password
                        }
                    );
                    peer.ack(&request).await;
                }
            );
            result.unwrap();
        }
        client.stop().await.unwrap();
        peer.transport.stop().await.unwrap();
    }
}

#[tokio::test(start_paused = true)]
async fn device_mgmt_confirmed_protocol_errors_and_rejects_are_preserved() {
    let (mut client, mut peer) = site(true).await;
    let (result, ()) = tokio::join!(
        client.device_communication_control_from_device(
            INSTANCE,
            EnableDisable::ENABLE,
            None,
            None
        ),
        async {
            let request = peer
                .confirmed(ConfirmedServiceChoice::DEVICE_COMMUNICATION_CONTROL)
                .await;
            peer.send(Apdu::Error(ErrorPdu {
                invoke_id: request.invoke_id,
                service_choice: request.service_choice,
                error_class: ErrorClass::SECURITY,
                error_code: ErrorCode::PASSWORD_FAILURE,
                error_data: Bytes::new(),
            }))
            .await;
        }
    );
    assert!(matches!(
        result,
        Err(Error::Remote(RemoteError::Error {
            class: ErrorClass::SECURITY,
            code: ErrorCode::PASSWORD_FAILURE
        }))
    ));
    let (result, ()) = tokio::join!(
        client.reinitialize_device_from_device(INSTANCE, ReinitializedState::WARMSTART, None),
        async {
            let request = peer
                .confirmed(ConfirmedServiceChoice::REINITIALIZE_DEVICE)
                .await;
            peer.send(Apdu::Reject(RejectPdu {
                invoke_id: request.invoke_id,
                reject_reason: RejectReason::UNRECOGNIZED_SERVICE,
            }))
            .await;
        }
    );
    assert!(matches!(
        result,
        Err(Error::Remote(RemoteError::Reject {
            reason: RejectReason::UNRECOGNIZED_SERVICE
        }))
    ));
    client.stop().await.unwrap();
    peer.transport.stop().await.unwrap();
}

#[tokio::test(start_paused = true)]
async fn device_mgmt_time_services_send_once_without_reply_and_localize_known_network() {
    for mode in 0..3 {
        let (mut client, mut peer) = site(mode != 0).await;
        if mode == 2 {
            client
                .network
                .local_network_number()
                .publish(bacnet_types::network_number::NetworkNumber::configured(NETWORK).unwrap());
            peer.routed = false;
            peer.next_hop = STATION;
        }
        for utc in [false, true] {
            // Send completes before any peer task runs or answers, even with retries configured.
            if utc {
                client
                    .utc_time_synchronization_from_device(INSTANCE, date(), time())
                    .await
                    .unwrap();
            } else {
                client
                    .time_synchronization_from_device(INSTANCE, date(), time())
                    .await
                    .unwrap();
            }
            let Apdu::UnconfirmedRequest(request) = peer.apdu(false).await else {
                panic!("expected unconfirmed time service");
            };
            assert_eq!(
                request.service_choice,
                if utc {
                    UnconfirmedServiceChoice::UTC_TIME_SYNCHRONIZATION
                } else {
                    UnconfirmedServiceChoice::TIME_SYNCHRONIZATION
                }
            );
            assert_eq!(
                TimeSynchronizationRequest::decode(&request.service_request).unwrap(),
                TimeSynchronizationRequest {
                    date: date(),
                    time: time()
                }
            );
            tokio::time::advance(Duration::from_secs(10)).await;
            peer.empty();
        }
        client.stop().await.unwrap();
        peer.transport.stop().await.unwrap();
    }
}

#[tokio::test(start_paused = true)]
async fn device_mgmt_unknown_device_and_invalid_time_routes_send_nothing() {
    let (mut client, mut peer) = site(true).await;
    assert!(
        client
            .device_communication_control_from_device(
                INSTANCE + 1,
                EnableDisable::ENABLE,
                None,
                None
            )
            .await
            .is_err()
    );
    assert!(
        client
            .reinitialize_device_from_device(INSTANCE + 1, ReinitializedState::WARMSTART, None)
            .await
            .is_err()
    );
    assert!(
        client
            .time_synchronization_from_device(INSTANCE + 1, date(), time())
            .await
            .is_err()
    );
    assert!(
        client
            .utc_time_synchronization_from_device(INSTANCE + 1, date(), time())
            .await
            .is_err()
    );
    peer.empty();
    for (network, address) in [
        (0, vec![5]),
        (u16::MAX, vec![5]),
        (NETWORK, vec![]),
        (NETWORK, vec![5; 256]),
        (NETWORK, vec![0xff]),
    ] {
        if address == [0xff] {
            // A route naming this network must still name a single station.
            client
                .network
                .local_network_number()
                .publish(bacnet_types::network_number::NetworkNumber::configured(NETWORK).unwrap());
        }
        client.device_table.lock().await.upsert(DiscoveredDevice {
            object_identifier: ObjectIdentifier::new(ObjectType::DEVICE, INSTANCE + 1).unwrap(),
            mac_address: MacAddr::from_slice(ROUTER),
            max_apdu_length: 1476,
            segmentation_supported: Segmentation::NONE,
            max_segments_accepted: None,
            vendor_id: 0,
            last_seen: std::time::Instant::now(),
            source_network: Some(network),
            source_address: Some(MacAddr::from_slice(&address)),
        });
        assert!(
            client
                .time_synchronization_from_device(INSTANCE + 1, date(), time())
                .await
                .is_err()
        );
        assert!(
            client
                .utc_time_synchronization_from_device(INSTANCE + 1, date(), time())
                .await
                .is_err()
        );
        peer.empty();
    }
    client.stop().await.unwrap();
    peer.transport.stop().await.unwrap();
}

#[tokio::test(start_paused = true)]
async fn over_long_or_empty_passwords_fail_before_anything_is_sent() {
    // #2085: 21 characters (two octets each in UTF-8) never reach the wire;
    // #2094: nor does an empty password, which the caller omits instead.
    for (too_long, why, routed) in [
        ("é".repeat(21), "20-character limit", true),
        ("é".repeat(21), "20-character limit", false),
        (String::new(), "omit it", true),
        (String::new(), "omit it", false),
    ] {
        let (mut client, mut peer) = site(routed).await;
        let errors = [
            client
                .device_communication_control_from_device(
                    INSTANCE,
                    EnableDisable::DISABLE,
                    None,
                    Some(too_long.clone()),
                )
                .await
                .unwrap_err(),
            client
                .reinitialize_device_from_device(
                    INSTANCE,
                    ReinitializedState::COLDSTART,
                    Some(too_long.clone()),
                )
                .await
                .unwrap_err(),
            client
                .device_communication_control(
                    ROUTER,
                    EnableDisable::DISABLE,
                    None,
                    Some(too_long.clone()),
                )
                .await
                .unwrap_err(),
            client
                .reinitialize_device(
                    ROUTER,
                    ReinitializedState::COLDSTART,
                    Some(too_long.clone()),
                )
                .await
                .unwrap_err(),
        ];
        for err in errors {
            assert!(matches!(err, Error::Encode(_)), "{err:?}");
            assert!(err.to_string().contains(why), "{err}");
        }
        tokio::task::yield_now().await;
        peer.empty();
        client.stop().await.unwrap();
        peer.transport.stop().await.unwrap();
    }
}