1use matter_model::Shape;
5use rs_matter::im::{AttrResp, EventResp, ReportDataResp};
6use serde_json::Value;
7
8use crate::{AttributeValue, EventValue};
9
10pub(crate) fn items<'a, T, C>(
13 c: &rs_matter::tlv::TLVContainer<'a, T, C>,
14) -> Result<rs_matter::tlv::TLVContainerIter<'a, T>, rs_matter::error::Error>
15where
16 T: rs_matter::tlv::FromTLV<'a>,
17{
18 c.element().container()?;
19 Ok(c.iter())
20}
21
22#[derive(Default)]
24pub(crate) struct Collected {
25 pub attributes: Vec<AttributeValue>,
26 pub events: Vec<EventValue>,
27}
28
29pub fn decode_report_data(
32 node: u64,
33 payload: &[u8],
34) -> Result<(Vec<AttributeValue>, Vec<EventValue>), crate::Error> {
35 use rs_matter::tlv::{FromTLV, TLVElement};
36 let resp = ReportDataResp::from_tlv(&TLVElement::new(payload))?;
37 let mut collected = Collected::default();
38 collected.add_chunk(node, &resp);
39 Ok((collected.attributes, collected.events))
40}
41
42impl Collected {
43 pub fn add_chunk(&mut self, node: u64, resp: &ReportDataResp<'_>) {
50 let attr_reports = resp.attr_reports.as_ref().map(items).transpose();
51 let event_reports = resp.event_reports.as_ref().map(items).transpose();
52 let (attr_reports, event_reports) = match (attr_reports, event_reports) {
53 (Ok(a), Ok(e)) => (a, e),
54 _ => {
55 log::warn!("node {node:016X}: malformed report, not a list of reports");
56 return;
57 }
58 };
59
60 if let Some(reports) = attr_reports {
61 for report in reports {
62 match report {
63 Ok(AttrResp::Data(data)) => {
64 let (Some(endpoint), Some(cluster), Some(attribute)) =
65 (data.path.endpoint, data.path.cluster, data.path.attr)
66 else {
67 continue;
68 };
69 let attr =
70 matter_model::cluster(cluster).and_then(|c| c.attribute(attribute));
71 let append = data.path.list_index.as_ref().is_some_and(|i| i.is_none());
72 let shape = match (attr, append) {
73 (Some(a), true) => Shape::of(a.ty),
74 (Some(a), false) => a.shape(),
75 (None, _) => Shape::ANY,
76 };
77 let value = match matter_model::to_json(&data.data, shape) {
78 Ok(v) => v,
79 Err(e) => {
80 log::warn!(
81 "node {node:016X}: undecodable {endpoint}/{cluster:#06x}/{attribute:#06x}: {e}"
82 );
83 continue;
84 }
85 };
86 if append {
87 match self.attributes.iter_mut().rev().find(|a| {
88 a.endpoint == endpoint
89 && a.cluster == cluster
90 && a.attribute == attribute
91 }) {
92 Some(AttributeValue {
93 value: Value::Array(items),
94 ..
95 }) => items.push(value),
96 _ => self.attributes.push(AttributeValue {
97 node,
98 endpoint,
99 cluster,
100 attribute,
101 value: Value::Array(vec![value]),
102 status: None,
103 }),
104 }
105 } else {
106 self.attributes.push(AttributeValue {
107 node,
108 endpoint,
109 cluster,
110 attribute,
111 value,
112 status: None,
113 });
114 }
115 }
116 Ok(AttrResp::Status(status)) => {
117 let path = status.path;
118 self.attributes.push(AttributeValue {
119 node,
120 endpoint: path.endpoint.unwrap_or_default(),
121 cluster: path.cluster.unwrap_or_default(),
122 attribute: path.attr.unwrap_or_default(),
123 value: Value::Null,
124 status: Some(format!("{:?}", status.status.status)),
125 });
126 }
127 Err(e) => log::warn!("node {node:016X}: malformed attribute report: {e:?}"),
128 }
129 }
130 }
131
132 if let Some(reports) = event_reports {
133 for report in reports {
134 match report {
135 Ok(EventResp::Data(data)) => {
136 let (Some(endpoint), Some(cluster), Some(event)) =
137 (data.path.endpoint, data.path.cluster, data.path.event)
138 else {
139 continue;
140 };
141 let shape = matter_model::cluster(cluster)
142 .and_then(|c| c.event(event))
143 .map_or(Shape::ANY, |e| e.shape());
144 match matter_model::to_json(&data.data, shape) {
145 Ok(value) => self.events.push(EventValue {
146 node,
147 endpoint,
148 cluster,
149 event,
150 number: data.event_number,
151 data: value,
152 }),
153 Err(e) => log::warn!(
154 "node {node:016X}: undecodable event {endpoint}/{cluster:#06x}/{event:#06x}: {e}"
155 ),
156 }
157 }
158 Ok(EventResp::Status(status)) => log::debug!(
159 "node {node:016X}: event status {:?} for {:?}",
160 status.status.status,
161 status.path
162 ),
163 Err(e) => log::warn!("node {node:016X}: malformed event report: {e:?}"),
164 }
165 }
166 }
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn a_report_whose_reports_are_not_a_list_is_refused() {
176 let (attributes, events) = decode_report_data(1, &[0x15, 0x24, 0x01, 0x05, 0x18]).unwrap();
178 assert!(attributes.is_empty() && events.is_empty());
179 }
180}