Skip to main content

zigbee_zcl/
value.rs

1//! ZCL attribute and field values.
2//!
3//! Attribute values are self-describing on the wire (a type id precedes
4//! them in reports and read responses), so one [`Value`] type and one
5//! decoder cover every cluster.
6
7use zigbee_primitives::wire::{Reader, Truncated, Writer};
8use zigbee_primitives::{Ieee, Key};
9
10use crate::types::{Class, DataType};
11
12/// Nested arrays and structures deeper than this are rejected.
13pub const MAX_DEPTH: usize = 4;
14
15/// A value did not decode.
16#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
17pub enum ValueError {
18    /// Too short.
19    #[error(transparent)]
20    Truncated(#[from] Truncated),
21    /// A type id that ZCL does not define.
22    #[error("unknown data type {0:#04x}")]
23    UnknownType(u8),
24    /// Arrays or structures nested deeper than [`MAX_DEPTH`].
25    #[error("values nested too deeply")]
26    TooDeep,
27    /// An array of a zero-size type claimed elements.
28    #[error("array of {0:?} with elements")]
29    ZeroSizeElements(DataType),
30}
31
32/// A decoded ZCL value.
33#[derive(Debug, Clone, PartialEq)]
34pub enum Value {
35    /// No data.
36    NoData,
37    /// A boolean, as sent: 0 false, 1 true, 0xFF invalid.
38    Bool(u8),
39    /// Raw data (`dataN`) or a bitmap (`mapN`).
40    Bits(DataType, u64),
41    /// An unsigned integer, or a time, date or id type.
42    Uint(DataType, u64),
43    /// A signed integer.
44    Int(DataType, i64),
45    /// An enumeration.
46    Enum(DataType, u16),
47    /// A floating-point value (half, single or double precision).
48    Float(DataType, f64),
49    /// An octet string; `None` is the invalid (0xFF / 0xFFFF length) value.
50    Octets(DataType, Option<Vec<u8>>),
51    /// A character string; `None` is the invalid value. Bytes that are not
52    /// UTF-8 are replaced.
53    Chars(DataType, Option<String>),
54    /// An array, set or bag: container type, element type, elements.
55    List(DataType, DataType, Option<Vec<Value>>),
56    /// A structure.
57    Struct(Option<Vec<Value>>),
58    /// An IEEE address.
59    Ieee(Ieee),
60    /// A 128-bit key.
61    Key(Key),
62}
63
64fn width(t: DataType) -> usize {
65    t.fixed_size().unwrap_or(0)
66}
67
68fn sign_extend(raw: u64, bits: usize) -> i64 {
69    if bits == 0 || bits >= 64 {
70        return raw as i64;
71    }
72    let shift = 64 - bits;
73    ((raw << shift) as i64) >> shift
74}
75
76impl Value {
77    /// An unsigned 8-bit integer.
78    pub fn u8(v: u8) -> Value {
79        Value::Uint(DataType::Uint8, u64::from(v))
80    }
81    /// An unsigned 16-bit integer.
82    pub fn u16(v: u16) -> Value {
83        Value::Uint(DataType::Uint16, u64::from(v))
84    }
85    /// An unsigned 32-bit integer.
86    pub fn u32(v: u32) -> Value {
87        Value::Uint(DataType::Uint32, u64::from(v))
88    }
89    /// A signed 16-bit integer.
90    pub fn i16(v: i16) -> Value {
91        Value::Int(DataType::Int16, i64::from(v))
92    }
93    /// A boolean.
94    pub fn bool(v: bool) -> Value {
95        Value::Bool(u8::from(v))
96    }
97    /// An 8-bit enumeration.
98    pub fn enum8(v: u8) -> Value {
99        Value::Enum(DataType::Enum8, u16::from(v))
100    }
101    /// A 16-bit enumeration.
102    pub fn enum16(v: u16) -> Value {
103        Value::Enum(DataType::Enum16, v)
104    }
105    /// An 8-bit bitmap.
106    pub fn map8(v: u8) -> Value {
107        Value::Bits(DataType::Map8, u64::from(v))
108    }
109    /// A 16-bit bitmap.
110    pub fn map16(v: u16) -> Value {
111        Value::Bits(DataType::Map16, u64::from(v))
112    }
113    /// A character string.
114    pub fn string(v: &str) -> Value {
115        Value::Chars(DataType::CharString, Some(v.to_string()))
116    }
117
118    /// The value's data type.
119    pub fn data_type(&self) -> DataType {
120        match self {
121            Value::NoData => DataType::NoData,
122            Value::Bool(_) => DataType::Bool,
123            Value::Bits(t, _)
124            | Value::Uint(t, _)
125            | Value::Int(t, _)
126            | Value::Enum(t, _)
127            | Value::Float(t, _)
128            | Value::Octets(t, _)
129            | Value::Chars(t, _)
130            | Value::List(t, _, _) => *t,
131            Value::Struct(_) => DataType::Struct,
132            Value::Ieee(_) => DataType::Ieee,
133            Value::Key(_) => DataType::SecurityKey,
134        }
135    }
136
137    /// Decode a value of type `t` (the type id has already been read).
138    pub fn decode(t: DataType, r: &mut Reader<'_>) -> Result<Value, ValueError> {
139        Self::decode_at(t, r, 0)
140    }
141
142    /// Decode a type id followed by a value.
143    pub fn decode_typed(r: &mut Reader<'_>) -> Result<Value, ValueError> {
144        let id = r.u8()?;
145        let t = DataType::from_u8(id).ok_or(ValueError::UnknownType(id))?;
146        Self::decode(t, r)
147    }
148
149    fn decode_at(t: DataType, r: &mut Reader<'_>, depth: usize) -> Result<Value, ValueError> {
150        if depth > MAX_DEPTH {
151            return Err(ValueError::TooDeep);
152        }
153        Ok(match t.class() {
154            Class::NoData | Class::Unknown => Value::NoData,
155            Class::Bool => Value::Bool(r.u8()?),
156            Class::Data | Class::Bitmap => Value::Bits(t, r.uint_n(width(t))?),
157            Class::Unsigned => Value::Uint(t, r.uint_n(width(t))?),
158            Class::Signed => Value::Int(t, sign_extend(r.uint_n(width(t))?, width(t) * 8)),
159            Class::Enum => Value::Enum(t, r.uint_n(width(t))? as u16),
160            Class::Float => Value::Float(
161                t,
162                match t {
163                    DataType::Semi => f64::from(half::f16::from_bits(r.u16()?).to_f32()),
164                    DataType::Single => f64::from(f32::from_bits(r.u32()?)),
165                    _ => f64::from_bits(r.u64()?),
166                },
167            ),
168            Class::Octets | Class::Chars => {
169                let long = matches!(t, DataType::LongOctetString | DataType::LongCharString);
170                let len = if long {
171                    usize::from(r.u16()?)
172                } else {
173                    usize::from(r.u8()?)
174                };
175                let invalid = if long { len == 0xFFFF } else { len == 0xFF };
176                let bytes = if invalid {
177                    None
178                } else {
179                    Some(r.bytes(len)?.to_vec())
180                };
181                if t.class() == Class::Octets {
182                    Value::Octets(t, bytes)
183                } else {
184                    Value::Chars(t, bytes.map(|b| String::from_utf8_lossy(&b).into_owned()))
185                }
186            }
187            Class::List => {
188                let id = r.u8()?;
189                let element = DataType::from_u8(id).ok_or(ValueError::UnknownType(id))?;
190                let count = r.u16()?;
191                if count == 0xFFFF {
192                    Value::List(t, element, None)
193                } else {
194                    let count = usize::from(count);
195                    if count > 0 && element.fixed_size() == Some(0) {
196                        return Err(ValueError::ZeroSizeElements(element));
197                    }
198                    // Every element takes at least one byte, so the input
199                    // bounds the allocation.
200                    let mut items = Vec::with_capacity(count.min(r.remaining()));
201                    for _ in 0..count {
202                        items.push(Self::decode_at(element, r, depth + 1)?);
203                    }
204                    Value::List(t, element, Some(items))
205                }
206            }
207            Class::Struct => {
208                let count = r.u16()?;
209                if count == 0xFFFF {
210                    Value::Struct(None)
211                } else {
212                    let count = usize::from(count);
213                    let mut items = Vec::with_capacity(count.min(r.remaining()));
214                    for _ in 0..count {
215                        let id = r.u8()?;
216                        let element = DataType::from_u8(id).ok_or(ValueError::UnknownType(id))?;
217                        items.push(Self::decode_at(element, r, depth + 1)?);
218                    }
219                    Value::Struct(Some(items))
220                }
221            }
222            Class::Ieee => Value::Ieee(r.ieee()?),
223            Class::Key => Value::Key(r.key()?),
224        })
225    }
226
227    /// Encode the value without its type id.
228    pub fn encode(&self, w: &mut Vec<u8>) {
229        match self {
230            Value::NoData => {}
231            Value::Bool(v) => w.put_u8(*v),
232            Value::Bits(t, v) | Value::Uint(t, v) => w.put_uint_n(*v, width(*t)),
233            Value::Int(t, v) => w.put_uint_n(*v as u64, width(*t)),
234            Value::Enum(t, v) => w.put_uint_n(u64::from(*v), width(*t)),
235            Value::Float(t, v) => match t {
236                DataType::Semi => w.put_u16(half::f16::from_f64(*v).to_bits()),
237                DataType::Single => w.put_u32((*v as f32).to_bits()),
238                _ => w.put_u64(v.to_bits()),
239            },
240            Value::Octets(t, v) => put_string(w, *t, v.as_deref()),
241            Value::Chars(t, v) => put_string(w, *t, v.as_deref().map(str::as_bytes)),
242            Value::List(_, element, items) => {
243                w.put_u8(element.id());
244                match items {
245                    None => w.put_u16(0xFFFF),
246                    Some(items) => {
247                        w.put_u16(items.len().min(0xFFFE) as u16);
248                        items.iter().take(0xFFFE).for_each(|i| i.encode(w));
249                    }
250                }
251            }
252            Value::Struct(items) => match items {
253                None => w.put_u16(0xFFFF),
254                Some(items) => {
255                    w.put_u16(items.len().min(0xFFFE) as u16);
256                    for i in items.iter().take(0xFFFE) {
257                        w.put_u8(i.data_type().id());
258                        i.encode(w);
259                    }
260                }
261            },
262            Value::Ieee(v) => w.put_ieee(*v),
263            Value::Key(v) => w.put_key(v),
264        }
265    }
266
267    /// Encode the type id and the value.
268    pub fn encode_typed(&self, w: &mut Vec<u8>) {
269        w.put_u8(self.data_type().id());
270        self.encode(w);
271    }
272
273    /// True for the type's "invalid" (non-value) encoding: a sensor that
274    /// has no reading reports this.
275    pub fn is_invalid(&self) -> bool {
276        match self {
277            Value::Bool(v) => *v == 0xFF,
278            Value::Uint(t, v) => {
279                let bits = width(*t) * 8;
280                bits > 0 && *v == (u64::MAX >> (64 - bits))
281            }
282            Value::Int(t, v) => {
283                let bits = width(*t) * 8;
284                bits > 0 && *v == sign_extend(1u64 << (bits - 1), bits)
285            }
286            Value::Enum(t, v) => *v == if *t == DataType::Enum8 { 0xFF } else { 0xFFFF },
287            Value::Float(_, v) => v.is_nan(),
288            Value::Octets(_, v) => v.is_none(),
289            Value::Chars(_, v) => v.is_none(),
290            Value::List(_, _, v) => v.is_none(),
291            Value::Struct(v) => v.is_none(),
292            Value::Ieee(v) => *v == Ieee::UNSET,
293            Value::NoData | Value::Bits(..) | Value::Key(_) => false,
294        }
295    }
296
297    /// The value as a number, unless it is invalid or not numeric.
298    pub fn as_f64(&self) -> Option<f64> {
299        if self.is_invalid() {
300            return None;
301        }
302        match self {
303            Value::Bool(v) => Some(f64::from(*v)),
304            Value::Bits(_, v) | Value::Uint(_, v) => Some(*v as f64),
305            Value::Int(_, v) => Some(*v as f64),
306            Value::Enum(_, v) => Some(f64::from(*v)),
307            Value::Float(_, v) => Some(*v),
308            _ => None,
309        }
310    }
311
312    /// The value as an unsigned integer, unless invalid or not integral.
313    pub fn as_u64(&self) -> Option<u64> {
314        if self.is_invalid() {
315            return None;
316        }
317        match self {
318            Value::Bool(v) => Some(u64::from(*v)),
319            Value::Bits(_, v) | Value::Uint(_, v) => Some(*v),
320            Value::Enum(_, v) => Some(u64::from(*v)),
321            Value::Int(_, v) => u64::try_from(*v).ok(),
322            _ => None,
323        }
324    }
325
326    /// The value as a boolean.
327    pub fn as_bool(&self) -> Option<bool> {
328        match self {
329            Value::Bool(0) => Some(false),
330            Value::Bool(1) => Some(true),
331            _ => None,
332        }
333    }
334
335    /// The value as text, for character strings.
336    pub fn as_str(&self) -> Option<&str> {
337        match self {
338            Value::Chars(_, Some(s)) => Some(s),
339            _ => None,
340        }
341    }
342}
343
344fn put_string(w: &mut Vec<u8>, t: DataType, v: Option<&[u8]>) {
345    let long = matches!(t, DataType::LongOctetString | DataType::LongCharString);
346    match (v, long) {
347        (None, false) => w.put_u8(0xFF),
348        (None, true) => w.put_u16(0xFFFF),
349        (Some(b), false) => w.put_u8_prefixed(b),
350        (Some(b), true) => {
351            let b = b.get(..b.len().min(0xFFFE)).unwrap_or(b);
352            w.put_u16(b.len() as u16);
353            w.put_bytes(b);
354        }
355    }
356}
357
358#[cfg(feature = "serde")]
359impl serde::Serialize for Value {
360    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
361        use serde::ser::SerializeSeq;
362        if self.is_invalid() {
363            return s.serialize_none();
364        }
365        match self {
366            Value::NoData => s.serialize_none(),
367            Value::Bool(v) => s.serialize_bool(*v != 0),
368            Value::Bits(_, v) | Value::Uint(_, v) => s.serialize_u64(*v),
369            Value::Int(_, v) => s.serialize_i64(*v),
370            Value::Enum(_, v) => s.serialize_u16(*v),
371            Value::Float(_, v) => s.serialize_f64(*v),
372            Value::Octets(_, Some(v)) => {
373                s.serialize_str(&v.iter().map(|b| format!("{b:02x}")).collect::<String>())
374            }
375            Value::Chars(_, Some(v)) => s.serialize_str(v),
376            Value::List(_, _, Some(items)) | Value::Struct(Some(items)) => {
377                let mut seq = s.serialize_seq(Some(items.len()))?;
378                for i in items {
379                    seq.serialize_element(i)?;
380                }
381                seq.end()
382            }
383            Value::Ieee(v) => s.serialize_str(&v.to_prefixed_hex()),
384            Value::Key(v) => s.serialize_str(&v.to_hex()),
385            _ => s.serialize_none(),
386        }
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    fn round_trip(v: Value) {
395        let mut w = Vec::new();
396        v.encode_typed(&mut w);
397        let mut r = Reader::new(&w);
398        assert_eq!(Value::decode_typed(&mut r).unwrap(), v);
399        assert!(r.is_empty());
400    }
401
402    #[test]
403    fn every_class_round_trips() {
404        round_trip(Value::NoData);
405        round_trip(Value::bool(true));
406        round_trip(Value::Bits(DataType::Map24, 0xABCDEF));
407        round_trip(Value::Uint(DataType::Uint48, 0x0102_0304_0506));
408        round_trip(Value::Int(DataType::Int24, -2));
409        round_trip(Value::i16(-12345));
410        round_trip(Value::enum16(0x0015));
411        round_trip(Value::Float(DataType::Semi, 1.5));
412        round_trip(Value::Float(DataType::Single, -0.25));
413        round_trip(Value::Float(DataType::Double, 1e300));
414        round_trip(Value::Octets(DataType::OctetString, Some(vec![1, 2, 3])));
415        round_trip(Value::Octets(DataType::LongOctetString, None));
416        round_trip(Value::string("lumi.weather"));
417        round_trip(Value::Chars(DataType::CharString, None));
418        round_trip(Value::List(
419            DataType::Array,
420            DataType::Uint16,
421            Some(vec![Value::u16(1), Value::u16(2)]),
422        ));
423        round_trip(Value::Struct(Some(vec![Value::u8(1), Value::string("x")])));
424        round_trip(Value::Ieee(Ieee(0x00124B0012345678)));
425        round_trip(Value::Key(Key([9; 16])));
426    }
427
428    #[test]
429    fn signed_values_sign_extend() {
430        let mut r = Reader::new(&[0xFE, 0xFF, 0xFF]);
431        assert_eq!(
432            Value::decode(DataType::Int24, &mut r).unwrap(),
433            Value::Int(DataType::Int24, -2)
434        );
435    }
436
437    #[test]
438    fn invalid_values_are_recognized() {
439        assert!(Value::Int(DataType::Int16, -32768).is_invalid());
440        assert!(!Value::Int(DataType::Int16, -32767).is_invalid());
441        assert!(Value::u16(0xFFFF).is_invalid());
442        assert!(Value::Bool(0xFF).is_invalid());
443        assert_eq!(Value::u16(0xFFFF).as_f64(), None);
444        assert_eq!(Value::i16(2150).as_f64(), Some(2150.0));
445    }
446
447    #[test]
448    fn hostile_lists_do_not_allocate_or_recurse_forever() {
449        // An array of 65534 no-data elements.
450        assert_eq!(
451            Value::decode_typed(&mut Reader::new(&[0x48, 0x00, 0xFE, 0xFF])),
452            Err(ValueError::ZeroSizeElements(DataType::NoData))
453        );
454        // A claimed 65534 uint8 elements with three bytes present.
455        assert!(Value::decode_typed(&mut Reader::new(&[0x48, 0x20, 0xFE, 0xFF, 1, 2, 3])).is_err());
456        // Arrays nested beyond the limit.
457        let mut deep = Vec::new();
458        for _ in 0..10 {
459            deep.extend_from_slice(&[0x48, 0x48, 0x01, 0x00]);
460        }
461        assert!(Value::decode_typed(&mut Reader::new(&deep)).is_err());
462    }
463
464    #[cfg(feature = "serde")]
465    #[test]
466    fn serializes_to_plain_json() {
467        assert_eq!(serde_json::to_string(&Value::i16(2150)).unwrap(), "2150");
468        assert_eq!(serde_json::to_string(&Value::u16(0xFFFF)).unwrap(), "null");
469        assert_eq!(serde_json::to_string(&Value::string("a")).unwrap(), "\"a\"");
470        assert_eq!(serde_json::to_string(&Value::bool(false)).unwrap(), "false");
471    }
472}