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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! Matter TLV encoders and decoders for Window Covering Cluster
//! Cluster ID: 0x0102
//!
//! This file is automatically generated from WindowCovering.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 EndProductType {
    /// Simple Roller Shade
    Rollershade = 0,
    /// Roman Shade
    Romanshade = 1,
    /// Balloon Shade
    Balloonshade = 2,
    /// Woven Wood
    Wovenwood = 3,
    /// Pleated Shade
    Pleatedshade = 4,
    /// Cellular Shade
    Cellularshade = 5,
    /// Layered Shade
    Layeredshade = 6,
    /// Layered Shade 2D
    Layeredshade2d = 7,
    /// Sheer Shade
    Sheershade = 8,
    /// Tilt Only Interior Blind
    Tiltonlyinteriorblind = 9,
    /// Interior Blind
    Interiorblind = 10,
    /// Vertical Blind, Strip Curtain
    Verticalblindstripcurtain = 11,
    /// Interior Venetian Blind
    Interiorvenetianblind = 12,
    /// Exterior Venetian Blind
    Exteriorvenetianblind = 13,
    /// Lateral Left Curtain
    Lateralleftcurtain = 14,
    /// Lateral Right Curtain
    Lateralrightcurtain = 15,
    /// Central Curtain
    Centralcurtain = 16,
    /// Roller Shutter
    Rollershutter = 17,
    /// Exterior Vertical Screen
    Exteriorverticalscreen = 18,
    /// Awning Terrace (Patio)
    Awningterracepatio = 19,
    /// Awning Vertical Screen
    Awningverticalscreen = 20,
    /// Tilt Only Pergola
    Tiltonlypergola = 21,
    /// Swinging Shutter
    Swingingshutter = 22,
    /// Sliding Shutter
    Slidingshutter = 23,
    /// Unknown
    Unknown = 255,
}

impl EndProductType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(EndProductType::Rollershade),
            1 => Some(EndProductType::Romanshade),
            2 => Some(EndProductType::Balloonshade),
            3 => Some(EndProductType::Wovenwood),
            4 => Some(EndProductType::Pleatedshade),
            5 => Some(EndProductType::Cellularshade),
            6 => Some(EndProductType::Layeredshade),
            7 => Some(EndProductType::Layeredshade2d),
            8 => Some(EndProductType::Sheershade),
            9 => Some(EndProductType::Tiltonlyinteriorblind),
            10 => Some(EndProductType::Interiorblind),
            11 => Some(EndProductType::Verticalblindstripcurtain),
            12 => Some(EndProductType::Interiorvenetianblind),
            13 => Some(EndProductType::Exteriorvenetianblind),
            14 => Some(EndProductType::Lateralleftcurtain),
            15 => Some(EndProductType::Lateralrightcurtain),
            16 => Some(EndProductType::Centralcurtain),
            17 => Some(EndProductType::Rollershutter),
            18 => Some(EndProductType::Exteriorverticalscreen),
            19 => Some(EndProductType::Awningterracepatio),
            20 => Some(EndProductType::Awningverticalscreen),
            21 => Some(EndProductType::Tiltonlypergola),
            22 => Some(EndProductType::Swingingshutter),
            23 => Some(EndProductType::Slidingshutter),
            255 => Some(EndProductType::Unknown),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Type {
    /// RollerShade
    Rollershade = 0,
    /// RollerShade - 2 Motor
    Rollershade2motor = 1,
    /// RollerShade - Exterior
    Rollershadeexterior = 2,
    /// RollerShade - Exterior - 2 Motor
    Rollershadeexterior2motor = 3,
    /// Drapery (curtain)
    Drapery = 4,
    /// Awning
    Awning = 5,
    /// Shutter
    Shutter = 6,
    /// Tilt Blind - Tilt Only
    Tiltblindtiltonly = 7,
    /// Tilt Blind - Lift & Tilt
    Tiltblindliftandtilt = 8,
    /// Projector Screen
    Projectorscreen = 9,
    /// Unknown
    Unknown = 255,
}

impl Type {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Type::Rollershade),
            1 => Some(Type::Rollershade2motor),
            2 => Some(Type::Rollershadeexterior),
            3 => Some(Type::Rollershadeexterior2motor),
            4 => Some(Type::Drapery),
            5 => Some(Type::Awning),
            6 => Some(Type::Shutter),
            7 => Some(Type::Tiltblindtiltonly),
            8 => Some(Type::Tiltblindliftandtilt),
            9 => Some(Type::Projectorscreen),
            255 => Some(Type::Unknown),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// ConfigStatus bitmap type
pub type ConfigStatus = u8;

/// Constants for ConfigStatus
pub mod configstatus {
    /// Device is operational.
    pub const OPERATIONAL: u8 = 0x01;
    pub const ONLINE_RESERVED: u8 = 0x02;
    /// The lift movement is reversed.
    pub const LIFT_MOVEMENT_REVERSED: u8 = 0x04;
    /// Supports the PositionAwareLift feature (PA_LF).
    pub const LIFT_POSITION_AWARE: u8 = 0x08;
    /// Supports the PositionAwareTilt feature (PA_TL).
    pub const TILT_POSITION_AWARE: u8 = 0x10;
    /// Uses an encoder for lift.
    pub const LIFT_ENCODER_CONTROLLED: u8 = 0x20;
    /// Uses an encoder for tilt.
    pub const TILT_ENCODER_CONTROLLED: u8 = 0x40;
}

