matc 0.1.2

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
//! Matter TLV encoders and decoders for Level Control Cluster
//! Cluster ID: 0x0008
//!
//! This file is automatically generated from LevelControl.xml

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


// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum MoveMode {
    /// Increase the level
    Up = 0,
    /// Decrease the level
    Down = 1,
}

impl MoveMode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(MoveMode::Up),
            1 => Some(MoveMode::Down),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StepMode {
    /// Step upwards
    Up = 0,
    /// Step downwards
    Down = 1,
}

impl StepMode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(StepMode::Up),
            1 => Some(StepMode::Down),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// Options bitmap type
pub type Options = u8;

/// Constants for Options
pub mod options {
    /// Dependency on On/Off cluster
    pub const EXECUTE_IF_OFF: u8 = 0x01;
    /// Dependency on Color Control cluster
    pub const COUPLE_COLOR_TEMP_TO_LEVEL: u8 = 0x02;
}

// Command encoders

/// Encode MoveToLevel command (0x00)
pub fn encode_move_to_level(level: u8, transition_time: Option<u16>, options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(level)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(transition_time.unwrap_or(0))).into(),
        (2, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (3, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode Move command (0x01)
pub fn encode_move_(move_mode: MoveMode, rate: Option<u8>, options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(move_mode.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::UInt8(rate.unwrap_or(0))).into(),
        (2, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (3, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode Step command (0x02)
pub fn encode_step(step_mode: StepMode, step_size: u8, transition_time: Option<u16>, options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(step_mode.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::UInt8(step_size)).into(),
        (2, tlv::TlvItemValueEnc::UInt16(transition_time.unwrap_or(0))).into(),
        (3, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (4, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode Stop command (0x03)
pub fn encode_stop(options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode MoveToLevelWithOnOff command (0x04)
pub fn encode_move_to_level_with_on_off(level: u8, transition_time: Option<u16>, options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(level)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(transition_time.unwrap_or(0))).into(),
        (2, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (3, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode MoveWithOnOff command (0x05)
pub fn encode_move_with_on_off(move_mode: MoveMode, rate: Option<u8>, options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(move_mode.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::UInt8(rate.unwrap_or(0))).into(),
        (2, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (3, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode StepWithOnOff command (0x06)
pub fn encode_step_with_on_off(step_mode: StepMode, step_size: u8, transition_time: Option<u16>, options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(step_mode.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::UInt8(step_size)).into(),
        (2, tlv::TlvItemValueEnc::UInt16(transition_time.unwrap_or(0))).into(),
        (3, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (4, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode StopWithOnOff command (0x07)
pub fn encode_stop_with_on_off(options_mask: Options, options_override: Options) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(options_mask)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(options_override)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode MoveToClosestFrequency command (0x08)
pub fn encode_move_to_closest_frequency(frequency: u16) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt16(frequency)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

/// Decode RemainingTime attribute (0x0001)
pub fn decode_remaining_time(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

/// Decode MinLevel attribute (0x0002)
pub fn decode_min_level(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}

/// Decode MaxLevel attribute (0x0003)
pub fn decode_max_level(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}

/// Decode CurrentFrequency attribute (0x0004)
pub fn decode_current_frequency(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

/// Decode MinFrequency attribute (0x0005)
pub fn decode_min_frequency(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

/// Decode MaxFrequency attribute (0x0006)
pub fn decode_max_frequency(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

/// Decode Options attribute (0x000F)
pub fn decode_options(inp: &tlv::TlvItemValue) -> anyhow::Result<Options> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}

/// Decode OnOffTransitionTime attribute (0x0010)
pub fn decode_on_off_transition_time(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } else {
        Err(anyhow::anyhow!("Expected UInt16"))
    }
}

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

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

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

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

/// Decode StartUpCurrentLevel attribute (0x4000)
pub fn decode_start_up_current_level(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 != 0x0008 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0008, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_current_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_remaining_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_min_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_max_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_current_frequency(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_min_frequency(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_max_frequency(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000F => {
            match decode_options(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0010 => {
            match decode_on_off_transition_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0011 => {
            match decode_on_level(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0012 => {
            match decode_on_transition_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0013 => {
            match decode_off_transition_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0014 => {
            match decode_default_move_rate(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x4000 => {
            match decode_start_up_current_level(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, "CurrentLevel"),
        (0x0001, "RemainingTime"),
        (0x0002, "MinLevel"),
        (0x0003, "MaxLevel"),
        (0x0004, "CurrentFrequency"),
        (0x0005, "MinFrequency"),
        (0x0006, "MaxFrequency"),
        (0x000F, "Options"),
        (0x0010, "OnOffTransitionTime"),
        (0x0011, "OnLevel"),
        (0x0012, "OnTransitionTime"),
        (0x0013, "OffTransitionTime"),
        (0x0014, "DefaultMoveRate"),
        (0x4000, "StartUpCurrentLevel"),
    ]
}