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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! Matter TLV encoders and decoders for Content Control Cluster
//! Cluster ID: 0x050F
//!
//! This file is automatically generated from ContentControl.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 StatusCode {
    /// Provided PIN Code does not match the current PIN code.
    Invalidpincode = 2,
    /// Provided Rating is out of scope of the corresponding Rating list.
    Invalidrating = 3,
    /// Provided Channel(s) is invalid.
    Invalidchannel = 4,
    /// Provided Channel(s) already exists.
    Channelalreadyexist = 5,
    /// Provided Channel(s) doesn't exist in BlockChannelList attribute.
    Channelnotexist = 6,
    /// Provided Application(s) is not identified.
    Unidentifiableapplication = 7,
    /// Provided Application(s) already exists.
    Applicationalreadyexist = 8,
    /// Provided Application(s) doesn't exist in BlockApplicationList attribute.
    Applicationnotexist = 9,
    /// Provided time Window already exists in BlockContentTimeWindow attribute.
    Timewindowalreadyexist = 10,
    /// Provided time window doesn't exist in BlockContentTimeWindow attribute.
    Timewindownotexist = 11,
}

impl StatusCode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            2 => Some(StatusCode::Invalidpincode),
            3 => Some(StatusCode::Invalidrating),
            4 => Some(StatusCode::Invalidchannel),
            5 => Some(StatusCode::Channelalreadyexist),
            6 => Some(StatusCode::Channelnotexist),
            7 => Some(StatusCode::Unidentifiableapplication),
            8 => Some(StatusCode::Applicationalreadyexist),
            9 => Some(StatusCode::Applicationnotexist),
            10 => Some(StatusCode::Timewindowalreadyexist),
            11 => Some(StatusCode::Timewindownotexist),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// DayOfWeek bitmap type
pub type DayOfWeek = u8;

