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
//! Matter TLV encoders and decoders for Time Synchronization Cluster
//! Cluster ID: 0x0038
//!
//! This file is automatically generated from TimeSync.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 Granularity {
    /// This indicates that the node is not currently synchronized with a UTC Time source and its clock is based on the Last Known Good UTC Time only.
    Notimegranularity = 0,
    /// This indicates the node was synchronized to an upstream source in the past, but sufficient clock drift has occurred such that the clock error is now > 5 seconds.
    Minutesgranularity = 1,
    /// This indicates the node is synchronized to an upstream source using a low resolution protocol. UTC Time is accurate to ± 5 seconds.
    Secondsgranularity = 2,
    /// This indicates the node is synchronized to an upstream source using high resolution time-synchronization protocol such as NTP, or has built-in GNSS with some amount of jitter applying its GNSS timestamp. UTC Time is accurate to ± 50 ms.
    Millisecondsgranularity = 3,
    /// This indicates the node is synchronized to an upstream source using a highly precise time-synchronization protocol such as PTP, or has built-in GNSS. UTC time is accurate to ± 10 μs.
    Microsecondsgranularity = 4,
}

impl Granularity {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Granularity::Notimegranularity),
            1 => Some(Granularity::Minutesgranularity),
            2 => Some(Granularity::Secondsgranularity),
            3 => Some(Granularity::Millisecondsgranularity),
            4 => Some(Granularity::Microsecondsgranularity),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StatusCode {
    /// Node rejected the attempt to set the UTC time
    Timenotaccepted = 2,
}

