bacnet-emb 0.13.30

A bacnet library for embedded systems (no_std)
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
/// This module is meant to be a very basic way to interact with a BACnet IP network in a simple request / response manner
/// It automatically links up requests with responses using an invoke_id which only really works when you send one request at a time.
/// If you intend to fire off many simultaneous requests then you should keep track of invoke_ids and handle congestion and packet ordering yourself.
/// Your NetworkIo implementation is responsible for timeout detection for reads and writes.
/// This is an async-first module but you can run it in a native blocking way if you like.
///   The `maybe_async` crate is used to avoid code duplication and completely stips away async code when the `is_sync` feature flag is set.
/// If you are having trouble with the borrow checker try enabling the `alloc` feature to make BACnet objects fully owned
use core::{
    fmt::Debug,
    sync::atomic::{AtomicU8, Ordering},
};

use alloc::vec::Vec;
use maybe_async::maybe_async;

use crate::{
    application_protocol::{
        application_pdu::ApplicationPdu,
        confirmed::{
            ComplexAck, ComplexAckService, ConfirmedRequest, ConfirmedRequestService, SimpleAck,
        },
        services::{
            change_of_value::{CovNotification, SubscribeCov},
            i_am::IAm,
            read_property::{ReadProperty, ReadPropertyAck},
            read_property_multiple::{ReadPropertyMultiple, ReadPropertyMultipleAck},
            read_range::{ReadRange, ReadRangeAck},
            time_synchronization::TimeSynchronization,
            who_is::WhoIs,
            write_property::WriteProperty,
            write_property_multiple::WritePropertyMultiple,
        },
        unconfirmed::UnconfirmedRequest,
    },
    common::{
        error::Error,
        io::{Reader, Writer},
    },
    network_protocol::{
        data_link::{DataLink, DataLinkFunction},
        network_pdu::{DestinationAddress, MessagePriority, NetworkAddress, NetworkMessage, NetworkPdu},
    },
};

#[derive(Debug)]
pub struct Bacnet<T>
where
    T: NetworkIo + Debug,
{
    pub io: T,
    invoke_id: AtomicU8,
}

#[allow(async_fn_in_trait)]
#[cfg(feature = "defmt")]
#[maybe_async(AFIT)] // AFIT - Async Function In Trait
pub trait NetworkIo {
    type Error: Debug + defmt::Format;
    async fn read(&self, buf: &mut [u8]) -> Result<usize, Self::Error>;
    async fn write(&self, buf: &[u8]) -> Result<usize, Self::Error>;
}

#[cfg(not(feature = "defmt"))]
#[allow(async_fn_in_trait)]
#[maybe_async(AFIT)] // AFIT - Async Function In Trait
pub trait NetworkIo {
    type Error: Debug;