/// Constants for DayOfWeek
pub mod dayofweek {
    /// Sunday
    pub const SUNDAY: u8 = 0x01;
    /// Monday
    pub const MONDAY: u8 = 0x02;
    /// Tuesday
    pub const TUESDAY: u8 = 0x04;
    /// Wednesday
    pub const WEDNESDAY: u8 = 0x08;
    /// Thursday
    pub const THURSDAY: u8 = 0x10;
    /// Friday
    pub const FRIDAY: u8 = 0x20;
    /// Saturday
    pub const SATURDAY: u8 = 0x40;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct AppInfo {
    pub catalog_vendor_id: Option<u16>,
    pub application_id: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct BlockChannel {
    pub block_channel_index: Option<u16>,
    pub major_number: Option<u16>,
    pub minor_number: Option<u16>,
    pub identifier: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct RatingName {
    pub rating_name: Option<String>,
    pub rating_name_desc: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct TimePeriod {
    pub start_hour: Option<u8>,
    pub start_minute: Option<u8>,
    pub end_hour: Option<u8>,
    pub end_minute: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct TimeWindow {
    pub time_window_index: Option<u16>,
    pub day_of_week: Option<DayOfWeek>,
    pub time_period: Option<Vec<TimePeriod>>,
}

// Command encoders

/// Encode UpdatePIN command (0x00)
pub fn encode_update_pin(old_pin: String, new_pin: String) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::String(old_pin)).into(),
        (1, tlv::TlvItemValueEnc::String(new_pin)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

/// Encode SetScreenDailyTime command (0x06)
pub fn encode_set_screen_daily_time(screen_time: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt32(screen_time)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetOnDemandRatingThreshold command (0x09)
pub fn encode_set_on_demand_rating_threshold(rating: String) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::String(rating)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetScheduledContentRatingThreshold command (0x0A)
pub fn encode_set_scheduled_content_rating_threshold(rating: String) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::String(rating)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode AddBlockChannels command (0x0B)
pub fn encode_add_block_channels(channels: Vec<BlockChannel>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Array(channels.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.block_channel_index { fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.major_number { fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.minor_number { fields.push((2, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.identifier { fields.push((3, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveBlockChannels command (0x0C)
pub fn encode_remove_block_channels(channel_indexes: Vec<u16>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructAnon(channel_indexes.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt16(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode AddBlockApplications command (0x0D)
pub fn encode_add_block_applications(applications: Vec<AppInfo>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Array(applications.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.catalog_vendor_id { fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.application_id { fields.push((1, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveBlockApplications command (0x0E)
pub fn encode_remove_block_applications(applications: Vec<AppInfo>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Array(applications.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.catalog_vendor_id { fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.application_id { fields.push((1, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetBlockContentTimeWindow command (0x0F)
pub fn encode_set_block_content_time_window(time_window: TimeWindow) -> anyhow::Result<Vec<u8>> {
            // Encode struct TimeWindowStruct
            let mut time_window_fields = Vec::new();
            if let Some(x) = time_window.time_window_index { time_window_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
            if let Some(x) = time_window.day_of_week { time_window_fields.push((1, tlv::TlvItemValueEnc::UInt8(x)).into()); }
            if let Some(listv) = time_window.time_period {
                let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
                    let mut nested_fields = Vec::new();
                        if let Some(x) = inner.start_hour { nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x)).into()); }
                        if let Some(x) = inner.start_minute { nested_fields.push((1, tlv::TlvItemValueEnc::UInt8(x)).into()); }
                        if let Some(x) = inner.end_hour { nested_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
                        if let Some(x) = inner.end_minute { nested_fields.push((3, tlv::TlvItemValueEnc::UInt8(x)).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
                }).collect();
                time_window_fields.push((2, tlv::TlvItemValueEnc::Array(inner_vec)).into());
            }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructInvisible(time_window_fields)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveBlockContentTimeWindow command (0x10)
pub fn encode_remove_block_content_time_window(time_window_indexes: Vec<u16>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::StructAnon(time_window_indexes.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt16(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

/// Decode OnDemandRatings attribute (0x0001)
pub fn decode_on_demand_ratings(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<RatingName>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(RatingName {
                rating_name: item.get_string_owned(&[0]),
                rating_name_desc: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

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

/// Decode ScheduledContentRatings attribute (0x0003)
pub fn decode_scheduled_content_ratings(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<RatingName>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(RatingName {
                rating_name: item.get_string_owned(&[0]),
                rating_name_desc: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

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

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

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

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

/// Decode BlockChannelList attribute (0x0008)
pub fn decode_block_channel_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<BlockChannel>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(BlockChannel {
                block_channel_index: item.get_int(&[0]).map(|v| v as u16),
                major_number: item.get_int(&[1]).map(|v| v as u16),
                minor_number: item.get_int(&[2]).map(|v| v as u16),
                identifier: item.get_string_owned(&[3]),
            });
        }
    }
    Ok(res)
}

/// Decode BlockApplicationList attribute (0x0009)
pub fn decode_block_application_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<AppInfo>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(AppInfo {
                catalog_vendor_id: item.get_int(&[0]).map(|v| v as u16),
                application_id: item.get_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

/// Decode BlockContentTimeWindow attribute (0x000A)
pub fn decode_block_content_time_window(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TimeWindow>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TimeWindow {
                time_window_index: item.get_int(&[0]).map(|v| v as u16),
                day_of_week: item.get_int(&[1]).map(|v| v as u8),
                time_period: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(TimePeriod {
                start_hour: list_item.get_int(&[0]).map(|v| v as u8),
                start_minute: list_item.get_int(&[1]).map(|v| v as u8),
                end_hour: list_item.get_int(&[2]).map(|v| v as u8),
                end_minute: list_item.get_int(&[3]).map(|v| v as u8),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}


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

    match attribute_id {
        0x0000 => {
            match decode_enabled(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_on_demand_ratings(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_on_demand_rating_threshold(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_scheduled_content_ratings(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_scheduled_content_rating_threshold(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_screen_daily_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_remaining_screen_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_block_unrated(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_block_channel_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_block_application_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_block_content_time_window(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, "Enabled"),
        (0x0001, "OnDemandRatings"),
        (0x0002, "OnDemandRatingThreshold"),
        (0x0003, "ScheduledContentRatings"),
        (0x0004, "ScheduledContentRatingThreshold"),
        (0x0005, "ScreenDailyTime"),
        (0x0006, "RemainingScreenTime"),
        (0x0007, "BlockUnrated"),
        (0x0008, "BlockChannelList"),
        (0x0009, "BlockApplicationList"),
        (0x000A, "BlockContentTimeWindow"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "UpdatePIN"),
        (0x01, "ResetPIN"),
        (0x03, "Enable"),
        (0x04, "Disable"),
        (0x05, "AddBonusTime"),
        (0x06, "SetScreenDailyTime"),
        (0x07, "BlockUnratedContent"),
        (0x08, "UnblockUnratedContent"),
        (0x09, "SetOnDemandRatingThreshold"),
        (0x0A, "SetScheduledContentRatingThreshold"),
        (0x0B, "AddBlockChannels"),
        (0x0C, "RemoveBlockChannels"),
        (0x0D, "AddBlockApplications"),
        (0x0E, "RemoveBlockApplications"),
        (0x0F, "SetBlockContentTimeWindow"),
        (0x10, "RemoveBlockContentTimeWindow"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("UpdatePIN"),
        0x01 => Some("ResetPIN"),
        0x03 => Some("Enable"),
        0x04 => Some("Disable"),
        0x05 => Some("AddBonusTime"),
        0x06 => Some("SetScreenDailyTime"),
        0x07 => Some("BlockUnratedContent"),
        0x08 => Some("UnblockUnratedContent"),
        0x09 => Some("SetOnDemandRatingThreshold"),
        0x0A => Some("SetScheduledContentRatingThreshold"),
        0x0B => Some("AddBlockChannels"),
        0x0C => Some("RemoveBlockChannels"),
        0x0D => Some("AddBlockApplications"),
        0x0E => Some("RemoveBlockApplications"),
        0x0F => Some("SetBlockContentTimeWindow"),
        0x10 => Some("RemoveBlockContentTimeWindow"),
        _ => 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: "old_pin", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "new_pin", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
        ]),
        0x01 => Some(vec![]),
        0x03 => Some(vec![]),
        0x04 => Some(vec![]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "pin_code", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "bonus_time", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x06 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "screen_time", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x07 => Some(vec![]),
        0x08 => Some(vec![]),
        0x09 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "rating", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
        ]),
        0x0A => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "rating", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
        ]),
        0x0B => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "channels", kind: crate::clusters::codec::FieldKind::List { entry_type: "BlockChannelStruct" }, optional: false, nullable: false },
        ]),
        0x0C => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "channel_indexes", kind: crate::clusters::codec::FieldKind::List { entry_type: "uint16" }, optional: false, nullable: false },
        ]),
        0x0D => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "applications", kind: crate::clusters::codec::FieldKind::List { entry_type: "AppInfoStruct" }, optional: false, nullable: false },
        ]),
        0x0E => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "applications", kind: crate::clusters::codec::FieldKind::List { entry_type: "AppInfoStruct" }, optional: false, nullable: false },
        ]),
        0x0F => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "time_window", kind: crate::clusters::codec::FieldKind::Struct { name: "TimeWindowStruct" }, optional: false, nullable: false },
        ]),
        0x10 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "time_window_indexes", kind: crate::clusters::codec::FieldKind::List { entry_type: "uint16" }, 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 old_pin = crate::clusters::codec::json_util::get_string(args, "old_pin")?;
        let new_pin = crate::clusters::codec::json_util::get_string(args, "new_pin")?;
        encode_update_pin(old_pin, new_pin)
        }
        0x01 => Ok(vec![]),
        0x03 => Ok(vec![]),
        0x04 => Ok(vec![]),
        0x05 => {
        let pin_code = crate::clusters::codec::json_util::get_opt_string(args, "pin_code")?;
        let bonus_time = crate::clusters::codec::json_util::get_u32(args, "bonus_time")?;
        encode_add_bonus_time(pin_code, bonus_time)
        }
        0x06 => {
        let screen_time = crate::clusters::codec::json_util::get_u32(args, "screen_time")?;
        encode_set_screen_daily_time(screen_time)
        }
        0x07 => Ok(vec![]),
        0x08 => Ok(vec![]),
        0x09 => {
        let rating = crate::clusters::codec::json_util::get_string(args, "rating")?;
        encode_set_on_demand_rating_threshold(rating)
        }
        0x0A => {
        let rating = crate::clusters::codec::json_util::get_string(args, "rating")?;
        encode_set_scheduled_content_rating_threshold(rating)
        }
        0x0B => Err(anyhow::anyhow!("command \"AddBlockChannels\" has complex args: use raw mode")),
        0x0C => Err(anyhow::anyhow!("command \"RemoveBlockChannels\" has complex args: use raw mode")),
        0x0D => Err(anyhow::anyhow!("command \"AddBlockApplications\" has complex args: use raw mode")),
        0x0E => Err(anyhow::anyhow!("command \"RemoveBlockApplications\" has complex args: use raw mode")),
        0x0F => Err(anyhow::anyhow!("command \"SetBlockContentTimeWindow\" has complex args: use raw mode")),
        0x10 => Err(anyhow::anyhow!("command \"RemoveBlockContentTimeWindow\" has complex args: use raw mode")),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct ResetPINResponse {
    pub pin_code: Option<String>,
}

// Command response decoders

/// Decode ResetPINResponse command response (02)
pub fn decode_reset_pin_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ResetPINResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ResetPINResponse {
                pin_code: item.get_string_owned(&[0]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `UpdatePIN` command on cluster `Content Control`.
pub async fn update_pin(conn: &crate::controller::Connection, endpoint: u16, old_pin: String, new_pin: String) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_UPDATEPIN, &encode_update_pin(old_pin, new_pin)?).await?;
    Ok(())
}

/// Invoke `ResetPIN` command on cluster `Content Control`.
pub async fn reset_pin(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<ResetPINResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_RESETPIN, &[]).await?;
    decode_reset_pin_response(&tlv)
}

/// Invoke `Enable` command on cluster `Content Control`.
pub async fn enable(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_ENABLE, &[]).await?;
    Ok(())
}

/// Invoke `Disable` command on cluster `Content Control`.
pub async fn disable(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_DISABLE, &[]).await?;
    Ok(())
}

/// Invoke `AddBonusTime` command on cluster `Content Control`.
pub async fn add_bonus_time(conn: &crate::controller::Connection, endpoint: u16, pin_code: Option<String>, bonus_time: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_ADDBONUSTIME, &encode_add_bonus_time(pin_code, bonus_time)?).await?;
    Ok(())
}

/// Invoke `SetScreenDailyTime` command on cluster `Content Control`.
pub async fn set_screen_daily_time(conn: &crate::controller::Connection, endpoint: u16, screen_time: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_SETSCREENDAILYTIME, &encode_set_screen_daily_time(screen_time)?).await?;
    Ok(())
}

/// Invoke `BlockUnratedContent` command on cluster `Content Control`.
pub async fn block_unrated_content(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_BLOCKUNRATEDCONTENT, &[]).await?;
    Ok(())
}

/// Invoke `UnblockUnratedContent` command on cluster `Content Control`.
pub async fn unblock_unrated_content(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_UNBLOCKUNRATEDCONTENT, &[]).await?;
    Ok(())
}

/// Invoke `SetOnDemandRatingThreshold` command on cluster `Content Control`.
pub async fn set_on_demand_rating_threshold(conn: &crate::controller::Connection, endpoint: u16, rating: String) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_SETONDEMANDRATINGTHRESHOLD, &encode_set_on_demand_rating_threshold(rating)?).await?;
    Ok(())
}

/// Invoke `SetScheduledContentRatingThreshold` command on cluster `Content Control`.
pub async fn set_scheduled_content_rating_threshold(conn: &crate::controller::Connection, endpoint: u16, rating: String) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_SETSCHEDULEDCONTENTRATINGTHRESHOLD, &encode_set_scheduled_content_rating_threshold(rating)?).await?;
    Ok(())
}

/// Invoke `AddBlockChannels` command on cluster `Content Control`.
pub async fn add_block_channels(conn: &crate::controller::Connection, endpoint: u16, channels: Vec<BlockChannel>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_ADDBLOCKCHANNELS, &encode_add_block_channels(channels)?).await?;
    Ok(())
}

/// Invoke `RemoveBlockChannels` command on cluster `Content Control`.
pub async fn remove_block_channels(conn: &crate::controller::Connection, endpoint: u16, channel_indexes: Vec<u16>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_REMOVEBLOCKCHANNELS, &encode_remove_block_channels(channel_indexes)?).await?;
    Ok(())
}

/// Invoke `AddBlockApplications` command on cluster `Content Control`.
pub async fn add_block_applications(conn: &crate::controller::Connection, endpoint: u16, applications: Vec<AppInfo>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_ADDBLOCKAPPLICATIONS, &encode_add_block_applications(applications)?).await?;
    Ok(())
}

/// Invoke `RemoveBlockApplications` command on cluster `Content Control`.
pub async fn remove_block_applications(conn: &crate::controller::Connection, endpoint: u16, applications: Vec<AppInfo>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_REMOVEBLOCKAPPLICATIONS, &encode_remove_block_applications(applications)?).await?;
    Ok(())
}

/// Invoke `SetBlockContentTimeWindow` command on cluster `Content Control`.
pub async fn set_block_content_time_window(conn: &crate::controller::Connection, endpoint: u16, time_window: TimeWindow) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_SETBLOCKCONTENTTIMEWINDOW, &encode_set_block_content_time_window(time_window)?).await?;
    Ok(())
}

/// Invoke `RemoveBlockContentTimeWindow` command on cluster `Content Control`.
pub async fn remove_block_content_time_window(conn: &crate::controller::Connection, endpoint: u16, time_window_indexes: Vec<u16>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_CMD_ID_REMOVEBLOCKCONTENTTIMEWINDOW, &encode_remove_block_content_time_window(time_window_indexes)?).await?;
    Ok(())
}

/// Read `Enabled` attribute from cluster `Content Control`.
pub async fn read_enabled(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_ENABLED).await?;
    decode_enabled(&tlv)
}

/// Read `OnDemandRatings` attribute from cluster `Content Control`.
pub async fn read_on_demand_ratings(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<RatingName>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_ONDEMANDRATINGS).await?;
    decode_on_demand_ratings(&tlv)
}

/// Read `OnDemandRatingThreshold` attribute from cluster `Content Control`.
pub async fn read_on_demand_rating_threshold(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<String> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_ONDEMANDRATINGTHRESHOLD).await?;
    decode_on_demand_rating_threshold(&tlv)
}

/// Read `ScheduledContentRatings` attribute from cluster `Content Control`.
pub async fn read_scheduled_content_ratings(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<RatingName>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_SCHEDULEDCONTENTRATINGS).await?;
    decode_scheduled_content_ratings(&tlv)
}

/// Read `ScheduledContentRatingThreshold` attribute from cluster `Content Control`.
pub async fn read_scheduled_content_rating_threshold(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<String> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_SCHEDULEDCONTENTRATINGTHRESHOLD).await?;
    decode_scheduled_content_rating_threshold(&tlv)
}

/// Read `ScreenDailyTime` attribute from cluster `Content Control`.
pub async fn read_screen_daily_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_SCREENDAILYTIME).await?;
    decode_screen_daily_time(&tlv)
}

/// Read `RemainingScreenTime` attribute from cluster `Content Control`.
pub async fn read_remaining_screen_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_REMAININGSCREENTIME).await?;
    decode_remaining_screen_time(&tlv)
}

/// Read `BlockUnrated` attribute from cluster `Content Control`.
pub async fn read_block_unrated(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_BLOCKUNRATED).await?;
    decode_block_unrated(&tlv)
}

/// Read `BlockChannelList` attribute from cluster `Content Control`.
pub async fn read_block_channel_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<BlockChannel>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_BLOCKCHANNELLIST).await?;
    decode_block_channel_list(&tlv)
}

/// Read `BlockApplicationList` attribute from cluster `Content Control`.
pub async fn read_block_application_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<AppInfo>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_BLOCKAPPLICATIONLIST).await?;
    decode_block_application_list(&tlv)
}

/// Read `BlockContentTimeWindow` attribute from cluster `Content Control`.
pub async fn read_block_content_time_window(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TimeWindow>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CONTENT_CONTROL, crate::clusters::defs::CLUSTER_CONTENT_CONTROL_ATTR_ID_BLOCKCONTENTTIMEWINDOW).await?;
    decode_block_content_time_window(&tlv)
}