Skip to main content

zigbee_zcl/
defs.rs

1//! Cluster definitions and the table-driven codec for cluster commands.
2//!
3//! The tables ([`CLUSTERS`]) and constant modules ([`cluster_id`],
4//! [`attr`], [`command`], [`response`]) are generated at build time from
5//! `data/clusters.toml`.
6
7use zigbee_primitives::wire::{Reader, Writer};
8
9use crate::frame::Direction;
10use crate::types::DataType;
11use crate::value::{Value, ValueError};
12
13/// A cluster.
14#[derive(Debug)]
15pub struct ClusterDef {
16    /// Cluster id.
17    pub id: u16,
18    /// snake_case name.
19    pub name: &'static str,
20    /// Attributes, sorted by id.
21    pub attributes: &'static [AttributeDef],
22    /// Commands the server receives, sorted by id.
23    pub commands: &'static [CommandDef],
24    /// Commands the server generates, sorted by id.
25    pub responses: &'static [CommandDef],
26}
27
28/// An attribute.
29#[derive(Debug)]
30pub struct AttributeDef {
31    /// Attribute id.
32    pub id: u16,
33    /// snake_case name.
34    pub name: &'static str,
35    /// Its type.
36    pub data_type: DataType,
37    /// Writable.
38    pub writable: bool,
39    /// The reporting configuration a host writes by default, if the
40    /// attribute is worth reporting.
41    pub report: Option<ReportDefault>,
42}
43
44/// A default reporting configuration.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ReportDefault {
47    /// Seconds between reports at least.
48    pub min_interval: u16,
49    /// Seconds between reports at most.
50    pub max_interval: u16,
51    /// Reportable change, for analog types.
52    pub change: Option<u64>,
53}
54
55/// A cluster-specific command.
56#[derive(Debug)]
57pub struct CommandDef {
58    /// Command id.
59    pub id: u8,
60    /// snake_case name.
61    pub name: &'static str,
62    /// Its fields, in order.
63    pub fields: &'static [FieldDef],
64}
65
66/// A command field.
67#[derive(Debug)]
68pub struct FieldDef {
69    /// snake_case name.
70    pub name: &'static str,
71    /// How it is encoded.
72    pub kind: FieldKind,
73    /// May be absent at the end of the frame.
74    pub optional: bool,
75}
76
77/// How a command field is encoded.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum FieldKind {
80    /// One value of a type, without a type id.
81    Value(DataType),
82    /// A one-byte count followed by values of a type.
83    List8(DataType),
84    /// The rest of the payload, as octets.
85    Rest,
86}
87
88include!(concat!(env!("OUT_DIR"), "/clusters.rs"));
89
90/// The cluster with this id.
91pub fn cluster(id: u16) -> Option<&'static ClusterDef> {
92    CLUSTERS
93        .binary_search_by_key(&id, |c| c.id)
94        .ok()
95        .and_then(|i| CLUSTERS.get(i))
96}
97
98/// The cluster with this name.
99pub fn cluster_by_name(name: &str) -> Option<&'static ClusterDef> {
100    CLUSTERS.iter().find(|c| c.name == name)
101}
102
103impl ClusterDef {
104    /// The attribute with this id.
105    pub fn attribute(&self, id: u16) -> Option<&'static AttributeDef> {
106        self.attributes
107            .binary_search_by_key(&id, |a| a.id)
108            .ok()
109            .and_then(|i| self.attributes.get(i))
110    }
111
112    /// The attribute with this name.
113    pub fn attribute_by_name(&self, name: &str) -> Option<&'static AttributeDef> {
114        self.attributes.iter().find(|a| a.name == name)
115    }
116
117    /// The command with this id, sent in `direction`.
118    pub fn command(&self, direction: Direction, id: u8) -> Option<&'static CommandDef> {
119        let list = match direction {
120            Direction::ClientToServer => self.commands,
121            Direction::ServerToClient => self.responses,
122        };
123        list.binary_search_by_key(&id, |c| c.id)
124            .ok()
125            .and_then(|i| list.get(i))
126    }
127
128    /// The command with this name, sent in `direction`.
129    pub fn command_by_name(&self, direction: Direction, name: &str) -> Option<&'static CommandDef> {
130        let list = match direction {
131            Direction::ClientToServer => self.commands,
132            Direction::ServerToClient => self.responses,
133        };
134        list.iter().find(|c| c.name == name)
135    }
136}
137
138/// A command's fields did not encode.
139#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
140pub enum EncodeError {
141    /// A required field had no value.
142    #[error("missing field {0}")]
143    Missing(&'static str),
144    /// More values than fields.
145    #[error("{0} values for {1} fields")]
146    TooMany(usize, usize),
147}
148
149impl CommandDef {
150    /// Decode a payload into named fields. Absent optional fields are left
151    /// out.
152    pub fn decode(&self, payload: &[u8]) -> Result<Vec<(&'static str, Value)>, ValueError> {
153        let mut r = Reader::new(payload);
154        let mut out = Vec::with_capacity(self.fields.len());
155        for field in self.fields {
156            if field.optional && r.is_empty() {
157                break;
158            }
159            let value = match field.kind {
160                FieldKind::Value(t) => Value::decode(t, &mut r)?,
161                FieldKind::List8(t) => {
162                    let count = usize::from(r.u8()?);
163                    let mut items = Vec::with_capacity(count.min(r.remaining()));
164                    for _ in 0..count {
165                        items.push(Value::decode(t, &mut r)?);
166                    }
167                    Value::List(DataType::Array, t, Some(items))
168                }
169                FieldKind::Rest => Value::Octets(DataType::OctetString, Some(r.rest().to_vec())),
170            };
171            out.push((field.name, value));
172        }
173        Ok(out)
174    }
175
176    /// Encode values given in field order. Trailing optional fields may be
177    /// left out.
178    pub fn encode(&self, values: &[Value]) -> Result<Vec<u8>, EncodeError> {
179        if values.len() > self.fields.len() {
180            return Err(EncodeError::TooMany(values.len(), self.fields.len()));
181        }
182        let mut w = Vec::new();
183        for (i, field) in self.fields.iter().enumerate() {
184            let Some(value) = values.get(i) else {
185                if field.optional {
186                    break;
187                }
188                return Err(EncodeError::Missing(field.name));
189            };
190            match (field.kind, value) {
191                (FieldKind::List8(_), Value::List(_, _, items)) => {
192                    let items = items.as_deref().unwrap_or(&[]);
193                    w.put_u8(items.len().min(255) as u8);
194                    items.iter().take(255).for_each(|v| v.encode(&mut w));
195                }
196                (FieldKind::Rest, Value::Octets(_, bytes)) => {
197                    w.put_bytes(bytes.as_deref().unwrap_or(&[]))
198                }
199                _ => value.encode(&mut w),
200            }
201        }
202        Ok(w)
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    fn tables_are_sorted_and_findable() {
212        assert!(CLUSTERS.windows(2).all(|w| w[0].id < w[1].id));
213        for c in CLUSTERS {
214            assert!(
215                c.attributes.windows(2).all(|w| w[0].id < w[1].id),
216                "{}",
217                c.name
218            );
219            assert_eq!(cluster(c.id).map(|x| x.name), Some(c.name));
220        }
221        let t = cluster(cluster_id::TEMPERATURE_MEASUREMENT).unwrap();
222        let mv = t
223            .attribute(attr::temperature_measurement::MEASURED_VALUE)
224            .unwrap();
225        assert_eq!(mv.data_type, DataType::Int16);
226        assert_eq!(
227            mv.report,
228            Some(ReportDefault {
229                min_interval: 10,
230                max_interval: 3600,
231                change: Some(10)
232            })
233        );
234        assert_eq!(cluster_by_name("on_off").unwrap().id, 0x0006);
235    }
236
237    #[test]
238    fn commands_encode_and_decode_from_the_table() {
239        let level = cluster(cluster_id::LEVEL_CONTROL).unwrap();
240        let mtl = level
241            .command(
242                Direction::ClientToServer,
243                command::level_control::MOVE_TO_LEVEL,
244            )
245            .unwrap();
246        let bytes = mtl.encode(&[Value::u8(128), Value::u16(10)]).unwrap();
247        assert_eq!(bytes, [128, 10, 0]);
248        let fields = mtl.decode(&bytes).unwrap();
249        assert_eq!(
250            fields,
251            vec![
252                ("level", Value::u8(128)),
253                ("transition_time", Value::u16(10))
254            ]
255        );
256        assert_eq!(
257            mtl.encode(&[Value::u8(1)]),
258            Err(EncodeError::Missing("transition_time"))
259        );
260
261        let ias = cluster(cluster_id::IAS_ZONE).unwrap();
262        let notify = ias
263            .command(
264                Direction::ServerToClient,
265                response::ias_zone::ZONE_STATUS_CHANGE_NOTIFICATION,
266            )
267            .unwrap();
268        let fields = notify.decode(&[0x01, 0x00, 0x00]).unwrap();
269        assert_eq!(
270            fields,
271            vec![
272                ("zone_status", Value::map16(1)),
273                ("extended_status", Value::map8(0))
274            ]
275        );
276
277        let groups = cluster(cluster_id::GROUPS).unwrap();
278        let get = groups
279            .command(
280                Direction::ClientToServer,
281                command::groups::GET_GROUP_MEMBERSHIP,
282            )
283            .unwrap();
284        let list = Value::List(
285            DataType::Array,
286            DataType::Uint16,
287            Some(vec![Value::u16(1), Value::u16(2)]),
288        );
289        let bytes = get.encode(std::slice::from_ref(&list)).unwrap();
290        assert_eq!(bytes, [2, 1, 0, 2, 0]);
291        assert_eq!(get.decode(&bytes).unwrap(), vec![("group_list", list)]);
292    }
293}