Skip to main content

rustbac_datalink/
address.rs

1use core::fmt;
2
3#[cfg(feature = "std")]
4use std::net::{IpAddr, Ipv4Addr, SocketAddr};
5
6/// A data-link-layer address identifying a BACnet peer.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub enum DataLinkAddress {
10    /// A BACnet/IP endpoint (IPv4 or IPv6 socket address).
11    #[cfg(feature = "std")]
12    Ip(SocketAddr),
13    /// An MS/TP node MAC address (0–127, or 255 for broadcast).
14    Mstp(u8),
15}
16
17impl DataLinkAddress {
18    /// The default BACnet/IP UDP port (`0xBAC0` = 47808).
19    pub const BACNET_IP_DEFAULT_PORT: u16 = 47808;
20
21    /// Returns a broadcast address on the given port.
22    #[cfg(feature = "std")]
23    pub fn local_broadcast(port: u16) -> Self {
24        Self::Ip(SocketAddr::new(IpAddr::V4(Ipv4Addr::BROADCAST), port))
25    }
26
27    #[cfg(feature = "std")]
28    pub fn bacnet_default(addr: IpAddr) -> Self {
29        Self::Ip(SocketAddr::new(addr, Self::BACNET_IP_DEFAULT_PORT))
30    }
31
32    /// Returns the inner [`SocketAddr`] if this is an `Ip` address.
33    ///
34    /// # Panics
35    ///
36    /// Panics if called on an `Mstp` address.
37    #[cfg(feature = "std")]
38    pub fn as_socket_addr(self) -> SocketAddr {
39        match self {
40            Self::Ip(addr) => addr,
41            Self::Mstp(_) => panic!("as_socket_addr called on Mstp address"),
42        }
43    }
44
45    /// Returns a broadcast address for IPv6 multicast on the given group and port.
46    #[cfg(feature = "std")]
47    pub fn ipv6_broadcast(group: std::net::Ipv6Addr, port: u16) -> Self {
48        Self::Ip(SocketAddr::new(IpAddr::V6(group), port))
49    }
50}
51
52impl fmt::Display for DataLinkAddress {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            #[cfg(feature = "std")]
56            Self::Ip(addr) => write!(f, "{addr}"),
57            Self::Mstp(mac) => write!(f, "mstp:{mac}"),
58        }
59    }
60}