/// Mode bitmap type
pub type Mode = u8;

/// Constants for Mode
pub mod mode {
    /// Reverse the lift direction.
    pub const MOTOR_DIRECTION_REVERSED: u8 = 0x01;
    /// Perform a calibration.
    pub const CALIBRATION_MODE: u8 = 0x02;
    /// Freeze all motions for maintenance.
    pub const MAINTENANCE_MODE: u8 = 0x04;
    /// Control the LEDs feedback.
    pub const LED_FEEDBACK: u8 = 0x08;
}

/// OperationalStatus bitmap type
pub type OperationalStatus = u8;

/// SafetyStatus bitmap type
pub type SafetyStatus = u16;

/// Constants for SafetyStatus
pub mod safetystatus {
    /// Movement commands are ignored (locked out). e.g. not granted authorization, outside some time/date range.
    pub const REMOTE_LOCKOUT: u16 = 0x01;
    /// Tampering detected on sensors or any other safety equipment. Ex: a device has been forcedly moved without its actuator(s).
    pub const TAMPER_DETECTION: u16 = 0x02;
    /// Communication failure to sensors or other safety equipment.
    pub const FAILED_COMMUNICATION: u16 = 0x04;
    /// Device has failed to reach the desired position. e.g. with position aware device, time expired before TargetPosition is reached.
    pub const POSITION_FAILURE: u16 = 0x08;
    /// Motor(s) and/or electric circuit thermal protection activated.
    pub const THERMAL_PROTECTION: u16 = 0x10;
    /// An obstacle is preventing actuator movement.
    pub const OBSTACLE_DETECTED: u16 = 0x20;
    /// Device has power related issue or limitation e.g. device is running w/ the help of a backup battery or power might not be fully available at the moment.
    pub const POWER: u16 = 0x40;
    /// Local safety sensor (not a direct obstacle) is preventing movements (e.g. Safety EU Standard EN60335).
    pub const STOP_INPUT: u16 = 0x80;
    /// Mechanical problem related to the motor(s) detected.
    pub const MOTOR_JAMMED: u16 = 0x100;
    /// PCB, fuse and other electrics problems.
    pub const HARDWARE_FAILURE: u16 = 0x200;
    /// Actuator is manually operated and is preventing actuator movement (e.g. actuator is disengaged/decoupled).
    pub const MANUAL_OPERATION: u16 = 0x400;
    /// Protection is activated.
    pub const PROTECTION: u16 = 0x800;
}

// Command encoders

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

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

// Attribute decoders

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

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

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

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

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

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

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

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

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

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

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

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

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

