1#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
19#[repr(u8)]
20pub enum ApplyUpdateAction {
21 Proceed = 0,
23 Awaitnextaction = 1,
25 Discontinue = 2,
27}
28
29impl ApplyUpdateAction {
30 pub fn from_u8(value: u8) -> Option<Self> {
32 match value {
33 0 => Some(ApplyUpdateAction::Proceed),
34 1 => Some(ApplyUpdateAction::Awaitnextaction),
35 2 => Some(ApplyUpdateAction::Discontinue),
36 _ => None,
37 }
38 }
39
40 pub fn to_u8(self) -> u8 {
42 self as u8
43 }
44}
45
46impl From<ApplyUpdateAction> for u8 {
47 fn from(val: ApplyUpdateAction) -> Self {
48 val as u8
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
53#[repr(u8)]
54pub enum DownloadProtocol {
55 Bdxsynchronous = 0,
57 Bdxasynchronous = 1,
59 Https = 2,
61 Vendorspecific = 3,
63}
64
65impl DownloadProtocol {
66 pub fn from_u8(value: u8) -> Option<Self> {
68 match value {
69 0 => Some(DownloadProtocol::Bdxsynchronous),
70 1 => Some(DownloadProtocol::Bdxasynchronous),
71 2 => Some(DownloadProtocol::Https),
72 3 => Some(DownloadProtocol::Vendorspecific),
73 _ => None,
74 }
75 }
76
77 pub fn to_u8(self) -> u8 {
79 self as u8
80 }
81}
82
83impl From<DownloadProtocol> for u8 {
84 fn from(val: DownloadProtocol) -> Self {
85 val as u8
86 }
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
90#[repr(u8)]
91pub enum Status {
92 Updateavailable = 0,
94 Busy = 1,
96 Notavailable = 2,
98 Downloadprotocolnotsupported = 3,
100}
101
102impl Status {
103 pub fn from_u8(value: u8) -> Option<Self> {
105 match value {
106 0 => Some(Status::Updateavailable),
107 1 => Some(Status::Busy),
108 2 => Some(Status::Notavailable),
109 3 => Some(Status::Downloadprotocolnotsupported),
110 _ => None,
111 }
112 }
113
114 pub fn to_u8(self) -> u8 {
116 self as u8
117 }
118}
119
120impl From<Status> for u8 {
121 fn from(val: Status) -> Self {
122 val as u8
123 }
124}
125
126pub struct QueryImageParams {
130 pub vendor_id: u16,
131 pub product_id: u16,
132 pub software_version: u32,
133 pub protocols_supported: Vec<DownloadProtocol>,
134 pub hardware_version: u16,
135 pub location: String,
136 pub requestor_can_consent: bool,
137 pub metadata_for_provider: Vec<u8>,
138}
139
140pub fn encode_query_image(params: QueryImageParams) -> anyhow::Result<Vec<u8>> {
142 let tlv = tlv::TlvItemEnc {
143 tag: 0,
144 value: tlv::TlvItemValueEnc::StructInvisible(vec![
145 (0, tlv::TlvItemValueEnc::UInt16(params.vendor_id)).into(),
146 (1, tlv::TlvItemValueEnc::UInt16(params.product_id)).into(),
147 (2, tlv::TlvItemValueEnc::UInt32(params.software_version)).into(),
148 (3, tlv::TlvItemValueEnc::StructAnon(params.protocols_supported.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v.to_u8())).into()).collect())).into(),
149 (4, tlv::TlvItemValueEnc::UInt16(params.hardware_version)).into(),
150 (5, tlv::TlvItemValueEnc::String(params.location)).into(),
151 (6, tlv::TlvItemValueEnc::Bool(params.requestor_can_consent)).into(),
152 (7, tlv::TlvItemValueEnc::OctetString(params.metadata_for_provider)).into(),
153 ]),
154 };
155 Ok(tlv.encode()?)
156}
157
158pub fn encode_apply_update_request(update_token: Vec<u8>, new_version: u32) -> anyhow::Result<Vec<u8>> {
160 let tlv = tlv::TlvItemEnc {
161 tag: 0,
162 value: tlv::TlvItemValueEnc::StructInvisible(vec![
163 (0, tlv::TlvItemValueEnc::OctetString(update_token)).into(),
164 (1, tlv::TlvItemValueEnc::UInt32(new_version)).into(),
165 ]),
166 };
167 Ok(tlv.encode()?)
168}
169
170pub fn encode_notify_update_applied(update_token: Vec<u8>, software_version: u32) -> anyhow::Result<Vec<u8>> {
172 let tlv = tlv::TlvItemEnc {
173 tag: 0,
174 value: tlv::TlvItemValueEnc::StructInvisible(vec![
175 (0, tlv::TlvItemValueEnc::OctetString(update_token)).into(),
176 (1, tlv::TlvItemValueEnc::UInt32(software_version)).into(),
177 ]),
178 };
179 Ok(tlv.encode()?)
180}
181
182pub fn get_command_list() -> Vec<(u32, &'static str)> {
185 vec![
186 (0x00, "QueryImage"),
187 (0x02, "ApplyUpdateRequest"),
188 (0x04, "NotifyUpdateApplied"),
189 ]
190}
191
192pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
193 match cmd_id {
194 0x00 => Some("QueryImage"),
195 0x02 => Some("ApplyUpdateRequest"),
196 0x04 => Some("NotifyUpdateApplied"),
197 _ => None,
198 }
199}
200
201pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
202 match cmd_id {
203 0x00 => Some(vec![
204 crate::clusters::codec::CommandField { tag: 0, name: "vendor_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
205 crate::clusters::codec::CommandField { tag: 1, name: "product_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
206 crate::clusters::codec::CommandField { tag: 2, name: "software_version", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
207 crate::clusters::codec::CommandField { tag: 3, name: "protocols_supported", kind: crate::clusters::codec::FieldKind::List { entry_type: "DownloadProtocolEnum" }, optional: false, nullable: false },
208 crate::clusters::codec::CommandField { tag: 4, name: "hardware_version", kind: crate::clusters::codec::FieldKind::U16, optional: true, nullable: false },
209 crate::clusters::codec::CommandField { tag: 5, name: "location", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
210 crate::clusters::codec::CommandField { tag: 6, name: "requestor_can_consent", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
211 crate::clusters::codec::CommandField { tag: 7, name: "metadata_for_provider", kind: crate::clusters::codec::FieldKind::OctetString, optional: true, nullable: false },
212 ]),
213 0x02 => Some(vec![
214 crate::clusters::codec::CommandField { tag: 0, name: "update_token", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
215 crate::clusters::codec::CommandField { tag: 1, name: "new_version", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
216 ]),
217 0x04 => Some(vec![
218 crate::clusters::codec::CommandField { tag: 0, name: "update_token", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
219 crate::clusters::codec::CommandField { tag: 1, name: "software_version", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
220 ]),
221 _ => None,
222 }
223}
224
225pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
226 match cmd_id {
227 0x00 => Err(anyhow::anyhow!("command \"QueryImage\" has complex args: use raw mode")),
228 0x02 => {
229 let update_token = crate::clusters::codec::json_util::get_octstr(args, "update_token")?;
230 let new_version = crate::clusters::codec::json_util::get_u32(args, "new_version")?;
231 encode_apply_update_request(update_token, new_version)
232 }
233 0x04 => {
234 let update_token = crate::clusters::codec::json_util::get_octstr(args, "update_token")?;
235 let software_version = crate::clusters::codec::json_util::get_u32(args, "software_version")?;
236 encode_notify_update_applied(update_token, software_version)
237 }
238 _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
239 }
240}
241
242#[derive(Debug, serde::Serialize)]
243pub struct QueryImageResponse {
244 pub status: Option<Status>,
245 pub delayed_action_time: Option<u32>,
246 pub image_uri: Option<String>,
247 pub software_version: Option<u32>,
248 pub software_version_string: Option<String>,
249 #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
250 pub update_token: Option<Vec<u8>>,
251 pub user_consent_needed: Option<bool>,
252 #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
253 pub metadata_for_requestor: Option<Vec<u8>>,
254}
255
256#[derive(Debug, serde::Serialize)]
257pub struct ApplyUpdateResponse {
258 pub action: Option<ApplyUpdateAction>,
259 pub delayed_action_time: Option<u32>,
260}
261
262pub fn decode_query_image_response(inp: &tlv::TlvItemValue) -> anyhow::Result<QueryImageResponse> {
266 if let tlv::TlvItemValue::List(_fields) = inp {
267 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
268 Ok(QueryImageResponse {
269 status: item.get_int(&[0]).and_then(|v| Status::from_u8(v as u8)),
270 delayed_action_time: item.get_int(&[1]).map(|v| v as u32),
271 image_uri: item.get_string_owned(&[2]),
272 software_version: item.get_int(&[3]).map(|v| v as u32),
273 software_version_string: item.get_string_owned(&[4]),
274 update_token: item.get_octet_string_owned(&[5]),
275 user_consent_needed: item.get_bool(&[6]),
276 metadata_for_requestor: item.get_octet_string_owned(&[7]),
277 })
278 } else {
279 Err(anyhow::anyhow!("Expected struct fields"))
280 }
281}
282
283pub fn decode_apply_update_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ApplyUpdateResponse> {
285 if let tlv::TlvItemValue::List(_fields) = inp {
286 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
287 Ok(ApplyUpdateResponse {
288 action: item.get_int(&[0]).and_then(|v| ApplyUpdateAction::from_u8(v as u8)),
289 delayed_action_time: item.get_int(&[1]).map(|v| v as u32),
290 })
291 } else {
292 Err(anyhow::anyhow!("Expected struct fields"))
293 }
294}
295
296pub async fn query_image(conn: &crate::controller::Connection, endpoint: u16, params: QueryImageParams) -> anyhow::Result<QueryImageResponse> {
300 let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_PROVIDER, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_PROVIDER_CMD_ID_QUERYIMAGE, &encode_query_image(params)?).await?;
301 decode_query_image_response(&tlv)
302}
303
304pub async fn apply_update_request(conn: &crate::controller::Connection, endpoint: u16, update_token: Vec<u8>, new_version: u32) -> anyhow::Result<ApplyUpdateResponse> {
306 let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_PROVIDER, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_PROVIDER_CMD_ID_APPLYUPDATEREQUEST, &encode_apply_update_request(update_token, new_version)?).await?;
307 decode_apply_update_response(&tlv)
308}
309
310pub async fn notify_update_applied(conn: &crate::controller::Connection, endpoint: u16, update_token: Vec<u8>, software_version: u32) -> anyhow::Result<()> {
312 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_PROVIDER, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_PROVIDER_CMD_ID_NOTIFYUPDATEAPPLIED, &encode_notify_update_applied(update_token, software_version)?).await?;
313 Ok(())
314}
315