matc 0.1.3

Matter protocol library (controller side)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Matter TLV encoders and decoders for OTA Software Update Requestor Cluster
//! Cluster ID: 0x002A
//!
//! This file is automatically generated from OTARequestor.xml

#![allow(clippy::too_many_arguments)]

use crate::tlv;
use anyhow;
use serde_json;


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum AnnouncementReason {
    /// An OTA Provider is announcing its presence.
    Simpleannouncement = 0,
    /// An OTA Provider is announcing, either to a single Node or to a group of Nodes, that a new Software Image MAY be available.
    Updateavailable = 1,
    /// An OTA Provider is announcing, either to a single Node or to a group of Nodes, that a new Software Image MAY be available, which contains an update that needs to be applied urgently.
    Urgentupdateavailable = 2,
}

impl AnnouncementReason {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(AnnouncementReason::Simpleannouncement),
            1 => Some(AnnouncementReason::Updateavailable),
            2 => Some(AnnouncementReason::Urgentupdateavailable),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<AnnouncementReason> for u8 {
    fn from(val: AnnouncementReason) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ChangeReason {
    /// The reason for a state change is unknown.
    Unknown = 0,
    /// The reason for a state change is the success of a prior operation.
    Success = 1,
    /// The reason for a state change is the failure of a prior operation.
    Failure = 2,
    /// The reason for a state change is a time-out.
    Timeout = 3,
    /// The reason for a state change is a request by the OTA Provider to wait.
    Delaybyprovider = 4,
}

impl ChangeReason {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ChangeReason::Unknown),
            1 => Some(ChangeReason::Success),
            2 => Some(ChangeReason::Failure),
            3 => Some(ChangeReason::Timeout),
            4 => Some(ChangeReason::Delaybyprovider),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<ChangeReason> for u8 {
    fn from(val: ChangeReason) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum UpdateState {
    /// Current state is not yet determined.
    Unknown = 0,
    /// Indicate a Node not yet in the process of software update.
    Idle = 1,
    /// Indicate a Node in the process of querying an OTA Provider.
    Querying = 2,
    /// Indicate a Node waiting after a Busy response.
    Delayedonquery = 3,
    /// Indicate a Node currently in the process of downloading a software update.
    Downloading = 4,
    /// Indicate a Node currently in the process of verifying and applying a software update.
    Applying = 5,
    /// Indicate a Node waiting caused by AwaitNextAction response.
    Delayedonapply = 6,
    /// Indicate a Node in the process of recovering to a previous version.
    Rollingback = 7,
    /// Indicate a Node is capable of user consent.
    Delayedonuserconsent = 8,
}

impl UpdateState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(UpdateState::Unknown),
            1 => Some(UpdateState::Idle),
            2 => Some(UpdateState::Querying),
            3 => Some(UpdateState::Delayedonquery),
            4 => Some(UpdateState::Downloading),
            5 => Some(UpdateState::Applying),
            6 => Some(UpdateState::Delayedonapply),
            7 => Some(UpdateState::Rollingback),
            8 => Some(UpdateState::Delayedonuserconsent),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<UpdateState> for u8 {
    fn from(val: UpdateState) -> Self {
        val as u8
    }
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ProviderLocation {
    pub provider_node_id: Option<u64>,
    pub endpoint: Option<u16>,
}

// Command encoders

/// Encode AnnounceOTAProvider command (0x00)
pub fn encode_announce_ota_provider(provider_node_id: u64, vendor_id: u16, announcement_reason: AnnouncementReason, metadata_for_node: Option<Vec<u8>>, endpoint: u16) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt64(provider_node_id)).into());
    tlv_fields.push((1, tlv::TlvItemValueEnc::UInt16(vendor_id)).into());
    tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(announcement_reason.to_u8())).into());
    if let Some(x) = metadata_for_node { tlv_fields.push((3, tlv::TlvItemValueEnc::OctetString(x)).into()); }
    tlv_fields.push((4, tlv::TlvItemValueEnc::UInt16(endpoint)).into());
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode DefaultOTAProviders attribute (0x0000)
pub fn decode_default_ota_providers(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ProviderLocation>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ProviderLocation {
                provider_node_id: item.get_int(&[1]),
                endpoint: item.get_int(&[2]).map(|v| v as u16),
            });
        }
    }
    Ok(res)
}

/// Decode UpdatePossible attribute (0x0001)
pub fn decode_update_possible(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
    if let tlv::TlvItemValue::Bool(v) = inp {
        Ok(*v)
    } else {
        Err(anyhow::anyhow!("Expected Bool"))
    }
}

/// Decode UpdateState attribute (0x0002)
pub fn decode_update_state(inp: &tlv::TlvItemValue) -> anyhow::Result<UpdateState> {
    if let tlv::TlvItemValue::Int(v) = inp {
        UpdateState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode UpdateStateProgress attribute (0x0003)
pub fn decode_update_state_progress(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v as u8))
    } else {
        Ok(None)
    }
}


// JSON dispatcher function

