1use zigbee_primitives::wire::{Reader, Writer};
4
5use crate::types::DataType;
6use crate::value::{Value, ValueError};
7
8pub 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#[derive(Debug, Clone, PartialEq)]
29pub struct ReadRecord {
30 pub attribute: u16,
32 pub status: u8,
34 pub value: Option<Value>,
36}
37
38#[derive(Debug, Clone, PartialEq)]
40pub struct ReportingConfig {
41 pub attribute: u16,
43 pub data_type: DataType,
45 pub min_interval: u16,
47 pub max_interval: u16,
49 pub reportable_change: Option<Value>,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct ReportingStatus {
56 pub status: u8,
58 pub attribute: Option<u16>,
60}
61
62#[derive(Debug, Clone, PartialEq)]
64pub enum Global {
65 ReadAttributes(Vec<u16>),
67 ReadAttributesResponse(Vec<ReadRecord>),
69 WriteAttributes(Vec<(u16, Value)>),
71 WriteAttributesUndivided(Vec<(u16, Value)>),
73 WriteAttributesResponse(Vec<(u8, Option<u16>)>),
75 WriteAttributesNoResponse(Vec<(u16, Value)>),
77 ConfigureReporting(Vec<ReportingConfig>),
79 ConfigureReportingResponse(Vec<ReportingStatus>),
81 ReportAttributes(Vec<(u16, Value)>),
83 DefaultResponse {
85 command: u8,
87 status: u8,
89 },
90 DiscoverAttributes {
92 start: u16,
94 max: u8,
96 },
97 DiscoverAttributesResponse {
99 complete: bool,
101 attributes: Vec<(u16, DataType)>,
103 },
104 Other {
106 command: u8,
108 payload: Vec<u8>,
110 },
111}
112
113pub 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 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 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 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 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 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}