    async fn read(&self, buf: &mut [u8]) -> Result<usize, Self::Error>;
    async fn write(&self, buf: &[u8]) -> Result<usize, Self::Error>;
    async fn disconnect(&self) -> Result<bool, Self::Error>;
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum BacnetError<T>
where
    T: NetworkIo,
{
    Io(T::Error),
    Codec(Error),
    InvokeId(InvokeIdError),
}

impl<T: NetworkIo> From<Error> for BacnetError<T> {
    fn from(value: Error) -> Self {
        Self::Codec(value)
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct InvokeIdError {
    pub expected: u8,
    pub actual: u8,
}

impl<T> Bacnet<T>
where
    T: NetworkIo + Debug,
{
    pub fn new(io: T) -> Self {
        Self {
            io,
            invoke_id: AtomicU8::new(0),
        }
    }

    /// Returns the socket back to the caller and consumes self
    pub fn into_inner(self) -> T {
        self.io
    }

    #[maybe_async()]
    pub async fn who_is(&self, buf: &mut [u8]) -> Result<Option<Vec<IAm>>, BacnetError<T>> {
        let apdu = ApplicationPdu::UnconfirmedRequest(UnconfirmedRequest::WhoIs(WhoIs {}));
        let dst = Some(DestinationAddress::new(0xffff, None));
        let message = NetworkMessage::Apdu(apdu);
        let npdu = NetworkPdu::new(None, dst, false, MessagePriority::Normal, message);
        let data_link = DataLink::new(DataLinkFunction::OriginalBroadcastNpdu, Some(npdu));

        let mut writer = Writer::new(buf);
        data_link.encode(&mut writer);

        // send packet until we get a reply
        let buffer = writer.to_bytes();

        self.io.write(buffer).await.map_err(BacnetError::Io)?;

        let mut iams:Vec<IAm> = Vec::new();

        // receive reply
        for _ in 0..5 {

            match self.io.read(buf).await{
                Ok(n) => {

                    let buf = &buf[..n];

                    // use the DataLink codec to decode the bytes
                    let mut reader = Reader::default();
                    let message = DataLink::decode(&mut reader, buf).map_err(BacnetError::Codec)?;

                    if let Some(npdu) = message.npdu {

                        if let Some(dst_src) = npdu.src {

                            if let NetworkMessage::Apdu(ApplicationPdu::UnconfirmedRequest(
                                UnconfirmedRequest::IAm(iam),
                            )) = npdu.network_message
                            {
                                let mut iam = iam.clone();
                                iam.dst_addr = Some(dst_src);

                                iams.push(iam);
                            }

                        }
                    }
                },
                Err(_) => {
                    
                    break;
                }
            }
            
        }

        Ok(Some(iams))
    }

    #[maybe_async()]
    #[cfg_attr(feature = "alloc", bacnet_macros::remove_lifetimes_from_fn_args)]
    pub async fn read_property_multiple<'a>(
        &self,
        buf: &'a mut [u8],
        request: ReadPropertyMultiple<'_>,
        addr: Option<NetworkAddress>,
    ) -> Result<ReadPropertyMultipleAck<'a>, BacnetError<T>> {

        let service = ConfirmedRequestService::ReadPropertyMultiple(request);

        if let Some(ack) = self.send_and_receive_complex_ack(buf, service, addr).await? {
            match ack.service {
                ComplexAckService::ReadPropertyMultiple(ack) => Ok(ack),
                _ => Err(BacnetError::Codec(Error::ConvertDataLink(
                    "apdu message is not a ComplexAckService ReadPropertyMultipleAck",
                ))),
            }
        } else {
            Err(BacnetError::Codec(Error::ConvertDataLink(
                "apdu message is not a ComplexAckService ReadPropertyMultipleAck",
            )))
        }
    }

    #[maybe_async()]
    #[cfg_attr(feature = "alloc", bacnet_macros::remove_lifetimes_from_fn_args)]
    pub async fn read_property<'a>(
        &self,
        buf: &'a mut [u8],
        request: ReadProperty,
        addr: Option<NetworkAddress>,
    ) -> Result<ReadPropertyAck<'a>, BacnetError<T>> {

        let service = ConfirmedRequestService::ReadProperty(request);
        
