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
//! Matter TLV encoders and decoders for Fan Control Cluster
//! Cluster ID: 0x0202
//!
//! This file is automatically generated from FanControl.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 AirflowDirection {
    /// Airflow is in the forward direction
    Forward = 0,
    /// Airflow is in the reverse direction
    Reverse = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum FanMode {
    /// Fan is off
    Off = 0,
    /// Fan using low speed
    Low = 1,
    /// Fan using medium speed
    Medium = 2,
    /// Fan using high speed
    High = 3,
    On = 4,
    /// Fan is using auto mode
    Auto = 5,
    /// Fan is using smart mode
    Smart = 6,
}

impl FanMode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(FanMode::Off),
            1 => Some(FanMode::Low),
            2 => Some(FanMode::Medium),
            3 => Some(FanMode::High),
            4 => Some(FanMode::On),
            5 => Some(FanMode::Auto),
            6 => Some(FanMode::Smart),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum FanModeSequence {
    /// Fan is capable of off, low, medium and high modes
    Offlowmedhigh = 0,
    /// Fan is capable of off, low and high modes
    Offlowhigh = 1,
    /// Fan is capable of off, low, medium, high and auto modes
    Offlowmedhighauto = 2,
    /// Fan is capable of off, low, high and auto modes
    Offlowhighauto = 3,
    /// Fan is capable of off, high and auto modes
    Offhighauto = 4,
    /// Fan is capable of off and high modes
    Offhigh = 5,
}

impl FanModeSequence {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(FanModeSequence::Offlowmedhigh),
            1 => Some(FanModeSequence::Offlowhigh),
            2 => Some(FanModeSequence::Offlowmedhighauto),
            3 => Some(FanModeSequence::Offlowhighauto),
            4 => Some(FanModeSequence::Offhighauto),
            5 => Some(FanModeSequence::Offhigh),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StepDirection {
    /// Step moves in increasing direction
    Increase = 0,
    /// Step moves in decreasing direction
    Decrease = 1,
}

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

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

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

// Bitmap definitions

/// Rock bitmap type
pub type Rock = u8;

/// Constants for Rock
pub mod rock {
    /// Indicate rock left to right
    pub const ROCK_LEFT_RIGHT: u8 = 0x01;
    /// Indicate rock up and down
    pub const ROCK_UP_DOWN: u8 = 0x02;
    /// Indicate rock around
    pub const ROCK_ROUND: u8 = 0x04;
}

/// Wind bitmap type
pub type Wind = u8;

/// Constants for Wind
pub mod wind {
    /// Indicate sleep wind
    pub const SLEEP_WIND: u8 = 0x01;
    /// Indicate natural wind
    pub const NATURAL_WIND: u8 = 0x02;
}

// Command encoders

/// Encode Step command (0x00)
pub fn encode_step(direction: StepDirection, wrap: bool, lowest_off: bool) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(direction.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::Bool(wrap)).into(),
        (2, tlv::TlvItemValueEnc::Bool(lowest_off)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

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

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

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

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

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

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

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

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

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

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


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

    match attribute_id {
        0x0000 => {
            match decode_fan_mode(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_fan_mode_sequence(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_percent_setting(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_percent_current(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_speed_max(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_speed_setting(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_speed_current(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_rock_support(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_rock_setting(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_wind_support(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_wind_setting(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_airflow_direction(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, "FanMode"),
        (0x0001, "FanModeSequence"),
        (0x0002, "PercentSetting"),
        (0x0003, "PercentCurrent"),
        (0x0004, "SpeedMax"),
        (0x0005, "SpeedSetting"),
        (0x0006, "SpeedCurrent"),
        (0x0007, "RockSupport"),
        (0x0008, "RockSetting"),
        (0x0009, "WindSupport"),
        (0x000A, "WindSetting"),
        (0x000B, "AirflowDirection"),
    ]
}