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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Matter TLV encoders and decoders for Service Area Cluster
//! Cluster ID: 0x0150
//!
//! This file is automatically generated from ServiceArea.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 OperationalStatus {
    /// The device has not yet started operating at the given area, or has not finished operating at that area but it is not currently operating at the area
    Pending = 0,
    /// The device is currently operating at the given area
    Operating = 1,
    /// The device has skipped the given area, before or during operating at it, due to a SkipArea command, due an out of band command (e.g. from the vendor's application), due to a vendor specific reason, such as a time limit used by the device, or due the device ending operating unsuccessfully
    Skipped = 2,
    /// The device has completed operating at the given area
    Completed = 3,
}

impl OperationalStatus {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(OperationalStatus::Pending),
            1 => Some(OperationalStatus::Operating),
            2 => Some(OperationalStatus::Skipped),
            3 => Some(OperationalStatus::Completed),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum SelectAreasStatus {
    /// Attempting to operate in the areas identified by the entries of the NewAreas field is allowed and possible. The SelectedAreas attribute is set to the value of the NewAreas field.
    Success = 0,
    /// The value of at least one of the entries of the NewAreas field doesn't match any entries in the SupportedAreas attribute.
    Unsupportedarea = 1,
    /// The received request cannot be handled due to the current mode of the device.
    Invalidinmode = 2,
    /// The set of values is invalid. For example, areas on different floors, that a robot knows it can't reach on its own.
    Invalidset = 3,
}

impl SelectAreasStatus {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(SelectAreasStatus::Success),
            1 => Some(SelectAreasStatus::Unsupportedarea),
            2 => Some(SelectAreasStatus::Invalidinmode),
            3 => Some(SelectAreasStatus::Invalidset),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum SkipAreaStatus {
    /// Skipping the area is allowed and possible, or the device was operating at the last available area and has stopped.
    Success = 0,
    /// The SelectedAreas attribute is empty.
    Invalidarealist = 1,
    /// The received request cannot be handled due to the current mode of the device. For example, the CurrentArea attribute is null or the device is not operating.
    Invalidinmode = 2,
    /// The SkippedArea field doesn't match an entry in the SupportedAreas list.
    Invalidskippedarea = 3,
}

impl SkipAreaStatus {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(SkipAreaStatus::Success),
            1 => Some(SkipAreaStatus::Invalidarealist),
            2 => Some(SkipAreaStatus::Invalidinmode),
            3 => Some(SkipAreaStatus::Invalidskippedarea),
            _ => None,
        }
    }

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct AreaInfo {
    pub location_info: Option<LocationDescriptor>,
    pub landmark_info: Option<LandmarkInfo>,
}

#[derive(Debug, serde::Serialize)]
pub struct Area {
    pub area_id: Option<u32>,
    pub map_id: Option<u32>,
    pub area_info: Option<AreaInfo>,
}

#[derive(Debug, serde::Serialize)]
pub struct LandmarkInfo {
    pub landmark_tag: Option<u8>,
    pub relative_position_tag: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct Map {
    pub map_id: Option<u32>,
    pub name: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct Progress {
    pub area_id: Option<u32>,
    pub status: Option<OperationalStatus>,
    pub total_operational_time: Option<u32>,
    pub estimated_time: Option<u32>,
}

#[derive(Debug, serde::Serialize)]
pub struct LocationDescriptor {
    pub location_name: Option<String>,
    pub floor_number: Option<u16>,
    pub area_type: Option<u8>,
}

// Command encoders

/// Encode SelectAreas command (0x00)
pub fn encode_select_areas(new_areas: Vec<u32>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructAnon(new_areas.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt32(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SkipArea command (0x02)
pub fn encode_skip_area(skipped_area: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(skipped_area)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode SupportedAreas attribute (0x0000)
pub fn decode_supported_areas(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Area>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Area {
                area_id: item.get_int(&[0]).map(|v| v as u32),
                map_id: item.get_int(&[1]).map(|v| v as u32),
                area_info: {
                    if let Some(nested_tlv) = item.get(&[2]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 2, value: nested_tlv.clone() };
                            Some(AreaInfo {
                location_info: {
                    if let Some(nested_tlv) = nested_item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(LocationDescriptor {
                location_name: nested_item.get_string_owned(&[0]),
                floor_number: nested_item.get_int(&[1]).map(|v| v as u16),
                area_type: nested_item.get_int(&[2]).map(|v| v as u8),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                landmark_info: {
                    if let Some(nested_tlv) = nested_item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(LandmarkInfo {
                landmark_tag: nested_item.get_int(&[0]).map(|v| v as u8),
                relative_position_tag: nested_item.get_int(&[1]).map(|v| v as u8),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode SupportedMaps attribute (0x0001)
pub fn decode_supported_maps(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Map>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Map {
                map_id: item.get_int(&[0]).map(|v| v as u32),
                name: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

/// Decode SelectedAreas attribute (0x0002)
pub fn decode_selected_areas(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<u32>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                res.push(*i as u32);
            }
        }
    }
    Ok(res)
}

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

/// Decode EstimatedEndTime attribute (0x0004)
pub fn decode_estimated_end_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

/// Decode Progress attribute (0x0005)
pub fn decode_progress(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Progress>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Progress {
                area_id: item.get_int(&[0]).map(|v| v as u32),
                status: item.get_int(&[1]).and_then(|v| OperationalStatus::from_u8(v as u8)),
                total_operational_time: item.get_int(&[2]).map(|v| v as u32),
                estimated_time: item.get_int(&[3]).map(|v| v as u32),
            });
        }
    }
    Ok(res)
}


// 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 != 0x0150 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0150, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_supported_areas(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_supported_maps(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_selected_areas(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_current_area(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_estimated_end_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_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, "SupportedAreas"),
        (0x0001, "SupportedMaps"),
        (0x0002, "SelectedAreas"),
        (0x0003, "CurrentArea"),
        (0x0004, "EstimatedEndTime"),
        (0x0005, "Progress"),
    ]
}

// Command listing

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

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("SelectAreas"),
        0x02 => Some("SkipArea"),
        _ => 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: "new_areas", kind: crate::clusters::codec::FieldKind::List { entry_type: "uint32" }, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "skipped_area", kind: crate::clusters::codec::FieldKind::U32, 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 => Err(anyhow::anyhow!("command \"SelectAreas\" has complex args: use raw mode")),
        0x02 => {
        let skipped_area = crate::clusters::codec::json_util::get_u32(args, "skipped_area")?;
        encode_skip_area(skipped_area)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct SelectAreasResponse {
    pub status: Option<u8>,
    pub status_text: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct SkipAreaResponse {
    pub status: Option<u8>,
    pub status_text: Option<String>,
}

// Command response decoders

/// Decode SelectAreasResponse command response (01)
pub fn decode_select_areas_response(inp: &tlv::TlvItemValue) -> anyhow::Result<SelectAreasResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(SelectAreasResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                status_text: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode SkipAreaResponse command response (03)
pub fn decode_skip_area_response(inp: &tlv::TlvItemValue) -> anyhow::Result<SkipAreaResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(SkipAreaResponse {
                status: item.get_int(&[0]).map(|v| v as u8),
                status_text: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `SelectAreas` command on cluster `Service Area`.
pub async fn select_areas(conn: &crate::controller::Connection, endpoint: u16, new_areas: Vec<u32>) -> anyhow::Result<SelectAreasResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_CMD_ID_SELECTAREAS, &encode_select_areas(new_areas)?).await?;
    decode_select_areas_response(&tlv)
}

/// Invoke `SkipArea` command on cluster `Service Area`.
pub async fn skip_area(conn: &crate::controller::Connection, endpoint: u16, skipped_area: u32) -> anyhow::Result<SkipAreaResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_CMD_ID_SKIPAREA, &encode_skip_area(skipped_area)?).await?;
    decode_skip_area_response(&tlv)
}

/// Read `SupportedAreas` attribute from cluster `Service Area`.
pub async fn read_supported_areas(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Area>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_ATTR_ID_SUPPORTEDAREAS).await?;
    decode_supported_areas(&tlv)
}

/// Read `SupportedMaps` attribute from cluster `Service Area`.
pub async fn read_supported_maps(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Map>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_ATTR_ID_SUPPORTEDMAPS).await?;
    decode_supported_maps(&tlv)
}

/// Read `SelectedAreas` attribute from cluster `Service Area`.
pub async fn read_selected_areas(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_ATTR_ID_SELECTEDAREAS).await?;
    decode_selected_areas(&tlv)
}

/// Read `CurrentArea` attribute from cluster `Service Area`.
pub async fn read_current_area(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_ATTR_ID_CURRENTAREA).await?;
    decode_current_area(&tlv)
}

/// Read `EstimatedEndTime` attribute from cluster `Service Area`.
pub async fn read_estimated_end_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_ATTR_ID_ESTIMATEDENDTIME).await?;
    decode_estimated_end_time(&tlv)
}

/// Read `Progress` attribute from cluster `Service Area`.
pub async fn read_progress(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Progress>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_SERVICE_AREA, crate::clusters::defs::CLUSTER_SERVICE_AREA_ATTR_ID_PROGRESS).await?;
    decode_progress(&tlv)
}