Skip to main content

zigbee_zcl/
foundation.rs

1//! Global (foundation) commands, common to every cluster (ZCL chapter 2.5).
2
3use zigbee_primitives::wire::{Reader, Writer};
4
5use crate::types::DataType;
6use crate::value::{Value, ValueError};
7
8/// Global command ids.
9pub mod id {
10    #![allow(missing_docs)]
11    pub const READ_ATTRIBUTES: u8 = 0x00;
12    pub const READ_ATTRIBUTES_RESPONSE: u8 = 0x01;
13    pub const WRITE_ATTRIBUTES: u8 = 0x02;
14    pub const WRITE_ATTRIBUTES_UNDIVIDED: u8 = 0x03;
15    pub const WRITE_ATTRIBUTES_RESPONSE: u8 = 0x04;
16    pub const WRITE_ATTRIBUTES_NO_RESPONSE: u8 = 0x05;
17    pub const CONFIGURE_REPORTING: u8 = 0x06;
18    pub const CONFIGURE_REPORTING_RESPONSE: u8 = 0x07;
19    pub const READ_REPORTING_CONFIGURATION: u8 = 0x08;
20    pub const READ_REPORTING_CONFIGURATION_RESPONSE: u8 = 0x09;
21    pub const REPORT_ATTRIBUTES: u8 = 0x0A;
22    pub const DEFAULT_RESPONSE: u8 = 0x0B;
23    pub const DISCOVER_ATTRIBUTES: u8 = 0x0C;
24    pub const DISCOVER_ATTRIBUTES_RESPONSE: u8 = 0x0D;
25}
26
27/// One record of a read attributes response.
28#[derive(Debug, Clone, PartialEq)]
29pub struct ReadRecord {
30    /// Attribute id.
31    pub attribute: u16,
32    /// [`crate::status`] code.
33    pub status: u8,
34    /// The value, when `status` is success.
35    pub value: Option<Value>,
36}
37
38/// One attribute's reporting configuration.
39#[derive(Debug, Clone, PartialEq)]
40pub struct ReportingConfig {
41    /// Attribute id.
42    pub attribute: u16,
43    /// The attribute's type.
44    pub data_type: DataType,
45    /// Seconds between reports at least.
46    pub min_interval: u16,
47    /// Seconds between reports at most (0xFFFF: no periodic reports).
48    pub max_interval: u16,
49    /// Change that triggers a report, for analog types only.
50    pub reportable_change: Option<Value>,
51}
52
53/// One record of a configure reporting response.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct ReportingStatus {
56    /// [`crate::status`] code.
57    pub status: u8,
58    /// The attribute, absent in the single all-success record.
59    pub attribute: Option<u16>,
60}
61
62/// A global command.
63#[derive(Debug, Clone, PartialEq)]
64pub enum Global {
65    /// Read attributes.
66    ReadAttributes(Vec<u16>),
67    /// The answer.
68    ReadAttributesResponse(Vec<ReadRecord>),
69    /// Write attributes.
70    WriteAttributes(Vec<(u16, Value)>),
71    /// Write attributes, all or none.
72    WriteAttributesUndivided(Vec<(u16, Value)>),
73    /// The answer: one success record, or a record per failure.
74    WriteAttributesResponse(Vec<(u8, Option<u16>)>),
75    /// Write attributes without an answer.
76    WriteAttributesNoResponse(Vec<(u16, Value)>),
77    /// Configure reporting (attributes the receiver reports).
78    ConfigureReporting(Vec<ReportingConfig>),
79    /// The answer.
80    ConfigureReportingResponse(Vec<ReportingStatus>),
81    /// An attribute report.
82    ReportAttributes(Vec<(u16, Value)>),
83    /// The default response.
84    DefaultResponse {
85        /// The command answered.
86        command: u8,
87        /// [`crate::status`] code.
88        status: u8,
89    },
90    /// Discover attributes.
91    DiscoverAttributes {
92        /// First attribute id.
93        start: u16,
94        /// Most attributes to return.
95        max: u8,
96    },
97    /// The answer.
98    DiscoverAttributesResponse {
99        /// No more attributes.
100        complete: bool,
101        /// Attributes and their types.
102        attributes: Vec<(u16, DataType)>,
103    },
104    /// A global command this crate does not decode.
105    Other {
106        /// Command id.
107        command: u8,
108        /// Raw payload.
109        payload: Vec<u8>,
110    },
111}
112
113/// A global command's payload did not decode.
114pub type DecodeError = ValueError;
115
116fn read_type(r: &mut Reader<'_>) -> Result<DataType, ValueError> {
117    let id = r.u8()?;
118    DataType::from_u8(id).ok_or(ValueError::UnknownType(id))
119}
120
121fn read_values(r: &mut Reader<'_>) -> Result<Vec<(u16, Value)>, ValueError> {
122    let mut out = Vec::new();
123    while !r.is_empty() {
124        let attribute = r.u16()?;
125        out.push((attribute, Value::decode_typed(r)?));
126    }
127    Ok(out)
128}
129
130impl Global {
131    /// The command id.
132    pub fn command_id(&self) -> u8 {
133        match self {
134            Global::ReadAttributes(_) => id::READ_ATTRIBUTES,
135            Global::ReadAttributesResponse(_) => id::READ_ATTRIBUTES_RESPONSE,
136            Global::WriteAttributes(_) => id::WRITE_ATTRIBUTES,
137            Global::WriteAttributesUndivided(_) => id::WRITE_ATTRIBUTES_UNDIVIDED,
138            Global::WriteAttributesResponse(_) => id::WRITE_ATTRIBUTES_RESPONSE,
139            Global::WriteAttributesNoResponse(_) => id::WRITE_ATTRIBUTES_NO_RESPONSE,
140            Global::ConfigureReporting(_) => id::CONFIGURE_REPORTING,
141            Global::ConfigureReportingResponse(_) => id::CONFIGURE_REPORTING_RESPONSE,
142            Global::ReportAttributes(_) => id::REPORT_ATTRIBUTES,
143            Global::DefaultResponse { .. } => id::DEFAULT_RESPONSE,
144            Global::DiscoverAttributes { .. } => id::DISCOVER_ATTRIBUTES,
145            Global::DiscoverAttributesResponse { .. } => id::DISCOVER_ATTRIBUTES_RESPONSE,
146            Global::Other { command, .. } => *command,
147        }
148    }
149
150    /// Decode a global command's payload.
151    pub fn decode(command: u8, payload: &[u8]) -> Result<Global, DecodeError> {
152        let mut r = Reader::new(payload);
153        Ok(match command {
154            id::READ_ATTRIBUTES => {
155                let count = r.remaining() / 2;
156                Global::ReadAttributes(r.u16_list(count)?)
157            }
158            id::READ_ATTRIBUTES_RESPONSE => {
159                let mut records = Vec::new();
160                while !r.is_empty() {
161                    let attribute = r.u16()?;
162                    let status = r.u8()?;
163                    let value = if status == crate::status::SUCCESS {
164                        Some(Value::decode_typed(&mut r)?)
165                    } else {
166                        None
167                    };
168                    records.push(ReadRecord {
169                        attribute,
170                        status,
171                        value,
172                    });
173                }
174                Global::ReadAttributesResponse(records)
175            }
176            id::WRITE_ATTRIBUTES => Global::WriteAttributes(read_values(&mut r)?),
177            id::WRITE_ATTRIBUTES_UNDIVIDED => {
178                Global::WriteAttributesUndivided(read_values(&mut r)?)
179            }
180            id::WRITE_ATTRIBUTES_NO_RESPONSE => {
181                Global::WriteAttributesNoResponse(read_values(&mut r)?)
182            }
183            id::REPORT_ATTRIBUTES => Global::ReportAttributes(read_values(&mut r)?),
184            id::WRITE_ATTRIBUTES_RESPONSE => {
185                let mut records = Vec::new();
186                while !r.is_empty() {
187                    let status = r.u8()?;
188                    let attribute = if r.remaining() >= 2 {
189                        Some(r.u16()?)
190                    } else {
191                        None
192                    };
193                    records.push((status, attribute));
194                }
195                Global::WriteAttributesResponse(records)
196            }
197            id::CONFIGURE_REPORTING => {
198                let mut configs = Vec::new();
199                while !r.is_empty() {
200                    let direction = r.u8()?;
201                    let attribute = r.u16()?;
202                    if direction != 0 {
203                        // "Received" configurations carry only a timeout;
204                        // keep the record so the attribute is not lost.
205                        let timeout = r.u16()?;
206                        configs.push(ReportingConfig {
207                            attribute,
208                            data_type: DataType::NoData,
209                            min_interval: 0,
210                            max_interval: timeout,
211                            reportable_change: None,
212                        });
213                        continue;
214                    }
215                    let data_type = read_type(&mut r)?;
216                    let min_interval = r.u16()?;
217                    let max_interval = r.u16()?;
218                    let reportable_change = if data_type.is_analog() {
219                        Some(Value::decode(data_type, &mut r)?)
220                    } else {
221                        None
222                    };
223                    configs.push(ReportingConfig {
224                        attribute,
225                        data_type,
226                        min_interval,
227                        max_interval,
228                        reportable_change,
229                    });
230                }
231                Global::ConfigureReporting(configs)
232            }
233            id::CONFIGURE_REPORTING_RESPONSE => {
234                let mut records = Vec::new();
235                while !r.is_empty() {
236                    let status = r.u8()?;
237                    if r.is_empty() {
238                        records.push(ReportingStatus {
239                            status,
240                            attribute: None,
241                        });
242                        break;
243                    }
244                    let _direction = r.u8()?;
245                    records.push(ReportingStatus {
246                        status,
247                        attribute: Some(r.u16()?),
248                    });
249                }
250                Global::ConfigureReportingResponse(records)
251            }
252            id::DEFAULT_RESPONSE => Global::DefaultResponse {
253                command: r.u8()?,
254                status: r.u8()?,
255            },
256            id::DISCOVER_ATTRIBUTES => Global::DiscoverAttributes {
257                start: r.u16()?,
258                max: r.u8()?,
259            },
260            id::DISCOVER_ATTRIBUTES_RESPONSE => {
261                let complete = r.bool()?;
262                let mut attributes = Vec::new();
263                while !r.is_empty() {
264                    let attribute = r.u16()?;
265                    attributes.push((attribute, read_type(&mut r)?));
266                }
267                Global::DiscoverAttributesResponse {
268                    complete,
269                    attributes,
270                }
271            }
272            other => Global::Other {
273                command: other,
274                payload: payload.to_vec(),
275            },
276        })
277    }
278
279    /// Encode the payload.
280    pub fn encode(&self) -> Vec<u8> {
281        let mut w = Vec::with_capacity(16);
282        match self {
283            Global::ReadAttributes(ids) => ids.iter().for_each(|a| w.put_u16(*a)),
284            Global::ReadAttributesResponse(records) => {
285                for rec in records {
286                    w.put_u16(rec.attribute);
287                    w.put_u8(rec.status);
288                    if let (crate::status::SUCCESS, Some(v)) = (rec.status, &rec.value) {
289                        v.encode_typed(&mut w);
290                    }
291                }
292            }
293            Global::WriteAttributes(values)
294            | Global::WriteAttributesUndivided(values)
295            | Global::WriteAttributesNoResponse(values)
296            | Global::ReportAttributes(values) => {
297                for (attribute, value) in values {
298                    w.put_u16(*attribute);
299                    value.encode_typed(&mut w);
300                }
301            }
302            Global::WriteAttributesResponse(records) => {
303                for (status, attribute) in records {
304                    w.put_u8(*status);
305                    if let Some(a) = attribute {
306                        w.put_u16(*a);
307                    }
308                }
309            }
310            Global::ConfigureReporting(configs) => {
311                for c in configs {
312                    w.put_u8(0);
313                    w.put_u16(c.attribute);
314                    w.put_u8(c.data_type.id());
315                    w.put_u16(c.min_interval);
316                    w.put_u16(c.max_interval);
317                    if c.data_type.is_analog() {
318                        match &c.reportable_change {
319                            Some(change) => change.encode(&mut w),
320                            None => Value::Uint(c.data_type, 0).encode(&mut w),
321                        }
322                    }
323                }
324            }
325            Global::ConfigureReportingResponse(records) => {
326                for rec in records {
327                    w.put_u8(rec.status);
328                    if let Some(a) = rec.attribute {
329                        w.put_u8(0);
330                        w.put_u16(a);
331                    }
332                }
333            }
334            Global::DefaultResponse { command, status } => {
335                w.put_u8(*command);
336                w.put_u8(*status);
337            }
338            Global::DiscoverAttributes { start, max } => {
339                w.put_u16(*start);
340                w.put_u8(*max);
341            }
342            Global::DiscoverAttributesResponse {
343                complete,
344                attributes,
345            } => {
346                w.put_u8(u8::from(*complete));
347                for (a, t) in attributes {
348                    w.put_u16(*a);
349                    w.put_u8(t.id());
350                }
351            }
352            Global::Other { payload, .. } => w.put_bytes(payload),
353        }
354        w
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn global_commands_round_trip() {
364        let commands = vec![
365            Global::ReadAttributes(vec![0x0004, 0x0005]),
366            Global::ReadAttributesResponse(vec![
367                ReadRecord {
368                    attribute: 4,
369                    status: 0,
370                    value: Some(Value::string("LUMI")),
371                },
372                ReadRecord {
373                    attribute: 0x4000,
374                    status: crate::status::UNSUPPORTED_ATTRIBUTE,
375                    value: None,
376                },
377            ]),
378            Global::WriteAttributes(vec![(0x0010, Value::Ieee(zigbee_primitives::Ieee(5)))]),
379            Global::WriteAttributesResponse(vec![(0, None)]),
380            Global::ConfigureReporting(vec![
381                ReportingConfig {
382                    attribute: 0,
383                    data_type: DataType::Int16,
384                    min_interval: 10,
385                    max_interval: 3600,
386                    reportable_change: Some(Value::i16(10)),
387                },
388                ReportingConfig {
389                    attribute: 0,
390                    data_type: DataType::Bool,
391                    min_interval: 0,
392                    max_interval: 3600,
393                    reportable_change: None,
394                },
395            ]),
396            Global::ConfigureReportingResponse(vec![ReportingStatus {
397                status: 0,
398                attribute: None,
399            }]),
400            Global::ConfigureReportingResponse(vec![
401                ReportingStatus {
402                    status: 0x8C,
403                    attribute: Some(1),
404                },
405                ReportingStatus {
406                    status: 0x86,
407                    attribute: Some(2),
408                },
409            ]),
410            Global::ReportAttributes(vec![(0, Value::i16(2150))]),
411            Global::DefaultResponse {
412                command: 0x02,
413                status: 0,
414            },
415            Global::DiscoverAttributes { start: 0, max: 16 },
416            Global::DiscoverAttributesResponse {
417                complete: true,
418                attributes: vec![(0, DataType::Uint8)],
419            },
420        ];
421        for c in commands {
422            assert_eq!(
423                Global::decode(c.command_id(), &c.encode()).unwrap(),
424                c,
425                "{c:?}"
426            );
427        }
428    }
429
430    #[test]
431    fn decodes_a_real_temperature_report() {
432        // measured_value (0x0000), int16, 21.50 degrees
433        let g = Global::decode(id::REPORT_ATTRIBUTES, &[0x00, 0x00, 0x29, 0x66, 0x08]).unwrap();
434        assert_eq!(g, Global::ReportAttributes(vec![(0, Value::i16(2150))]));
435    }
436}