        if let Some(ack) = self.send_and_receive_complex_ack(buf, service, addr).await? {
        
            match ack.service {
                ComplexAckService::ReadProperty(ack) => Ok(ack),
                _ => Err(BacnetError::Codec(Error::ConvertDataLink(
                    "apdu message is not a ComplexAckService ReadPropertyAck",
                ))),
            }
        } else {
                    Err(BacnetError::Codec(Error::ConvertDataLink(
                    "apdu message is not a ComplexAckService ReadPropertyAck",
                )))
        }
    }

    #[maybe_async()]
    pub async fn subscribe_change_of_value(
        &self,
        buf: &mut [u8],
        request: SubscribeCov,
    ) -> Result<(), BacnetError<T>> {
        let service = ConfirmedRequestService::SubscribeCov(request);
        let _ack = self.send_and_receive_simple_ack(buf, service, None).await?;
        Ok(())
    }

    #[maybe_async()]
    #[cfg_attr(feature = "alloc", bacnet_macros::remove_lifetimes_from_fn_args)]
    pub async fn read_change_of_value<'a>(
        &self,
        buf: &'a mut [u8],
    ) -> Result<Option<CovNotification<'a>>, BacnetError<T>> {
        let n = self.io.read(buf).await.map_err(BacnetError::Io)?;
        let mut reader = Reader::default();
        let message = DataLink::decode(&mut reader, &buf[..n])?;

        if let Some(npdu) = message.npdu {
            if let NetworkMessage::Apdu(ApplicationPdu::UnconfirmedRequest(
                UnconfirmedRequest::CovNotification(x),
            )) = npdu.network_message
            {
                return Ok(Some(x));
            }
        };

        Ok(None)
    }

    #[maybe_async()]
    #[cfg_attr(feature = "alloc", bacnet_macros::remove_lifetimes_from_fn_args)]
    pub async fn read_range<'a>(
        &self,
        buf: &'a mut [u8],
        request: ReadRange,
    ) -> Result<ReadRangeAck<'a>, BacnetError<T>> {
        let service = ConfirmedRequestService::ReadRange(request);
        
        if let Some(ack) = self.send_and_receive_complex_ack(buf, service, None).await? {

            match ack.service {
                ComplexAckService::ReadRange(ack) => Ok(ack),
                _ => Err(BacnetError::Codec(Error::ConvertDataLink(
                    "apdu message is not a ComplexAckService ReadRangeAck",
                ))),
            }

        } else {
                Err(BacnetError::Codec(Error::ConvertDataLink(
                    "apdu message is not a ComplexAckService ReadRangeAck",
                )))
            
        }
    }

    #[maybe_async()]
    pub async fn write_property<'a>(
        &self,
        buf: &mut [u8],
        request: WriteProperty<'_>,
        addr: Option<NetworkAddress>,
    ) -> Result<(), BacnetError<T>> {
        let service = ConfirmedRequestService::WriteProperty(request);
        let _ack = self.send_and_receive_simple_ack(buf, service, addr).await?;
        Ok(())
    }

    /// Write multiple properties to one or more objects in a single request.
    /// This is more efficient than calling write_property multiple times.
    ///
    /// # Arguments
    /// * `buf` - Buffer for encoding/decoding the BACnet message
    /// * `request` - WritePropertyMultiple request containing objects and their property writes
    /// * `addr` - Optional network address of the target device
    ///
    /// # Returns
    /// * `Ok(())` - All properties were written successfully
    /// * `Err(BacnetError)` - Error occurred during the write operation
    ///
    /// # Example
    /// ```rust
    /// use bacnet_emb::{
    ///     application_protocol::services::write_property_multiple::{WritePropertyMultiple, WritePropertyMultipleObject, WritePropertyRequest},
    ///     application_protocol::primitives::data_value::ApplicationDataValueWrite,
    ///     common::object_id::{ObjectId, ObjectType},
    ///     common::property_id::PropertyId,
    /// };
    ///
    /// // Create write requests for a single object
    /// let writes = vec![
    ///     WritePropertyRequest::new(
    ///         PropertyId::PropPresentValue,
    ///         None,
    ///         ApplicationDataValueWrite::Real(22.5),
    ///         None,
    ///     ),
    ///     WritePropertyRequest::new(
    ///         PropertyId::PropPriorityArray,
    ///         None,
    ///         ApplicationDataValueWrite::Boolean(true),
    ///         Some(8),
    ///     ),
    /// ];
    ///
    /// let object = WritePropertyMultipleObject::new(
    ///     ObjectId::new(ObjectType::AnalogInput, 0),
    ///     writes,
    /// );
    ///
    /// let request = WritePropertyMultiple::new(vec![object]);
    /// bacnet.write_property_multiple(&mut buffer, request, None).await?;
    /// ```
    #[maybe_async()]
    pub async fn write_property_multiple<'a>(
        &self,
        buf: &mut [u8],
        request: WritePropertyMultiple<'_>,
        addr: Option<NetworkAddress>,
    ) -> Result<(), BacnetError<T>> {
        let service = ConfirmedRequestService::WritePropertyMultiple(request);
        let _ack = self.send_and_receive_simple_ack(buf, service, addr).await?;
        Ok(())
    }

    #[maybe_async()]
    pub async fn time_sync(
        &self,
        buf: &mut [u8],
        request: TimeSynchronization,
    ) -> Result<(), BacnetError<T>> {
        let service = UnconfirmedRequest::TimeSynchronization(request);
        self.send_unconfirmed(buf, service).await
    }

    /*
    #[maybe_async()]
    #[cfg_attr(feature = "alloc", bacnet_macros::remove_lifetimes_from_fn_args)]
    async fn send_and_receive_complex_ack<'a>(
        &self,
        buf: &'a mut [u8],
        service: ConfirmedRequestService<'_>,
        addr: Option<NetworkAddress>,
    ) -> Result<ComplexAck<'a>, BacnetError<T>> {
        
        let invoke_id = self.send_confirmed(buf, service, addr).await?;

        loop {
            // receive reply
            let n = self.io.read(buf).await.map_err(BacnetError::Io)?;
            let buf = &buf[..n];

            // use the DataLink codec to decode the bytes
            let mut reader = Reader::default();
            let message = DataLink::decode(&mut reader, buf).map_err(BacnetError::Codec)?;

            match message.npdu {
                Some(x) => match x.network_message {
                    NetworkMessage::Apdu(ApplicationPdu::ComplexAck(ack)) => {
                        // ignore earier messages
                        if ack.invoke_id < invoke_id {
                            continue;
                        }

                        // return message is expected to have the same invoke_id as the request (return error if later invoke id)
                        Self::check_invoke_id(invoke_id, ack.invoke_id)?;
                        return Ok(ack);
                    }
                    _ => continue,
                },
                _ => continue,
            }
        }
    }
    */  

    #[maybe_async()]
    #[cfg_attr(feature = "alloc", bacnet_macros::remove_lifetimes_from_fn_args)]
    async fn send_and_receive_complex_ack<'a>(
        &self,
        buf: &'a mut [u8],
        service: ConfirmedRequestService<'_>,
        addr: Option<NetworkAddress>,
    ) -> Result<Option<ComplexAck<'a>>, BacnetError<T>> {

        let invoke_id = self.send_confirmed(buf, service, addr).await?;

        for _ in 1..3 {

            // receive reply
            let n = self.io.read(buf).await.map_err(BacnetError::Io)?;
            let buf = &buf[..n];

            // use the DataLink codec to decode the bytes
            let mut reader = Reader::default();
            let message = DataLink::decode(&mut reader, buf).map_err(BacnetError::Codec)?;

            match message.npdu {
                Some(x) => match x.network_message {
                    NetworkMessage::Apdu(ApplicationPdu::ComplexAck(ack)) => {
                        // ignore earier messages
                        if ack.invoke_id < invoke_id {
                            continue;
                        }

                        // return message is expected to have the same invoke_id as the request (return error if later invoke id)
                        Self::check_invoke_id(invoke_id, ack.invoke_id)?;
                        return Ok(Some(ack));
                    }
                    _ => continue,
                },
                _ => continue,
            }
        }

        Ok(None)
    }
     

    #[maybe_async()]
    async fn send_and_receive_simple_ack<'a>(
        &self,
        buf: &mut [u8],
        service: ConfirmedRequestService<'_>,
        addr: Option<NetworkAddress>,
    ) -> Result<SimpleAck, BacnetError<T>> {
        let invoke_id = self.send_confirmed(buf, service, addr).await?;

        // receive reply
        let n = self.io.read(buf).await.map_err(BacnetError::Io)?;
        let buf = &buf[..n];

        // use the DataLink codec to decode the bytes
        let mut reader = Reader::default();
        let message = DataLink::decode(&mut reader, buf).map_err(BacnetError::Codec)?;

        // TODO: return bacnet error if the server returns one
        // return message is expected to be a ComplexAck
        let ack: SimpleAck = message.try_into().map_err(BacnetError::Codec)?;

        // return message is expected to have the same invoke_id as the request
        Self::check_invoke_id(invoke_id, ack.invoke_id)?;

        Ok(ack)
    }

    #[maybe_async()]
    async fn send_unconfirmed(
        &self,
        buf: &mut [u8],
        service: UnconfirmedRequest<'_>,
    ) -> Result<(), BacnetError<T>> {
        let apdu = ApplicationPdu::UnconfirmedRequest(service);
        let message = NetworkMessage::Apdu(apdu);
        let npdu = NetworkPdu::new(None, None, true, MessagePriority::Normal, message);
        let data_link = DataLink::new(DataLinkFunction::OriginalUnicastNpdu, Some(npdu));

        let mut writer = Writer::new(buf);
        data_link.encode(&mut writer);

        // send packet
        let buffer = writer.to_bytes();
        self.io.write(buffer).await.map_err(BacnetError::Io)?;
        Ok(())
    }

    #[maybe_async()]
    async fn send_confirmed(
        &self,
        buf: &mut [u8],
        service: ConfirmedRequestService<'_>,
        addr: Option<NetworkAddress>,
    ) -> Result<u8, BacnetError<T>> {

        let mut dst: Option<DestinationAddress> = None;

        if let Some(addr) = addr {
            dst = Some(DestinationAddress::new(addr.net, addr.addr));
        }
        let invoke_id = self.get_then_inc_invoke_id();
        let apdu = ApplicationPdu::ConfirmedRequest(ConfirmedRequest::new(invoke_id, service));
        let message = NetworkMessage::Apdu(apdu);
        let npdu = NetworkPdu::new(None, dst, true, MessagePriority::Normal, message);
        let data_link = DataLink::new(DataLinkFunction::OriginalUnicastNpdu, Some(npdu));

        let mut writer = Writer::new(buf);
        data_link.encode(&mut writer);

        // send packet
        let buffer = writer.to_bytes();
        self.io.write(buffer).await.map_err(BacnetError::Io)?;

        Ok(invoke_id)
    }

    fn check_invoke_id(expected: u8, actual: u8) -> Result<(), BacnetError<T>> {
        if expected != actual {
            Err(BacnetError::InvokeId(InvokeIdError { expected, actual }))
        } else {
            Ok(())
        }
    }

    fn get_then_inc_invoke_id(&self) -> u8 {
        self.invoke_id.fetch_add(1, Ordering::SeqCst)
    }
}