/// Decode SafetyStatus attribute (0x001A)
pub fn decode_safety_status(inp: &tlv::TlvItemValue) -> anyhow::Result<SafetyStatus> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u16)
    } 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 != 0x0102 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0102, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_type_(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_number_of_actuations_lift(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_number_of_actuations_tilt(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_config_status(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_current_position_lift_percentage(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_current_position_tilt_percentage(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_operational_status(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_target_position_lift_percent100ths(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000C => {
            match decode_target_position_tilt_percent100ths(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000D => {
            match decode_end_product_type(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000E => {
            match decode_current_position_lift_percent100ths(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000F => {
            match decode_current_position_tilt_percent100ths(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0017 => {
            match decode_mode(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x001A => {
            match decode_safety_status(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, "Type"),
        (0x0005, "NumberOfActuationsLift"),
        (0x0006, "NumberOfActuationsTilt"),
        (0x0007, "ConfigStatus"),
        (0x0008, "CurrentPositionLiftPercentage"),
        (0x0009, "CurrentPositionTiltPercentage"),
        (0x000A, "OperationalStatus"),
        (0x000B, "TargetPositionLiftPercent100ths"),
        (0x000C, "TargetPositionTiltPercent100ths"),
        (0x000D, "EndProductType"),
        (0x000E, "CurrentPositionLiftPercent100ths"),
        (0x000F, "CurrentPositionTiltPercent100ths"),
        (0x0017, "Mode"),
        (0x001A, "SafetyStatus"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "UpOrOpen"),
        (0x01, "DownOrClose"),
        (0x02, "StopMotion"),
        (0x05, "GoToLiftPercentage"),
        (0x08, "GoToTiltPercentage"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("UpOrOpen"),
        0x01 => Some("DownOrClose"),
        0x02 => Some("StopMotion"),
        0x05 => Some("GoToLiftPercentage"),
        0x08 => Some("GoToTiltPercentage"),
        _ => 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![]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "lift_percent100ths_value", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x08 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "tilt_percent100ths_value", 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 => Ok(vec![]),
        0x01 => Ok(vec![]),
        0x02 => Ok(vec![]),
        0x05 => {
        let lift_percent100ths_value = crate::clusters::codec::json_util::get_u16(args, "lift_percent100ths_value")?;
        encode_go_to_lift_percentage(lift_percent100ths_value)
        }
        0x08 => {
        let tilt_percent100ths_value = crate::clusters::codec::json_util::get_u16(args, "tilt_percent100ths_value")?;
        encode_go_to_tilt_percentage(tilt_percent100ths_value)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `UpOrOpen` command on cluster `Window Covering`.
pub async fn up_or_open(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_CMD_ID_UPOROPEN, &[]).await?;
    Ok(())
}

/// Invoke `DownOrClose` command on cluster `Window Covering`.
pub async fn down_or_close(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_CMD_ID_DOWNORCLOSE, &[]).await?;
    Ok(())
}

/// Invoke `StopMotion` command on cluster `Window Covering`.
pub async fn stop_motion(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_CMD_ID_STOPMOTION, &[]).await?;
    Ok(())
}

/// Invoke `GoToLiftPercentage` command on cluster `Window Covering`.
pub async fn go_to_lift_percentage(conn: &crate::controller::Connection, endpoint: u16, lift_percent100ths_value: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_CMD_ID_GOTOLIFTPERCENTAGE, &encode_go_to_lift_percentage(lift_percent100ths_value)?).await?;
    Ok(())
}

/// Invoke `GoToTiltPercentage` command on cluster `Window Covering`.
pub async fn go_to_tilt_percentage(conn: &crate::controller::Connection, endpoint: u16, tilt_percent100ths_value: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_CMD_ID_GOTOTILTPERCENTAGE, &encode_go_to_tilt_percentage(tilt_percent100ths_value)?).await?;
    Ok(())
}

/// Read `Type` attribute from cluster `Window Covering`.
pub async fn read_type_(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Type> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_TYPE).await?;
    decode_type_(&tlv)
}

/// Read `NumberOfActuationsLift` attribute from cluster `Window Covering`.
pub async fn read_number_of_actuations_lift(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_NUMBEROFACTUATIONSLIFT).await?;
    decode_number_of_actuations_lift(&tlv)
}

/// Read `NumberOfActuationsTilt` attribute from cluster `Window Covering`.
pub async fn read_number_of_actuations_tilt(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_NUMBEROFACTUATIONSTILT).await?;
    decode_number_of_actuations_tilt(&tlv)
}

/// Read `ConfigStatus` attribute from cluster `Window Covering`.
pub async fn read_config_status(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ConfigStatus> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_CONFIGSTATUS).await?;
    decode_config_status(&tlv)
}

/// Read `CurrentPositionLiftPercentage` attribute from cluster `Window Covering`.
pub async fn read_current_position_lift_percentage(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_CURRENTPOSITIONLIFTPERCENTAGE).await?;
    decode_current_position_lift_percentage(&tlv)
}

/// Read `CurrentPositionTiltPercentage` attribute from cluster `Window Covering`.
pub async fn read_current_position_tilt_percentage(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_CURRENTPOSITIONTILTPERCENTAGE).await?;
    decode_current_position_tilt_percentage(&tlv)
}

/// Read `OperationalStatus` attribute from cluster `Window Covering`.
pub async fn read_operational_status(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<OperationalStatus> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_OPERATIONALSTATUS).await?;
    decode_operational_status(&tlv)
}

/// Read `TargetPositionLiftPercent100ths` attribute from cluster `Window Covering`.
pub async fn read_target_position_lift_percent100ths(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_TARGETPOSITIONLIFTPERCENT100THS).await?;
    decode_target_position_lift_percent100ths(&tlv)
}

/// Read `TargetPositionTiltPercent100ths` attribute from cluster `Window Covering`.
pub async fn read_target_position_tilt_percent100ths(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_TARGETPOSITIONTILTPERCENT100THS).await?;
    decode_target_position_tilt_percent100ths(&tlv)
}

/// Read `EndProductType` attribute from cluster `Window Covering`.
pub async fn read_end_product_type(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<EndProductType> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_ENDPRODUCTTYPE).await?;
    decode_end_product_type(&tlv)
}

/// Read `CurrentPositionLiftPercent100ths` attribute from cluster `Window Covering`.
pub async fn read_current_position_lift_percent100ths(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_CURRENTPOSITIONLIFTPERCENT100THS).await?;
    decode_current_position_lift_percent100ths(&tlv)
}

/// Read `CurrentPositionTiltPercent100ths` attribute from cluster `Window Covering`.
pub async fn read_current_position_tilt_percent100ths(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_CURRENTPOSITIONTILTPERCENT100THS).await?;
    decode_current_position_tilt_percent100ths(&tlv)
}

/// Read `Mode` attribute from cluster `Window Covering`.
pub async fn read_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Mode> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_MODE).await?;
    decode_mode(&tlv)
}

/// Read `SafetyStatus` attribute from cluster `Window Covering`.
pub async fn read_safety_status(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<SafetyStatus> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WINDOW_COVERING, crate::clusters::defs::CLUSTER_WINDOW_COVERING_ATTR_ID_SAFETYSTATUS).await?;
    decode_safety_status(&tlv)
}