matc 0.1.2

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
//! Matter TLV encoders and decoders for Time Synchronization Cluster
//! Cluster ID: 0x0038
//!
//! This file is automatically generated from TimeSync.xml

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: TimeSource) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(utc_time)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(granularity.to_u8())).into(),
        (2, tlv::TlvItemValueEnc::UInt8(time_source.to_u8())).into(),
        ]),
    };
    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"),
    ]
}

#[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"))
    }
}

#[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"))
    }
}