/// Decode attribute value and return as JSON string
///
/// # Parameters
/// * `cluster_id` - The cluster identifier
/// * `attribute_id` - The attribute identifier
/// * `tlv_value` - The TLV value to decode
///
/// # Returns
/// JSON string representation of the decoded value or error
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
    // Verify this is the correct cluster
    if cluster_id != 0x002A {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x002A, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_default_ota_providers(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_update_possible(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_update_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_update_state_progress(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
    }
}

/// Get list of all attributes supported by this cluster
///
/// # Returns
/// Vector of tuples containing (attribute_id, attribute_name)
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x0000, "DefaultOTAProviders"),
        (0x0001, "UpdatePossible"),
        (0x0002, "UpdateState"),
        (0x0003, "UpdateStateProgress"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "AnnounceOTAProvider"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("AnnounceOTAProvider"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "provider_node_id", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "vendor_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "announcement_reason", kind: crate::clusters::codec::FieldKind::Enum { name: "AnnouncementReason", variants: &[(0, "Simpleannouncement"), (1, "Updateavailable"), (2, "Urgentupdateavailable")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "metadata_for_node", kind: crate::clusters::codec::FieldKind::OctetString, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 4, name: "endpoint", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let provider_node_id = crate::clusters::codec::json_util::get_u64(args, "provider_node_id")?;
        let vendor_id = crate::clusters::codec::json_util::get_u16(args, "vendor_id")?;
        let announcement_reason = {
            let n = crate::clusters::codec::json_util::get_u64(args, "announcement_reason")?;
            AnnouncementReason::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid AnnouncementReason: {}", n))?
        };
        let metadata_for_node = crate::clusters::codec::json_util::get_opt_octstr(args, "metadata_for_node")?;
        let endpoint = crate::clusters::codec::json_util::get_u16(args, "endpoint")?;
        encode_announce_ota_provider(provider_node_id, vendor_id, announcement_reason, metadata_for_node, endpoint)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `AnnounceOTAProvider` command on cluster `OTA Software Update Requestor`.
pub async fn announce_ota_provider(conn: &crate::controller::Connection, endpoint: u16, provider_node_id: u64, vendor_id: u16, announcement_reason: AnnouncementReason, metadata_for_node: Option<Vec<u8>>, endpoint_: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_REQUESTOR, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_REQUESTOR_CMD_ID_ANNOUNCEOTAPROVIDER, &encode_announce_ota_provider(provider_node_id, vendor_id, announcement_reason, metadata_for_node, endpoint_)?).await?;
    Ok(())
}

/// Read `DefaultOTAProviders` attribute from cluster `OTA Software Update Requestor`.
pub async fn read_default_ota_providers(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ProviderLocation>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_REQUESTOR, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_REQUESTOR_ATTR_ID_DEFAULTOTAPROVIDERS).await?;
    decode_default_ota_providers(&tlv)
}

/// Read `UpdatePossible` attribute from cluster `OTA Software Update Requestor`.
pub async fn read_update_possible(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_REQUESTOR, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_REQUESTOR_ATTR_ID_UPDATEPOSSIBLE).await?;
    decode_update_possible(&tlv)
}

/// Read `UpdateState` attribute from cluster `OTA Software Update Requestor`.
pub async fn read_update_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<UpdateState> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_REQUESTOR, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_REQUESTOR_ATTR_ID_UPDATESTATE).await?;
    decode_update_state(&tlv)
}

/// Read `UpdateStateProgress` attribute from cluster `OTA Software Update Requestor`.
pub async fn read_update_state_progress(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_REQUESTOR, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_REQUESTOR_ATTR_ID_UPDATESTATEPROGRESS).await?;
    decode_update_state_progress(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct StateTransitionEvent {
    pub previous_state: Option<UpdateState>,
    pub new_state: Option<UpdateState>,
    pub reason: Option<ChangeReason>,
    pub target_software_version: Option<u32>,
}

#[derive(Debug, serde::Serialize)]
pub struct VersionAppliedEvent {
    pub software_version: Option<u32>,
    pub product_id: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct DownloadErrorEvent {
    pub software_version: Option<u32>,
    pub bytes_downloaded: Option<u64>,
    pub progress_percent: Option<u8>,
    pub platform_code: Option<i64>,
}

// Event decoders

/// Decode StateTransition event (0x00, priority: info)
pub fn decode_state_transition_event(inp: &tlv::TlvItemValue) -> anyhow::Result<StateTransitionEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(StateTransitionEvent {
                                previous_state: item.get_int(&[0]).and_then(|v| UpdateState::from_u8(v as u8)),
                                new_state: item.get_int(&[1]).and_then(|v| UpdateState::from_u8(v as u8)),
                                reason: item.get_int(&[2]).and_then(|v| ChangeReason::from_u8(v as u8)),
                                target_software_version: item.get_int(&[3]).map(|v| v as u32),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode VersionApplied event (0x01, priority: critical)
pub fn decode_version_applied_event(inp: &tlv::TlvItemValue) -> anyhow::Result<VersionAppliedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(VersionAppliedEvent {
                                software_version: item.get_int(&[0]).map(|v| v as u32),
                                product_id: item.get_int(&[1]).map(|v| v as u16),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode DownloadError event (0x02, priority: info)
pub fn decode_download_error_event(inp: &tlv::TlvItemValue) -> anyhow::Result<DownloadErrorEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(DownloadErrorEvent {
                                software_version: item.get_int(&[0]).map(|v| v as u32),
                                bytes_downloaded: item.get_int(&[1]),
                                progress_percent: item.get_int(&[2]).map(|v| v as u8),
                                platform_code: item.get_int(&[3]).map(|v| v as i64),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}