impl StatusCode {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            2 => Some(StatusCode::Timenotaccepted),
            _ => 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
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TimeSource {
    /// Node is not currently synchronized with a UTC Time source.
    None = 0,
    /// Node uses an unlisted time source.
    Unknown = 1,
    /// Node received time from a client using the SetUTCTime Command.
    Admin = 2,
    /// Synchronized time by querying the Time Synchronization cluster of another Node.
    Nodetimecluster = 3,
    /// SNTP from a server not in the Matter network. NTS is not used.
    Nonmattersntp = 4,
    /// NTP from servers not in the Matter network. None of the servers used NTS.
    Nonmatterntp = 5,
    /// SNTP from a server within the Matter network. NTS is not used.
    Mattersntp = 6,
    /// NTP from servers within the Matter network. None of the servers used NTS.
    Matterntp = 7,
    /// NTP from multiple servers in the Matter network and external. None of the servers used NTS.
    Mixedntp = 8,
    /// SNTP from a server not in the Matter network. NTS is used.
    Nonmattersntpnts = 9,
    /// NTP from servers not in the Matter network. NTS is used on at least one server.
    Nonmatterntpnts = 10,
    /// SNTP from a server within the Matter network. NTS is used.
    Mattersntpnts = 11,
    /// NTP from a server within the Matter network. NTS is used on at least one server.
    Matterntpnts = 12,
    /// NTP from multiple servers in the Matter network and external. NTS is used on at least one server.
    Mixedntpnts = 13,
    /// Time synchronization comes from a vendor cloud-based source (e.g. "Date" header in authenticated HTTPS connection).
    Cloudsource = 14,
    /// Time synchronization comes from PTP.
    Ptp = 15,
    /// Time synchronization comes from a GNSS source.
    Gnss = 16,
}

impl TimeSource {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(TimeSource::None),
            1 => Some(TimeSource::Unknown),
            2 => Some(TimeSource::Admin),
            3 => Some(TimeSource::Nodetimecluster),
            4 => Some(TimeSource::Nonmattersntp),
            5 => Some(TimeSource::Nonmatterntp),
            6 => Some(TimeSource::Mattersntp),
            7 => Some(TimeSource::Matterntp),
            8 => Some(TimeSource::Mixedntp),
            9 => Some(TimeSource::Nonmattersntpnts),
            10 => Some(TimeSource::Nonmatterntpnts),
            11 => Some(TimeSource::Mattersntpnts),
            12 => Some(TimeSource::Matterntpnts),
            13 => Some(TimeSource::Mixedntpnts),
            14 => Some(TimeSource::Cloudsource),
            15 => Some(TimeSource::Ptp),
            16 => Some(TimeSource::Gnss),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TimeZoneDatabase {
    /// Node has a full list of the available time zones
    Full = 0,
    /// Node has a partial list of the available time zones
    Partial = 1,
    /// Node does not have a time zone database
    None = 2,
}

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

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

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

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct DSTOffset {
    pub offset: Option<i32>,
    pub valid_starting: Option<u64>,
    pub valid_until: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct FabricScopedTrustedTimeSource {
    pub node_id: Option<u64>,
    pub endpoint: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct TimeZone {
    pub offset: Option<i32>,
    pub valid_at: Option<u64>,
    pub name: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct TrustedTimeSource {
    pub fabric_index: Option<u8>,
    pub node_id: Option<u64>,
    pub endpoint: Option<u16>,
}

// Command encoders

/// Encode SetUTCTime command (0x00)
pub fn encode_set_utc_time(utc_time: u64, granularity: Granularity, time_source: Option<TimeSource>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    tlv_fields.push((0, tlv::TlvItemValueEnc::UInt64(utc_time)).into());
    tlv_fields.push((1, tlv::TlvItemValueEnc::UInt8(granularity.to_u8())).into());
    if let Some(x) = time_source { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

/// Encode SetTrustedTimeSource command (0x01)
pub fn encode_set_trusted_time_source(trusted_time_source: Option<FabricScopedTrustedTimeSource>) -> anyhow::Result<Vec<u8>> {
            // Encode optional struct FabricScopedTrustedTimeSourceStruct
            let trusted_time_source_enc = if let Some(s) = trusted_time_source {
                let mut fields = Vec::new();
                if let Some(x) = s.node_id { fields.push((0, tlv::TlvItemValueEnc::UInt64(x)).into()); }
                if let Some(x) = s.endpoint { fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                tlv::TlvItemValueEnc::StructInvisible(fields)
            } else {
                tlv::TlvItemValueEnc::StructInvisible(Vec::new())
            };
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, trusted_time_source_enc).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetTimeZone command (0x02)
pub fn encode_set_time_zone(time_zone: Vec<TimeZone>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Array(time_zone.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.offset { fields.push((0, tlv::TlvItemValueEnc::Int32(x)).into()); }
                    if let Some(x) = v.valid_at { fields.push((1, tlv::TlvItemValueEnc::UInt64(x)).into()); }
                    if let Some(x) = v.name { fields.push((2, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetDSTOffset command (0x04)
pub fn encode_set_dst_offset(dst_offset: Vec<DSTOffset>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Array(dst_offset.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.offset { fields.push((0, tlv::TlvItemValueEnc::Int32(x)).into()); }
                    if let Some(x) = v.valid_starting { fields.push((1, tlv::TlvItemValueEnc::UInt64(x)).into()); }
                    if let Some(x) = v.valid_until { fields.push((2, tlv::TlvItemValueEnc::UInt64(x)).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SetDefaultNTP command (0x05)
pub fn encode_set_default_ntp(default_ntp: Option<String>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::String(default_ntp.unwrap_or("".to_string()))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode UTCTime attribute (0x0000)
pub fn decode_utc_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

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

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

/// Decode TrustedTimeSource attribute (0x0003)
pub fn decode_trusted_time_source(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<TrustedTimeSource>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(TrustedTimeSource {
                fabric_index: item.get_int(&[0]).map(|v| v as u8),
                node_id: item.get_int(&[1]),
                endpoint: item.get_int(&[2]).map(|v| v as u16),
        }))
    //} else if let tlv::TlvItemValue::Null = inp {
    //    // Null value for nullable struct
    //    Ok(None)
    } else {
    Ok(None)
    //    Err(anyhow::anyhow!("Expected struct fields or null"))
    }
}

/// Decode DefaultNTP attribute (0x0004)
pub fn decode_default_ntp(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<String>> {
    if let tlv::TlvItemValue::String(v) = inp {
        Ok(Some(v.clone()))
    } else {
        Ok(None)
    }
}

/// Decode TimeZone attribute (0x0005)
pub fn decode_time_zone(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TimeZone>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TimeZone {
                offset: item.get_int(&[0]).map(|v| v as i32),
                valid_at: item.get_int(&[1]),
                name: item.get_string_owned(&[2]),
            });
        }
    }
    Ok(res)
}

/// Decode DSTOffset attribute (0x0006)
pub fn decode_dst_offset(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<DSTOffset>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(DSTOffset {
                offset: item.get_int(&[0]).map(|v| v as i32),
                valid_starting: item.get_int(&[1]),
                valid_until: item.get_int(&[2]),
            });
        }
    }
    Ok(res)
}

/// Decode LocalTime attribute (0x0007)
pub fn decode_local_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(Some(*v))
    } else {
        Ok(None)
    }
}

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

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

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

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

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


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

    match attribute_id {
        0x0000 => {
            match decode_utc_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_granularity(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_time_source(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_trusted_time_source(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_default_ntp(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_time_zone(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_dst_offset(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_local_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_time_zone_database(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_ntp_server_available(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_time_zone_list_max_size(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_dst_offset_list_max_size(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000C => {
            match decode_supports_dns_resolve(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, "UTCTime"),
        (0x0001, "Granularity"),
        (0x0002, "TimeSource"),
        (0x0003, "TrustedTimeSource"),
        (0x0004, "DefaultNTP"),
        (0x0005, "TimeZone"),
        (0x0006, "DSTOffset"),
        (0x0007, "LocalTime"),
        (0x0008, "TimeZoneDatabase"),
        (0x0009, "NTPServerAvailable"),
        (0x000A, "TimeZoneListMaxSize"),
        (0x000B, "DSTOffsetListMaxSize"),
        (0x000C, "SupportsDNSResolve"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "SetUTCTime"),
        (0x01, "SetTrustedTimeSource"),
        (0x02, "SetTimeZone"),
        (0x04, "SetDSTOffset"),
        (0x05, "SetDefaultNTP"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("SetUTCTime"),
        0x01 => Some("SetTrustedTimeSource"),
        0x02 => Some("SetTimeZone"),
        0x04 => Some("SetDSTOffset"),
        0x05 => Some("SetDefaultNTP"),
        _ => 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: "utc_time", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "granularity", kind: crate::clusters::codec::FieldKind::Enum { name: "Granularity", variants: &[(0, "Notimegranularity"), (1, "Minutesgranularity"), (2, "Secondsgranularity"), (3, "Millisecondsgranularity"), (4, "Microsecondsgranularity")] }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "time_source", kind: crate::clusters::codec::FieldKind::Enum { name: "TimeSource", variants: &[(0, "None"), (1, "Unknown"), (2, "Admin"), (3, "Nodetimecluster"), (4, "Nonmattersntp"), (5, "Nonmatterntp"), (6, "Mattersntp"), (7, "Matterntp"), (8, "Mixedntp"), (9, "Nonmattersntpnts"), (10, "Nonmatterntpnts"), (11, "Mattersntpnts"), (12, "Matterntpnts"), (13, "Mixedntpnts"), (14, "Cloudsource"), (15, "Ptp"), (16, "Gnss")] }, optional: true, nullable: false },
        ]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "trusted_time_source", kind: crate::clusters::codec::FieldKind::Struct { name: "FabricScopedTrustedTimeSourceStruct" }, optional: false, nullable: true },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "time_zone", kind: crate::clusters::codec::FieldKind::List { entry_type: "TimeZoneStruct" }, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "dst_offset", kind: crate::clusters::codec::FieldKind::List { entry_type: "DSTOffsetStruct" }, optional: false, nullable: false },
        ]),
        0x05 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "default_ntp", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: true },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => {
        let utc_time = crate::clusters::codec::json_util::get_u64(args, "utc_time")?;
        let granularity = {
            let n = crate::clusters::codec::json_util::get_u64(args, "granularity")?;
            Granularity::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid Granularity: {}", n))?
        };
        let time_source = crate::clusters::codec::json_util::get_opt_u64(args, "time_source")?
            .and_then(|n| TimeSource::from_u8(n as u8));
        encode_set_utc_time(utc_time, granularity, time_source)
        }
        0x01 => Err(anyhow::anyhow!("command \"SetTrustedTimeSource\" has complex args: use raw mode")),
        0x02 => Err(anyhow::anyhow!("command \"SetTimeZone\" has complex args: use raw mode")),
        0x04 => Err(anyhow::anyhow!("command \"SetDSTOffset\" has complex args: use raw mode")),
        0x05 => {
        let default_ntp = crate::clusters::codec::json_util::get_opt_string(args, "default_ntp")?;
        encode_set_default_ntp(default_ntp)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[derive(Debug, serde::Serialize)]
pub struct SetTimeZoneResponse {
    pub dst_offset_required: Option<bool>,
}

// Command response decoders

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

// Typed facade (invokes + reads)

/// Invoke `SetUTCTime` command on cluster `Time Synchronization`.
pub async fn set_utc_time(conn: &crate::controller::Connection, endpoint: u16, utc_time: u64, granularity: Granularity, time_source: Option<TimeSource>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETUTCTIME, &encode_set_utc_time(utc_time, granularity, time_source)?).await?;
    Ok(())
}

/// Invoke `SetTrustedTimeSource` command on cluster `Time Synchronization`.
pub async fn set_trusted_time_source(conn: &crate::controller::Connection, endpoint: u16, trusted_time_source: Option<FabricScopedTrustedTimeSource>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETTRUSTEDTIMESOURCE, &encode_set_trusted_time_source(trusted_time_source)?).await?;
    Ok(())
}

/// Invoke `SetTimeZone` command on cluster `Time Synchronization`.
pub async fn set_time_zone(conn: &crate::controller::Connection, endpoint: u16, time_zone: Vec<TimeZone>) -> anyhow::Result<SetTimeZoneResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETTIMEZONE, &encode_set_time_zone(time_zone)?).await?;
    decode_set_time_zone_response(&tlv)
}

/// Invoke `SetDSTOffset` command on cluster `Time Synchronization`.
pub async fn set_dst_offset(conn: &crate::controller::Connection, endpoint: u16, dst_offset: Vec<DSTOffset>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETDSTOFFSET, &encode_set_dst_offset(dst_offset)?).await?;
    Ok(())
}

/// Invoke `SetDefaultNTP` command on cluster `Time Synchronization`.
pub async fn set_default_ntp(conn: &crate::controller::Connection, endpoint: u16, default_ntp: Option<String>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETDEFAULTNTP, &encode_set_default_ntp(default_ntp)?).await?;
    Ok(())
}

/// Read `UTCTime` attribute from cluster `Time Synchronization`.
pub async fn read_utc_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_UTCTIME).await?;
    decode_utc_time(&tlv)
}

/// Read `Granularity` attribute from cluster `Time Synchronization`.
pub async fn read_granularity(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Granularity> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_GRANULARITY).await?;
    decode_granularity(&tlv)
}

/// Read `TimeSource` attribute from cluster `Time Synchronization`.
pub async fn read_time_source(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TimeSource> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMESOURCE).await?;
    decode_time_source(&tlv)
}

/// Read `TrustedTimeSource` attribute from cluster `Time Synchronization`.
pub async fn read_trusted_time_source(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<TrustedTimeSource>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TRUSTEDTIMESOURCE).await?;
    decode_trusted_time_source(&tlv)
}

/// Read `DefaultNTP` attribute from cluster `Time Synchronization`.
pub async fn read_default_ntp(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<String>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_DEFAULTNTP).await?;
    decode_default_ntp(&tlv)
}

/// Read `TimeZone` attribute from cluster `Time Synchronization`.
pub async fn read_time_zone(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TimeZone>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMEZONE).await?;
    decode_time_zone(&tlv)
}

/// Read `DSTOffset` attribute from cluster `Time Synchronization`.
pub async fn read_dst_offset(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<DSTOffset>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_DSTOFFSET).await?;
    decode_dst_offset(&tlv)
}

/// Read `LocalTime` attribute from cluster `Time Synchronization`.
pub async fn read_local_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_LOCALTIME).await?;
    decode_local_time(&tlv)
}

/// Read `TimeZoneDatabase` attribute from cluster `Time Synchronization`.
pub async fn read_time_zone_database(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TimeZoneDatabase> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMEZONEDATABASE).await?;
    decode_time_zone_database(&tlv)
}

/// Read `NTPServerAvailable` attribute from cluster `Time Synchronization`.
pub async fn read_ntp_server_available(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_NTPSERVERAVAILABLE).await?;
    decode_ntp_server_available(&tlv)
}

