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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//! Matter TLV encoders and decoders for Actions Cluster
//! Cluster ID: 0x0025
//!
//! This file is automatically generated from ActionsCluster.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 ActionError {
    /// Other reason not listed in the row(s) below
    Unknown = 0,
    /// The action was interrupted by another command or interaction
    Interrupted = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ActionState {
    /// The action is not active
    Inactive = 0,
    /// The action is active
    Active = 1,
    /// The action has been paused
    Paused = 2,
    /// The action has been disabled
    Disabled = 3,
}

impl ActionState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ActionState::Inactive),
            1 => Some(ActionState::Active),
            2 => Some(ActionState::Paused),
            3 => Some(ActionState::Disabled),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ActionType {
    /// Use this only when none of the other values applies
    Other = 0,
    /// Bring the endpoints into a certain state
    Scene = 1,
    /// A sequence of states with a certain time pattern
    Sequence = 2,
    /// Control an automation (e.g. motion sensor controlling lights)
    Automation = 3,
    /// Sequence that will run when something doesn't happen
    Exception = 4,
    /// Use the endpoints to send a message to user
    Notification = 5,
    /// Higher priority notification
    Alarm = 6,
}

impl ActionType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ActionType::Other),
            1 => Some(ActionType::Scene),
            2 => Some(ActionType::Sequence),
            3 => Some(ActionType::Automation),
            4 => Some(ActionType::Exception),
            5 => Some(ActionType::Notification),
            6 => Some(ActionType::Alarm),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum EndpointListType {
    /// Another group of endpoints
    Other = 0,
    /// User-configured group of endpoints where an endpoint can be in only one room
    Room = 1,
    /// User-configured group of endpoints where an endpoint can be in any number of zones
    Zone = 2,
}

impl EndpointListType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(EndpointListType::Other),
            1 => Some(EndpointListType::Room),
            2 => Some(EndpointListType::Zone),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// CommandBits bitmap type
pub type CommandBits = u16;

