Skip to main content

zigbee_types/
lib.rs

1#![no_std]
2
3use core::fmt;
4use core::mem::size_of_val;
5use core::ops::Deref;
6use core::ops::DerefMut;
7use core::slice;
8
9use byte::BytesExt;
10use byte::TryRead;
11use byte::TryWrite;
12use byte::ctx;
13use heapless::Vec;
14use heapless::index_set::FnvIndexSet;
15use itertools::Itertools;
16use zigbee_macros::impl_byte;
17
18pub mod storage;
19pub mod sync;
20
21pub type NwkAddress = u16;
22
23/// A fixed-size byte array.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct ByteArray<const N: usize>(pub [u8; N]);
26
27impl<const N: usize> Deref for ByteArray<N> {
28    type Target = [u8; N];
29
30    fn deref(&self) -> &Self::Target {
31        &self.0
32    }
33}
34
35impl<'a, const N: usize, C: Default> TryRead<'a, C> for ByteArray<N> {
36    fn try_read(bytes: &'a [u8], _: C) -> Result<(Self, usize), byte::Error> {
37        let offset = &mut 0;
38        let mut buf = [0u8; N];
39        let data = bytes.read_with(offset, ctx::Bytes::Len(N))?;
40        buf.copy_from_slice(data);
41        Ok((Self(buf), *offset))
42    }
43}
44
45impl<const N: usize, C: Default> TryWrite<C> for ByteArray<N> {
46    fn try_write(self, bytes: &mut [u8], _: C) -> Result<usize, byte::Error> {
47        let offset = &mut 0;
48        bytes.write_with(offset, &self.0[..], ())?;
49        Ok(*offset)
50    }
51}
52
53pub struct ByteArrayRef<'a>(pub &'a [u8]);
54
55impl<'a> Deref for ByteArrayRef<'a> {
56    type Target = &'a [u8];
57
58    fn deref(&self) -> &Self::Target {
59        &self.0
60    }
61}
62
63impl<'a, C: Default> TryRead<'a, C> for ByteArrayRef<'a> {
64    fn try_read(bytes: &'a [u8], _: C) -> Result<(Self, usize), byte::Error> {
65        let offset = &mut 0;
66        let data = bytes.read_with(offset, ctx::Bytes::Len(bytes.len()))?;
67        Ok((Self(data), *offset))
68    }
69}
70
71impl<C: Default> TryWrite<C> for ByteArrayRef<'_> {
72    fn try_write(self, bytes: &mut [u8], _: C) -> Result<usize, byte::Error> {
73        bytes.copy_from_slice(self.0);
74        Ok(self.0.len())
75    }
76}
77
78pub enum TypeArrayCtx {
79    Len(usize),
80}
81
82/// A reference to a typed array.
83///
84/// **SAFETY**: T must be unaligned, i.e. for structs, have `#[repr(packed)]`
85#[derive(Debug, Clone, Copy)]
86pub struct TypeArrayRef<'a, T>(pub &'a [T]);
87
88impl<'a, T> Deref for TypeArrayRef<'a, T> {
89    type Target = &'a [T];
90    fn deref(&self) -> &Self::Target {
91        &self.0
92    }
93}
94
95impl<T, C: Default> TryWrite<C> for TypeArrayRef<'_, T> {
96    fn try_write(self, bytes: &mut [u8], _: C) -> Result<usize, byte::Error> {
97        let offset = &mut 0;
98        let len = size_of_val(self.0);
99        // SAFETY: T needs to be packed
100        let buf = unsafe { slice::from_raw_parts(self.0.as_ptr().cast::<u8>(), len) };
101        bytes.write_with(offset, buf, ())?;
102        Ok(*offset)
103    }
104}
105
106impl<'a, T> TryRead<'a, TypeArrayCtx> for TypeArrayRef<'a, T> {
107    fn try_read(
108        bytes: &'a [u8],
109        TypeArrayCtx::Len(ctx): TypeArrayCtx,
110    ) -> Result<(Self, usize), byte::Error> {
111        let offset = &mut 0;
112        let len = size_of::<T>() * ctx;
113        let data: &[u8] = bytes.read_with(offset, ctx::Bytes::Len(len))?;
114        // SAFETY: T needs to be packed
115        let data: &[T] = unsafe { slice::from_raw_parts(data.as_ptr().cast::<T>(), ctx) };
116        Ok((Self(data), *offset))
117    }
118}
119
120#[derive(Debug)]
121pub struct StorageVec<T, const N: usize>(pub Vec<T, N>);
122
123impl<const N: usize, T: fmt::Debug> StorageVec<T, N> {
124    pub fn find_or_insert_with_mut(&mut self, f: impl Fn(&T) -> bool, i: impl Fn() -> T) -> &mut T {
125        let index = if let Some((i, _)) = self.iter().find_position(|v| f(v)) {
126            i
127        } else {
128            self.push(i()).unwrap();
129            self.len() - 1
130        };
131
132        self.0.get_mut(index).unwrap()
133    }
134}
135
136impl<const N: usize, T> Default for StorageVec<T, N> {
137    fn default() -> Self {
138        Self(Default::default())
139    }
140}
141
142impl<const N: usize, T> StorageVec<T, N> {
143    pub fn new() -> Self {
144        Self(Vec::new())
145    }
146}
147
148impl<const N: usize, T> Deref for StorageVec<T, N> {
149    type Target = Vec<T, N>;
150
151    fn deref(&self) -> &Self::Target {
152        &self.0
153    }
154}
155
156impl<const N: usize, T> DerefMut for StorageVec<T, N> {
157    fn deref_mut(&mut self) -> &mut Self::Target {
158        &mut self.0
159    }
160}
161
162impl<const N: usize, T: Clone> Clone for StorageVec<T, N> {
163    fn clone(&self) -> Self {
164        Self(self.0.clone())
165    }
166}
167
168impl<'a, const N: usize, C, T> TryRead<'a, C> for StorageVec<T, N>
169where
170    C: Default + Copy + Clone,
171    T: TryRead<'a, C>,
172{
173    fn try_read(bytes: &'a [u8], ctx: C) -> Result<(Self, usize), byte::Error> {
174        let offset = &mut 0;
175        // first 2 bytes is the length, should be enough
176        let len: u16 = bytes.read_with(offset, byte::LE)?;
177
178        let mut data: Vec<T, N> = Vec::new();
179        for _i in 0..len {
180            let entry: T = bytes.read_with(offset, ctx)?;
181            let _ = data.push(entry);
182        }
183        Ok((Self(data), *offset))
184    }
185}
186
187impl<const N: usize, C, T> TryWrite<C> for StorageVec<T, N>
188where
189    C: Default + Copy + Clone,
190    T: TryWrite<C>,
191{
192    #[allow(clippy::cast_possible_truncation)]
193    fn try_write(self, bytes: &mut [u8], ctx: C) -> Result<usize, byte::Error> {
194        let offset = &mut 0;
195        // first 2 bytes is the length
196        bytes.write_with(offset, self.0.len() as u16, byte::LE)?;
197        for entry in self.0 {
198            bytes.write_with(offset, entry, ctx)?;
199        }
200        Ok(*offset)
201    }
202}
203
204impl_byte! {
205    /// 16-bit network address
206    #[derive(Clone, Copy, Eq, Hash, PartialEq)]
207    pub struct ShortAddress(pub u16);
208}
209
210impl ShortAddress {
211    /// Network coordinator (Zigbee R22 3.6.1.1: the coordinator is always
212    /// assigned address `0x0000`).
213    pub const COORDINATOR: Self = Self(0x0000);
214    /// Broadcast to all devices in the PAN (3.6.5).
215    pub const BROADCAST_ALL: Self = Self(0xffff);
216    /// Broadcast to all routers and the coordinator (3.6.5).
217    pub const BROADCAST_ROUTERS_AND_COORDINATOR: Self = Self(0xfffc);
218    /// Broadcast to all devices with `RxOnWhenIdle = TRUE` (3.6.5).
219    pub const BROADCAST_RX_ON_WHEN_IDLE: Self = Self(0xfffd);
220    /// Broadcast to all low-power routers (3.6.5).
221    pub const BROADCAST_LOW_POWER_ROUTERS: Self = Self(0xfffb);
222}
223
224impl From<u16> for ShortAddress {
225    fn from(value: u16) -> Self {
226        Self(value)
227    }
228}
229
230impl fmt::Debug for ShortAddress {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        write!(f, "ShortAddress(0x{:04x})", self.0)
233    }
234}
235
236impl Default for ShortAddress {
237    fn default() -> Self {
238        Self(0xffff)
239    }
240}
241
242impl_byte! {
243    /// 64-bit network address
244    #[derive(Clone, Default, Copy, PartialEq, Eq)]
245    pub struct IeeeAddress(pub u64);
246}
247
248impl From<u64> for IeeeAddress {
249    fn from(value: u64) -> Self {
250        Self(value)
251    }
252}
253
254impl fmt::Debug for IeeeAddress {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        write!(f, "IeeeAddress(0x{:016x})", self.0)
257    }
258}
259
260pub struct MacCapabilityFlagsField(u8);
261
262/// 2.3.2.3.6 - MAC Capability Flags Field
263#[repr(u8)]
264#[derive(Clone, Copy, Eq, Hash, PartialEq)]
265pub enum MacCapability {
266    /// The alternate PAN coordinator sub-field is one bit in length and shall
267    /// be set to 1 if this node is capable of becoming a PAN coordinator.
268    /// Otherwise, the alternative PAN coordinator sub-field shall be set to 0.
269    AlternatePanCoordinator = 0,
270    /// The device type sub-field is one bit in length and shall be set to 1 if
271    /// this node is a full function device (FFD). Otherwise, the device
272    /// type sub-field shall be set to 0, indicating a reduced function device
273    /// (RFD).
274    DeviceType = 1,
275    /// The power source sub-field is one bit in length and shall be set to 1 if
276    /// the current power source is mains power. Otherwise, the power source
277    /// sub-field shall be set to 0. This information is derived from the
278    /// node current power source field of the node power descriptor.
279    PowerSource = 2,
280    /// The receiver on when idle sub-field is one bit in length and shall be
281    /// set to 1 if the device does not disable its receiver to conserve power
282    /// during idle periods. Otherwise, the receiver on when idle sub-field
283    /// shall be set to 0.
284    ReceiverOnWhenIdle = 3,
285    /// The security capability sub-field is one bit in length and shall be set
286    /// to 1 if the device is capable of sending and receiving frames
287    /// secured using the security suite specified in [B1]. Otherwise, the
288    /// security capability sub-field shall be set to 0.
289    SecurityCapability = 6,
290    /// The allocate address sub-field is one bit in length and shall be set to
291    /// 0 or 1
292    AllocateAddress = 7,
293}
294
295impl MacCapabilityFlagsField {
296    // capacity of IndexSet must be a power of 2
297    pub fn new(capabilities: &FnvIndexSet<MacCapability, 8>) -> Self {
298        let mut value: u8 = 0;
299        for capa in capabilities.iter() {
300            value |= 1 << *capa as u8;
301        }
302
303        Self(value)
304    }
305
306    pub fn is_set(&self, capability: MacCapability) -> bool {
307        (self.0 & (1 << capability as u8)) != 0
308    }
309}
310
311/// 2.3.2.3.10 - Server Mask Field
312pub struct ServerMaskField(pub u16);
313
314#[repr(u8)]
315#[derive(Clone, Copy, Eq, Hash, PartialEq)]
316pub enum ServerMaskBit {
317    PrimaryTrustCenter = 0,
318    BackupTrustCenter = 1,
319    PrimaryBindingTableCache = 2,
320    BackupBindingTableCache = 3,
321    PrimaryDiscoveryCache = 4,
322    BackupDiscoveryCache = 5,
323    NetworkManager = 6,
324}
325
326impl ServerMaskField {
327    pub fn new(
328        server_mask_bits: &FnvIndexSet<ServerMaskBit, 16>,
329        stack_compliance_revision: u8,
330    ) -> Self {
331        let mut value: u16 = 0;
332        for bit in server_mask_bits.iter() {
333            value |= 1 << *bit as u16;
334        }
335
336        value |= (stack_compliance_revision as u16) << 9;
337
338        Self(value)
339    }
340
341    pub fn is_set(&self, server_mask_bit: ServerMaskBit) -> bool {
342        self.0 & (1 << server_mask_bit as u16) != 0
343    }
344
345    pub fn get_stack_compliance_revision(&self) -> u8 {
346        (self.0 >> 9) as u8
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use byte::TryRead;
353    use byte::TryWrite;
354
355    use super::*;
356
357    #[test]
358    fn creating_mac_capabilites_should_succeed() {
359        let expected: u8 = 0b1000_0001;
360
361        let mut capas = FnvIndexSet::<MacCapability, 8>::new();
362        let _ = capas.insert(MacCapability::AlternatePanCoordinator);
363        let _ = capas.insert(MacCapability::AllocateAddress);
364        let flagsfield = MacCapabilityFlagsField::new(&capas);
365
366        assert_eq!(expected, flagsfield.0);
367    }
368
369    #[test]
370    fn reading_mac_capabilites_should_succeed() {
371        let mut capas = FnvIndexSet::<MacCapability, 8>::new();
372        let _ = capas.insert(MacCapability::AlternatePanCoordinator);
373        let _ = capas.insert(MacCapability::AllocateAddress);
374
375        let flagsfield = MacCapabilityFlagsField::new(&capas);
376
377        assert!(flagsfield.is_set(MacCapability::AlternatePanCoordinator));
378        assert!(flagsfield.is_set(MacCapability::AllocateAddress));
379        assert!(!flagsfield.is_set(MacCapability::DeviceType));
380    }
381
382    #[test]
383    fn creating_server_mask_field_should_succeed() {
384        let expected = 0b0010_1100_0100_0001;
385
386        let mut bits = FnvIndexSet::<ServerMaskBit, 16>::new();
387        let _ = bits.insert(ServerMaskBit::PrimaryTrustCenter);
388        let _ = bits.insert(ServerMaskBit::NetworkManager);
389        let server_mask_field = ServerMaskField::new(&bits, 22);
390
391        assert_eq!(expected, server_mask_field.0);
392    }
393
394    #[test]
395    fn reading_server_mask_field_should_succeed() {
396        let mut bits = FnvIndexSet::<ServerMaskBit, 16>::new();
397        let _ = bits.insert(ServerMaskBit::PrimaryTrustCenter);
398        let _ = bits.insert(ServerMaskBit::NetworkManager);
399
400        let server_mask_field = ServerMaskField::new(&bits, 22);
401
402        assert!(server_mask_field.is_set(ServerMaskBit::PrimaryTrustCenter));
403        assert!(server_mask_field.is_set(ServerMaskBit::NetworkManager));
404        assert!(!server_mask_field.is_set(ServerMaskBit::PrimaryDiscoveryCache));
405        assert_eq!(22, server_mask_field.get_stack_compliance_revision());
406    }
407
408    #[test]
409    fn bytearray_try_read_should_succeed() {
410        let input_data = [0x01, 0x02, 0x03, 0x04, 0x05];
411
412        let (result, bytes_read) = ByteArray::<5>::try_read(&input_data, ()).unwrap();
413
414        assert_eq!(result, ByteArray(input_data));
415        assert_eq!(bytes_read, 5);
416    }
417
418    #[test]
419    fn bytearray_try_write_should_succeed() {
420        let byte_array = ByteArray([0xaa, 0xbb, 0xcc, 0xdd]);
421        let mut output_buffer = [0u8; 4];
422
423        let bytes_written = byte_array.try_write(&mut output_buffer, ()).unwrap();
424
425        assert_eq!(bytes_written, 4);
426        assert_eq!(output_buffer, byte_array.0);
427    }
428
429    #[test]
430    fn bytearrayref_try_read_should_succeed() {
431        let input_data = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
432
433        let (result, bytes_read) = ByteArrayRef::try_read(&input_data, ()).unwrap();
434
435        assert_eq!(bytes_read, 6);
436        assert_eq!(result.0, input_data);
437    }
438
439    #[test]
440    fn bytearrayref_try_write_should_succeed() {
441        let input_data = [0x77, 0x88, 0x99];
442        let byte_array_ref = ByteArrayRef(&input_data);
443        let mut output_buffer = [0u8; 3];
444
445        let bytes_written = byte_array_ref.try_write(&mut output_buffer, ()).unwrap();
446
447        assert_eq!(bytes_written, 3);
448        assert_eq!(&output_buffer[..], input_data);
449    }
450
451    #[repr(C, packed)]
452    #[derive(Debug, Clone, Copy, PartialEq)]
453    struct TestPackedStruct {
454        field1: u8,
455        field2: u16,
456        field3: u8,
457    }
458
459    #[test]
460    fn typearrayref_try_read_should_succeed() {
461        // field1(1) + field2(2) + field3(1) = 4 bytes per struct
462        let input_data = [
463            0x12, 0x34, 0x56, 0x78, // field1=0x12, field2=0x5634, field3=0x78
464            0xaa, 0xbb, 0xcc, 0xdd, // field1=0xaa, field2=0xccbb, field3=0xdd
465        ];
466        let expected_structs = [
467            TestPackedStruct {
468                field1: 0x12,
469                field2: 0x5634,
470                field3: 0x78,
471            },
472            TestPackedStruct {
473                field1: 0xaa,
474                field2: 0xccbb,
475                field3: 0xdd,
476            },
477        ];
478
479        let (result, bytes_read) =
480            TypeArrayRef::<TestPackedStruct>::try_read(&input_data, TypeArrayCtx::Len(2)).unwrap();
481
482        assert_eq!(bytes_read, 8);
483        assert_eq!(result.0, &expected_structs);
484    }
485
486    #[test]
487    fn typearrayref_try_write_should_succeed() {
488        let test_structs = [
489            TestPackedStruct {
490                field1: 0xab,
491                field2: 0xcdef,
492                field3: 0x12,
493            },
494            TestPackedStruct {
495                field1: 0x34,
496                field2: 0x5678,
497                field3: 0x9a,
498            },
499        ];
500        let type_array_ref = TypeArrayRef(&test_structs);
501        let mut output_buffer = [0u8; 8];
502
503        let bytes_written = type_array_ref.try_write(&mut output_buffer, ()).unwrap();
504
505        assert_eq!(bytes_written, 8);
506        assert_eq!(
507            output_buffer,
508            [0xab, 0xef, 0xcd, 0x12, 0x34, 0x78, 0x56, 0x9a]
509        );
510    }
511}