/// Read `TimeZoneListMaxSize` attribute from cluster `Time Synchronization`.
pub async fn read_time_zone_list_max_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMEZONELISTMAXSIZE).await?;
    decode_time_zone_list_max_size(&tlv)
}

/// Read `DSTOffsetListMaxSize` attribute from cluster `Time Synchronization`.
pub async fn read_dst_offset_list_max_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_DSTOFFSETLISTMAXSIZE).await?;
    decode_dst_offset_list_max_size(&tlv)
}

/// Read `SupportsDNSResolve` attribute from cluster `Time Synchronization`.
pub async fn read_supports_dns_resolve(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_SUPPORTSDNSRESOLVE).await?;
    decode_supports_dns_resolve(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct DSTStatusEvent {
    pub dst_offset_active: Option<bool>,
}

#[derive(Debug, serde::Serialize)]
pub struct TimeZoneStatusEvent {
    pub offset: Option<i32>,
    pub name: Option<String>,
}

// Event decoders

/// Decode DSTStatus event (0x01, priority: info)
pub fn decode_dst_status_event(inp: &tlv::TlvItemValue) -> anyhow::Result<DSTStatusEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(DSTStatusEvent {
                                dst_offset_active: item.get_bool(&[0]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode TimeZoneStatus event (0x02, priority: info)
pub fn decode_time_zone_status_event(inp: &tlv::TlvItemValue) -> anyhow::Result<TimeZoneStatusEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(TimeZoneStatusEvent {
                                offset: item.get_int(&[0]).map(|v| v as i32),
                                name: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}