Skip to main content

zigbee_primitives/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(
3    not(test),
4    deny(
5        clippy::indexing_slicing,
6        clippy::unwrap_used,
7        clippy::expect_used,
8        clippy::panic
9    )
10)]
11
12use std::fmt;
13use std::str::FromStr;
14
15pub mod wire;
16
17/// A 16-bit network (short) address.
18pub type NodeId = u16;
19/// A 16-bit PAN id.
20pub type PanId = u16;
21
22/// The coordinator's network address.
23pub const COORDINATOR_NODE_ID: NodeId = 0x0000;
24/// Broadcast to every device.
25pub const BROADCAST_ALL: NodeId = 0xFFFF;
26/// Broadcast to every device whose receiver is on when idle.
27pub const BROADCAST_RX_ON_WHEN_IDLE: NodeId = 0xFFFD;
28/// Broadcast to every router and the coordinator.
29pub const BROADCAST_ROUTERS: NodeId = 0xFFFC;
30
31/// Error from parsing a hex address or key.
32#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
33pub enum ParseHexError {
34    /// The text was not the expected number of hex digits.
35    #[error("expected {expected} hex digits, got {got}")]
36    Length {
37        /// Digits expected.
38        expected: usize,
39        /// Digits found.
40        got: usize,
41    },
42    /// A character was not a hex digit.
43    #[error("invalid hex digit {0:?}")]
44    Digit(char),
45}
46
47fn parse_hex_bytes<const N: usize>(text: &str) -> Result<[u8; N], ParseHexError> {
48    let text = text.trim();
49    let text = text
50        .strip_prefix("0x")
51        .or_else(|| text.strip_prefix("0X"))
52        .unwrap_or(text);
53    let digits: Vec<char> = text.chars().filter(|c| *c != ':' && *c != '-').collect();
54    if digits.len() != N * 2 {
55        return Err(ParseHexError::Length {
56            expected: N * 2,
57            got: digits.len(),
58        });
59    }
60    let mut out = [0u8; N];
61    for (byte, pair) in out.iter_mut().zip(digits.chunks(2)) {
62        let mut value = 0u8;
63        for c in pair {
64            let nibble = c.to_digit(16).ok_or(ParseHexError::Digit(*c))?;
65            value = (value << 4) | nibble as u8;
66        }
67        *byte = value;
68    }
69    Ok(out)
70}
71
72/// A 64-bit IEEE (EUI-64) address.
73///
74/// Shown and parsed most-significant byte first, as printed on labels and in
75/// the open coordinator backup format: `00124b0001020304`. Parsing also
76/// accepts a `0x` prefix and `:` separators. On the wire it is little-endian.
77#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
78pub struct Ieee(pub u64);
79
80impl Ieee {
81    /// All zeros, used by some stacks to mean "any device".
82    pub const ZERO: Ieee = Ieee(0);
83    /// All ones, the unset value.
84    pub const UNSET: Ieee = Ieee(u64::MAX);
85
86    /// From the 8 wire (little-endian) bytes.
87    pub fn from_le_bytes(bytes: [u8; 8]) -> Self {
88        Ieee(u64::from_le_bytes(bytes))
89    }
90
91    /// The 8 wire (little-endian) bytes.
92    pub fn to_le_bytes(self) -> [u8; 8] {
93        self.0.to_le_bytes()
94    }
95
96    /// The address as `0x` followed by 16 hex digits, the conventional
97    /// friendly name for a device that has none.
98    pub fn to_prefixed_hex(self) -> String {
99        format!("0x{:016x}", self.0)
100    }
101}
102
103impl fmt::Display for Ieee {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        write!(f, "{:016x}", self.0)
106    }
107}
108
109impl fmt::Debug for Ieee {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        write!(f, "Ieee({:016x})", self.0)
112    }
113}
114
115impl FromStr for Ieee {
116    type Err = ParseHexError;
117    fn from_str(s: &str) -> Result<Self, Self::Err> {
118        parse_hex_bytes::<8>(s).map(|b| Ieee(u64::from_be_bytes(b)))
119    }
120}
121
122/// A 64-bit extended PAN id, shown most-significant byte first like [`Ieee`].
123#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
124pub struct ExtPanId(pub u64);
125
126impl ExtPanId {
127    /// From the 8 wire (little-endian) bytes.
128    pub fn from_le_bytes(bytes: [u8; 8]) -> Self {
129        ExtPanId(u64::from_le_bytes(bytes))
130    }
131
132    /// The 8 wire (little-endian) bytes.
133    pub fn to_le_bytes(self) -> [u8; 8] {
134        self.0.to_le_bytes()
135    }
136}
137
138impl fmt::Display for ExtPanId {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        write!(f, "{:016x}", self.0)
141    }
142}
143
144impl fmt::Debug for ExtPanId {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        write!(f, "ExtPanId({:016x})", self.0)
147    }
148}
149
150impl FromStr for ExtPanId {
151    type Err = ParseHexError;
152    fn from_str(s: &str) -> Result<Self, Self::Err> {
153        parse_hex_bytes::<8>(s).map(|b| ExtPanId(u64::from_be_bytes(b)))
154    }
155}
156
157/// A 128-bit AES key (network key, link key, install-code-derived key).
158///
159/// Its `Debug` output never contains the key, so a key that ends up in a
160/// log line by mistake is not leaked. Use [`Key::to_hex`] deliberately.
161#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
162pub struct Key(pub [u8; 16]);
163
164impl Key {
165    /// The well-known Zigbee 3.0 / HA "ZigBeeAlliance09" trust center link key.
166    pub const ZIGBEE_ALLIANCE_09: Key = Key(*b"ZigBeeAlliance09");
167
168    /// The key as 32 lowercase hex digits, in byte order.
169    pub fn to_hex(&self) -> String {
170        self.0.iter().map(|b| format!("{b:02x}")).collect()
171    }
172
173    /// True when every byte is zero (an unset key).
174    pub fn is_zero(&self) -> bool {
175        self.0.iter().all(|b| *b == 0)
176    }
177}
178
179impl fmt::Debug for Key {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        f.write_str("Key(<redacted>)")
182    }
183}
184
185impl FromStr for Key {
186    type Err = ParseHexError;
187    fn from_str(s: &str) -> Result<Self, Self::Err> {
188        parse_hex_bytes::<16>(s).map(Key)
189    }
190}
191
192#[cfg(feature = "serde")]
193mod serde_impls {
194    use super::*;
195    use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
196
197    macro_rules! hex_serde {
198        ($t:ty, $ser:expr) => {
199            impl Serialize for $t {
200                fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
201                    let f: fn(&$t) -> String = $ser;
202                    s.serialize_str(&f(self))
203                }
204            }
205            impl<'de> Deserialize<'de> for $t {
206                fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
207                    let text = String::deserialize(d)?;
208                    text.parse().map_err(D::Error::custom)
209                }
210            }
211        };
212    }
213
214    hex_serde!(Ieee, |v| v.to_string());
215    hex_serde!(ExtPanId, |v| v.to_string());
216    hex_serde!(Key, |v| v.to_hex());
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn ieee_round_trips_in_every_spelling() {
225        let a: Ieee = "00124b0001020304".parse().unwrap();
226        assert_eq!(a, Ieee(0x00124b0001020304));
227        assert_eq!("0x00124B0001020304".parse::<Ieee>().unwrap(), a);
228        assert_eq!("00:12:4b:00:01:02:03:04".parse::<Ieee>().unwrap(), a);
229        assert_eq!(a.to_string(), "00124b0001020304");
230        assert_eq!(a.to_prefixed_hex(), "0x00124b0001020304");
231        assert_eq!(a.to_le_bytes(), [4, 3, 2, 1, 0, 0x4b, 0x12, 0]);
232        assert!("00124b00010203".parse::<Ieee>().is_err());
233        assert!("00124b000102030g".parse::<Ieee>().is_err());
234    }
235
236    #[test]
237    fn key_debug_is_redacted() {
238        let k = Key::ZIGBEE_ALLIANCE_09;
239        assert_eq!(format!("{k:?}"), "Key(<redacted>)");
240        assert_eq!(k.to_hex(), "5a6967426565416c6c69616e63653039");
241        assert_eq!(k.to_hex().parse::<Key>().unwrap(), k);
242    }
243}