Skip to main content

rustbac_datalink/
traits.rs

1#[cfg(feature = "std")]
2use crate::DataLinkAddress;
3
4/// Errors that can occur at the data-link layer.
5#[derive(Debug)]
6#[cfg_attr(feature = "std", derive(thiserror::Error))]
7pub enum DataLinkError {
8    #[cfg(feature = "std")]
9    #[error("io error: {0}")]
10    Io(#[from] std::io::Error),
11    #[cfg_attr(feature = "std", error("frame too large"))]
12    FrameTooLarge,
13    #[cfg_attr(feature = "std", error("invalid frame"))]
14    InvalidFrame,
15    #[cfg_attr(feature = "std", error("unsupported BVLC function 0x{0:02x}"))]
16    UnsupportedBvlcFunction(u8),
17    #[cfg_attr(feature = "std", error("BVLC result code 0x{0:04x}"))]
18    BvlcResult(u16),
19    #[cfg_attr(feature = "std", error("bbmd not configured"))]
20    BbmdNotConfigured,
21}
22
23#[cfg(not(feature = "std"))]
24impl core::fmt::Display for DataLinkError {
25    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
26        match self {
27            DataLinkError::FrameTooLarge => write!(f, "frame too large"),
28            DataLinkError::InvalidFrame => write!(f, "invalid frame"),
29            DataLinkError::UnsupportedBvlcFunction(v) => {
30                write!(f, "unsupported BVLC function 0x{v:02x}")
31            }
32            DataLinkError::BvlcResult(v) => write!(f, "BVLC result code 0x{v:04x}"),
33            DataLinkError::BbmdNotConfigured => write!(f, "bbmd not configured"),
34        }
35    }
36}
37
38/// Async trait for sending and receiving raw BACnet frames.
39///
40/// Implementors include [`BacnetIpTransport`](crate::BacnetIpTransport) for
41/// BACnet/IP over UDP and [`BacnetScTransport`] for BACnet/SC over WebSocket.
42#[cfg(feature = "std")]
43pub trait DataLink: Send + Sync {
44    /// Sends `payload` to the given data-link `address`.
45    async fn send(&self, address: DataLinkAddress, payload: &[u8]) -> Result<(), DataLinkError>;
46
47    /// Receives a frame into `buf`, returning `(bytes_read, source_address)`.
48    async fn recv(&self, buf: &mut [u8]) -> Result<(usize, DataLinkAddress), DataLinkError>;
49}