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
//! Matter TLV encoders and decoders for On/Off Cluster
//! Cluster ID: 0x0006
//!
//! This file is automatically generated from OnOff.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 DelayedAllOffEffectVariant {
    /// Fade to off in 0.8 seconds
    Delayedofffastfade = 0,
    /// No fade
    Nofade = 1,
    /// 50% dim down in 0.8 seconds then fade to off in 12 seconds
    Delayedoffslowfade = 2,
}

impl DelayedAllOffEffectVariant {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(DelayedAllOffEffectVariant::Delayedofffastfade),
            1 => Some(DelayedAllOffEffectVariant::Nofade),
            2 => Some(DelayedAllOffEffectVariant::Delayedoffslowfade),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum DyingLightEffectVariant {
    /// 20% dim up in 0.5s then fade to off in 1 second
    Dyinglightfadeoff = 0,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum EffectIdentifier {
    /// Delayed All Off
    Delayedalloff = 0,
    /// Dying Light
    Dyinglight = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StartUpOnOff {
    /// Set the OnOff attribute to FALSE
    Off = 0,
    /// Set the OnOff attribute to TRUE
    On = 1,
    /// If the previous value of the OnOff attribute is equal to FALSE, set the OnOff attribute to TRUE. If the previous value of the OnOff attribute is equal to TRUE, set the OnOff attribute to FALSE (toggle).
    Toggle = 2,
}

impl StartUpOnOff {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(StartUpOnOff::Off),
            1 => Some(StartUpOnOff::On),
            2 => Some(StartUpOnOff::Toggle),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// OnOffControl bitmap type
pub type OnOffControl = u8;

/// Constants for OnOffControl
pub mod onoffcontrol {
    /// Indicates a command is only accepted when in On state.
    pub const ACCEPT_ONLY_WHEN_ON: u8 = 0x01;
}

// Command encoders

/// Encode OffWithEffect command (0x40)
pub fn encode_off_with_effect(effect_identifier: EffectIdentifier, effect_variant: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(effect_identifier.to_u8())).into(),
        (1, tlv::TlvItemValueEnc::UInt8(effect_variant)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode OnWithTimedOff command (0x42)
pub fn encode_on_with_timed_off(on_off_control: OnOffControl, on_time: u16, off_wait_time: u16) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(on_off_control)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(on_time)).into(),
        (2, tlv::TlvItemValueEnc::UInt16(off_wait_time)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

/// Decode OnTime attribute (0x4001)
pub fn decode_on_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 OffWaitTime attribute (0x4002)
pub fn decode_off_wait_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 StartUpOnOff attribute (0x4003)
pub fn decode_start_up_on_off(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<StartUpOnOff>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(StartUpOnOff::from_u8(*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 != 0x0006 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0006, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_on_off(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x4000 => {
            match decode_global_scene_control(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x4001 => {
            match decode_on_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x4002 => {
            match decode_off_wait_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x4003 => {
            match decode_start_up_on_off(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, "OnOff"),
        (0x4000, "GlobalSceneControl"),
        (0x4001, "OnTime"),
        (0x4002, "OffWaitTime"),
        (0x4003, "StartUpOnOff"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "Off"),
        (0x01, "On"),
        (0x02, "Toggle"),
        (0x40, "OffWithEffect"),
        (0x41, "OnWithRecallGlobalScene"),
        (0x42, "OnWithTimedOff"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("Off"),
        0x01 => Some("On"),
        0x02 => Some("Toggle"),
        0x40 => Some("OffWithEffect"),
        0x41 => Some("OnWithRecallGlobalScene"),
        0x42 => Some("OnWithTimedOff"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![]),
        0x01 => Some(vec![]),
        0x02 => Some(vec![]),
        0x40 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "effect_identifier", kind: crate::clusters::codec::FieldKind::Enum { name: "EffectIdentifier", variants: &[(0, "Delayedalloff"), (1, "Dyinglight")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "effect_variant", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
        ]),
        0x41 => Some(vec![]),
        0x42 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "on_off_control", kind: crate::clusters::codec::FieldKind::Bitmap { name: "OnOffControl", bits: &[(1, "ACCEPT_ONLY_WHEN_ON")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "on_time", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "off_wait_time", 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 => Ok(vec![]),
        0x01 => Ok(vec![]),
        0x02 => Ok(vec![]),
        0x40 => {
        let effect_identifier = {
            let n = crate::clusters::codec::json_util::get_u64(args, "effect_identifier")?;
            EffectIdentifier::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid EffectIdentifier: {}", n))?
        };
        let effect_variant = crate::clusters::codec::json_util::get_u8(args, "effect_variant")?;
        encode_off_with_effect(effect_identifier, effect_variant)
        }
        0x41 => Ok(vec![]),
        0x42 => {
        let on_off_control = crate::clusters::codec::json_util::get_u8(args, "on_off_control")?;
        let on_time = crate::clusters::codec::json_util::get_u16(args, "on_time")?;
        let off_wait_time = crate::clusters::codec::json_util::get_u16(args, "off_wait_time")?;
        encode_on_with_timed_off(on_off_control, on_time, off_wait_time)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `Off` command on cluster `On/Off`.
pub async fn off(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_OFF, &[]).await?;
    Ok(())
}

/// Invoke `On` command on cluster `On/Off`.
pub async fn on(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_ON, &[]).await?;
    Ok(())
}

/// Invoke `Toggle` command on cluster `On/Off`.
pub async fn toggle(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_TOGGLE, &[]).await?;
    Ok(())
}

/// Invoke `OffWithEffect` command on cluster `On/Off`.
pub async fn off_with_effect(conn: &crate::controller::Connection, endpoint: u16, effect_identifier: EffectIdentifier, effect_variant: u8) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_OFFWITHEFFECT, &encode_off_with_effect(effect_identifier, effect_variant)?).await?;
    Ok(())
}

/// Invoke `OnWithRecallGlobalScene` command on cluster `On/Off`.
pub async fn on_with_recall_global_scene(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_ONWITHRECALLGLOBALSCENE, &[]).await?;
    Ok(())
}

/// Invoke `OnWithTimedOff` command on cluster `On/Off`.
pub async fn on_with_timed_off(conn: &crate::controller::Connection, endpoint: u16, on_off_control: OnOffControl, on_time: u16, off_wait_time: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_ONWITHTIMEDOFF, &encode_on_with_timed_off(on_off_control, on_time, off_wait_time)?).await?;
    Ok(())
}

/// Read `OnOff` attribute from cluster `On/Off`.
pub async fn read_on_off(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_ONOFF).await?;
    decode_on_off(&tlv)
}

/// Read `GlobalSceneControl` attribute from cluster `On/Off`.
pub async fn read_global_scene_control(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_GLOBALSCENECONTROL).await?;
    decode_global_scene_control(&tlv)
}

/// Read `OnTime` attribute from cluster `On/Off`.
pub async fn read_on_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_ONTIME).await?;
    decode_on_time(&tlv)
}

/// Read `OffWaitTime` attribute from cluster `On/Off`.
pub async fn read_off_wait_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_OFFWAITTIME).await?;
    decode_off_wait_time(&tlv)
}

/// Read `StartUpOnOff` attribute from cluster `On/Off`.
pub async fn read_start_up_on_off(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<StartUpOnOff>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_STARTUPONOFF).await?;
    decode_start_up_on_off(&tlv)
}