/// Constants for CommandBits
pub mod commandbits {
    /// Indicate support for InstantAction command
    pub const INSTANT_ACTION: u16 = 0x01;
    /// Indicate support for InstantActionWithTransition command
    pub const INSTANT_ACTION_WITH_TRANSITION: u16 = 0x02;
    /// Indicate support for StartAction command
    pub const START_ACTION: u16 = 0x04;
    /// Indicate support for StartActionWithDuration command
    pub const START_ACTION_WITH_DURATION: u16 = 0x08;
    /// Indicate support for StopAction command
    pub const STOP_ACTION: u16 = 0x10;
    /// Indicate support for PauseAction command
    pub const PAUSE_ACTION: u16 = 0x20;
    /// Indicate support for PauseActionWithDuration command
    pub const PAUSE_ACTION_WITH_DURATION: u16 = 0x40;
    /// Indicate support for ResumeAction command
    pub const RESUME_ACTION: u16 = 0x80;
    /// Indicate support for EnableAction command
    pub const ENABLE_ACTION: u16 = 0x100;
    /// Indicate support for EnableActionWithDuration command
    pub const ENABLE_ACTION_WITH_DURATION: u16 = 0x200;
    /// Indicate support for DisableAction command
    pub const DISABLE_ACTION: u16 = 0x400;
    /// Indicate support for DisableActionWithDuration command
    pub const DISABLE_ACTION_WITH_DURATION: u16 = 0x800;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct Action {
    pub action_id: Option<u16>,
    pub name: Option<String>,
    pub type_: Option<ActionType>,
    pub endpoint_list_id: Option<u16>,
    pub supported_commands: Option<u8>,
    pub state: Option<ActionState>,
}

#[derive(Debug, serde::Serialize)]
pub struct EndpointList {
    pub endpoint_list_id: Option<u16>,
    pub name: Option<String>,
    pub type_: Option<EndpointListType>,
    pub endpoints: Option<Vec<u16>>,
}

// Command encoders

/// Encode InstantAction command (0x00)
pub fn encode_instant_action(action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode InstantActionWithTransition command (0x01)
pub fn encode_instant_action_with_transition(action_id: u16, invoke_id: Option<u32>, transition_time: u16) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    tlv_fields.push((2, tlv::TlvItemValueEnc::UInt16(transition_time)).into());
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode StartAction command (0x02)
pub fn encode_start_action(action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode StartActionWithDuration command (0x03)
pub fn encode_start_action_with_duration(action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    tlv_fields.push((2, tlv::TlvItemValueEnc::UInt32(duration)).into());
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode StopAction command (0x04)
pub fn encode_stop_action(action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode PauseAction command (0x05)
pub fn encode_pause_action(action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode PauseActionWithDuration command (0x06)
pub fn encode_pause_action_with_duration(action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    tlv_fields.push((2, tlv::TlvItemValueEnc::UInt32(duration)).into());
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode ResumeAction command (0x07)
pub fn encode_resume_action(action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode EnableAction command (0x08)
pub fn encode_enable_action(action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode EnableActionWithDuration command (0x09)
pub fn encode_enable_action_with_duration(action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    tlv_fields.push((2, tlv::TlvItemValueEnc::UInt32(duration)).into());
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode DisableAction command (0x0A)
pub fn encode_disable_action(action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode DisableActionWithDuration command (0x0B)
pub fn encode_disable_action_with_duration(action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt16(action_id)).into());
    if let Some(x) = invoke_id { tlv_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
    tlv_fields.push((2, tlv::TlvItemValueEnc::UInt32(duration)).into());
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode ActionList attribute (0x0000)
pub fn decode_action_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Action>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Action {
                action_id: item.get_int(&[0]).map(|v| v as u16),
                name: item.get_string_owned(&[1]),
                type_: item.get_int(&[2]).and_then(|v| ActionType::from_u8(v as u8)),
                endpoint_list_id: item.get_int(&[3]).map(|v| v as u16),
                supported_commands: item.get_int(&[4]).map(|v| v as u8),
                state: item.get_int(&[5]).and_then(|v| ActionState::from_u8(v as u8)),
            });
        }
    }
    Ok(res)
}

/// Decode EndpointLists attribute (0x0001)
pub fn decode_endpoint_lists(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<EndpointList>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(EndpointList {
                endpoint_list_id: item.get_int(&[0]).map(|v| v as u16),
                name: item.get_string_owned(&[1]),
                type_: item.get_int(&[2]).and_then(|v| EndpointListType::from_u8(v as u8)),
                endpoints: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[3]) {
                        let items: Vec<u16> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Some(*v as u16) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode SetupURL attribute (0x0002)
pub fn decode_setup_url(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(v.clone())
    } else {
        Err(anyhow::anyhow!("Expected String"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_action_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_endpoint_lists(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_setup_url(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, "ActionList"),
        (0x0001, "EndpointLists"),
        (0x0002, "SetupURL"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "InstantAction"),
        (0x01, "InstantActionWithTransition"),
        (0x02, "StartAction"),
        (0x03, "StartActionWithDuration"),
        (0x04, "StopAction"),
        (0x05, "PauseAction"),
        (0x06, "PauseActionWithDuration"),
        (0x07, "ResumeAction"),
        (0x08, "EnableAction"),
        (0x09, "EnableActionWithDuration"),
        (0x0A, "DisableAction"),
        (0x0B, "DisableActionWithDuration"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("InstantAction"),
        0x01 => Some("InstantActionWithTransition"),
        0x02 => Some("StartAction"),
        0x03 => Some("StartActionWithDuration"),
        0x04 => Some("StopAction"),
        0x05 => Some("PauseAction"),
        0x06 => Some("PauseActionWithDuration"),
        0x07 => Some("ResumeAction"),
        0x08 => Some("EnableAction"),
        0x09 => Some("EnableActionWithDuration"),
        0x0A => Some("DisableAction"),
        0x0B => Some("DisableActionWithDuration"),
        _ => 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: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "transition_time", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x03 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "duration", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x06 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "duration", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x07 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x08 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x09 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "duration", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x0A => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
        ]),
        0x0B => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "action_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "invoke_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "duration", 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 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        encode_instant_action(action_id, invoke_id)
        }
        0x01 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        let transition_time = crate::clusters::codec::json_util::get_u16(args, "transition_time")?;
        encode_instant_action_with_transition(action_id, invoke_id, transition_time)
        }
        0x02 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        encode_start_action(action_id, invoke_id)
        }
        0x03 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        let duration = crate::clusters::codec::json_util::get_u32(args, "duration")?;
        encode_start_action_with_duration(action_id, invoke_id, duration)
        }
        0x04 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        encode_stop_action(action_id, invoke_id)
        }
        0x05 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        encode_pause_action(action_id, invoke_id)
        }
        0x06 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        let duration = crate::clusters::codec::json_util::get_u32(args, "duration")?;
        encode_pause_action_with_duration(action_id, invoke_id, duration)
        }
        0x07 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        encode_resume_action(action_id, invoke_id)
        }
        0x08 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        encode_enable_action(action_id, invoke_id)
        }
        0x09 => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        let duration = crate::clusters::codec::json_util::get_u32(args, "duration")?;
        encode_enable_action_with_duration(action_id, invoke_id, duration)
        }
        0x0A => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        encode_disable_action(action_id, invoke_id)
        }
        0x0B => {
        let action_id = crate::clusters::codec::json_util::get_u16(args, "action_id")?;
        let invoke_id = crate::clusters::codec::json_util::get_opt_u32(args, "invoke_id")?;
        let duration = crate::clusters::codec::json_util::get_u32(args, "duration")?;
        encode_disable_action_with_duration(action_id, invoke_id, duration)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `InstantAction` command on cluster `Actions`.
pub async fn instant_action(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_INSTANTACTION, &encode_instant_action(action_id, invoke_id)?).await?;
    Ok(())
}

/// Invoke `InstantActionWithTransition` command on cluster `Actions`.
pub async fn instant_action_with_transition(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>, transition_time: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_INSTANTACTIONWITHTRANSITION, &encode_instant_action_with_transition(action_id, invoke_id, transition_time)?).await?;
    Ok(())
}

/// Invoke `StartAction` command on cluster `Actions`.
pub async fn start_action(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_STARTACTION, &encode_start_action(action_id, invoke_id)?).await?;
    Ok(())
}

/// Invoke `StartActionWithDuration` command on cluster `Actions`.
pub async fn start_action_with_duration(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_STARTACTIONWITHDURATION, &encode_start_action_with_duration(action_id, invoke_id, duration)?).await?;
    Ok(())
}

/// Invoke `StopAction` command on cluster `Actions`.
pub async fn stop_action(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_STOPACTION, &encode_stop_action(action_id, invoke_id)?).await?;
    Ok(())
}

/// Invoke `PauseAction` command on cluster `Actions`.
pub async fn pause_action(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_PAUSEACTION, &encode_pause_action(action_id, invoke_id)?).await?;
    Ok(())
}

/// Invoke `PauseActionWithDuration` command on cluster `Actions`.
pub async fn pause_action_with_duration(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_PAUSEACTIONWITHDURATION, &encode_pause_action_with_duration(action_id, invoke_id, duration)?).await?;
    Ok(())
}

/// Invoke `ResumeAction` command on cluster `Actions`.
pub async fn resume_action(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_RESUMEACTION, &encode_resume_action(action_id, invoke_id)?).await?;
    Ok(())
}

/// Invoke `EnableAction` command on cluster `Actions`.
pub async fn enable_action(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_ENABLEACTION, &encode_enable_action(action_id, invoke_id)?).await?;
    Ok(())
}

/// Invoke `EnableActionWithDuration` command on cluster `Actions`.
pub async fn enable_action_with_duration(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_ENABLEACTIONWITHDURATION, &encode_enable_action_with_duration(action_id, invoke_id, duration)?).await?;
    Ok(())
}

/// Invoke `DisableAction` command on cluster `Actions`.
pub async fn disable_action(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_DISABLEACTION, &encode_disable_action(action_id, invoke_id)?).await?;
    Ok(())
}

/// Invoke `DisableActionWithDuration` command on cluster `Actions`.
pub async fn disable_action_with_duration(conn: &crate::controller::Connection, endpoint: u16, action_id: u16, invoke_id: Option<u32>, duration: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_CMD_ID_DISABLEACTIONWITHDURATION, &encode_disable_action_with_duration(action_id, invoke_id, duration)?).await?;
    Ok(())
}

/// Read `ActionList` attribute from cluster `Actions`.
pub async fn read_action_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Action>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_ATTR_ID_ACTIONLIST).await?;
    decode_action_list(&tlv)
}

/// Read `EndpointLists` attribute from cluster `Actions`.
pub async fn read_endpoint_lists(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<EndpointList>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_ATTR_ID_ENDPOINTLISTS).await?;
    decode_endpoint_lists(&tlv)
}

/// Read `SetupURL` attribute from cluster `Actions`.
pub async fn read_setup_url(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<String> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ACTIONS, crate::clusters::defs::CLUSTER_ACTIONS_ATTR_ID_SETUPURL).await?;
    decode_setup_url(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct StateChangedEvent {
    pub action_id: Option<u16>,
    pub invoke_id: Option<u32>,
    pub new_state: Option<ActionState>,
}

#[derive(Debug, serde::Serialize)]
pub struct ActionFailedEvent {
    pub action_id: Option<u16>,
    pub invoke_id: Option<u32>,
    pub new_state: Option<ActionState>,
    pub error: Option<ActionError>,
}

// Event decoders

/// Decode StateChanged event (0x00, priority: info)
pub fn decode_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<StateChangedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(StateChangedEvent {
                                action_id: item.get_int(&[0]).map(|v| v as u16),
                                invoke_id: item.get_int(&[1]).map(|v| v as u32),
                                new_state: item.get_int(&[2]).and_then(|v| ActionState::from_u8(v as u8)),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ActionFailed event (0x01, priority: info)
pub fn decode_action_failed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ActionFailedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ActionFailedEvent {
                                action_id: item.get_int(&[0]).map(|v| v as u16),
                                invoke_id: item.get_int(&[1]).map(|v| v as u32),
                                new_state: item.get_int(&[2]).and_then(|v| ActionState::from_u8(v as u8)),
                                error: item.get_int(&[3]).and_then(|v| ActionError::from_u8(v as u8)),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}