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
//! Matter TLV encoders and decoders for Closure Control Cluster
//! Cluster ID: 0x0104
//!
//! This file is automatically generated from ClosureControl.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 ClosureError {
    /// An obstacle is blocking the closure movement
    Physicallyblocked = 0,
    /// The closure is unsafe to move, as determined by a sensor (e.g. photoelectric sensor) before attempting movement
    Blockedbysensor = 1,
    /// A warning raised by the closure that indicates an over-temperature, e.g. due to excessive drive or stall current
    Temperaturelimited = 2,
    /// Some malfunctions that are not easily recoverable are detected, or urgent servicing is needed
    Maintenancerequired = 3,
    /// An internal element is prohibiting motion, e.g. an integrated door within a bigger garage door is open and prevents motion
    Internalinterference = 4,
}

impl ClosureError {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ClosureError::Physicallyblocked),
            1 => Some(ClosureError::Blockedbysensor),
            2 => Some(ClosureError::Temperaturelimited),
            3 => Some(ClosureError::Maintenancerequired),
            4 => Some(ClosureError::Internalinterference),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum CurrentPosition {
    /// Fully closed state
    Fullyclosed = 0,
    /// Fully opened state
    Fullyopened = 1,
    /// Partially opened state (closure is not fully opened or fully closed)
    Partiallyopened = 2,
    /// Closure is in the Pedestrian position
    Openedforpedestrian = 3,
    /// Closure is in the Ventilation position
    Openedforventilation = 4,
    /// Closure is in its "Signature position"
    Openedatsignature = 5,
}

impl CurrentPosition {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(CurrentPosition::Fullyclosed),
            1 => Some(CurrentPosition::Fullyopened),
            2 => Some(CurrentPosition::Partiallyopened),
            3 => Some(CurrentPosition::Openedforpedestrian),
            4 => Some(CurrentPosition::Openedforventilation),
            5 => Some(CurrentPosition::Openedatsignature),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum MainState {
    /// Closure is stopped
    Stopped = 0,
    /// Closure is actively moving
    Moving = 1,
    /// Closure is waiting before a motion (e.g. pre-heat, pre-check)
    Waitingformotion = 2,
    /// Closure is in an error state
    Error = 3,
    /// Closure is currently calibrating its Opened and Closed limits to determine effective physical range
    Calibrating = 4,
    /// Some protective measures are activated to prevent damage to the closure. Commands MAY be rejected.
    Protected = 5,
    /// Closure has a disengaged element preventing any actuator movements
    Disengaged = 6,
    /// Movement commands are ignored since the closure is not operational and requires further setup and/or calibration
    Setuprequired = 7,
}

impl MainState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(MainState::Stopped),
            1 => Some(MainState::Moving),
            2 => Some(MainState::Waitingformotion),
            3 => Some(MainState::Error),
            4 => Some(MainState::Calibrating),
            5 => Some(MainState::Protected),
            6 => Some(MainState::Disengaged),
            7 => Some(MainState::Setuprequired),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TargetPosition {
    /// Move to a fully closed state
    Movetofullyclosed = 0,
    /// Move to a fully open state
    Movetofullyopen = 1,
    /// Move to the Pedestrian position
    Movetopedestrianposition = 2,
    /// Move to the Ventilation position
    Movetoventilationposition = 3,
    /// Move to the Signature position
    Movetosignatureposition = 4,
}

impl TargetPosition {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(TargetPosition::Movetofullyclosed),
            1 => Some(TargetPosition::Movetofullyopen),
            2 => Some(TargetPosition::Movetopedestrianposition),
            3 => Some(TargetPosition::Movetoventilationposition),
            4 => Some(TargetPosition::Movetosignatureposition),
            _ => None,
        }
    }

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

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

// Bitmap definitions

/// LatchControlModes bitmap type
pub type LatchControlModes = u8;

/// Constants for LatchControlModes
pub mod latchcontrolmodes {
    /// Remote latching capability
    pub const REMOTE_LATCHING: u8 = 0x01;
    /// Remote unlatching capability
    pub const REMOTE_UNLATCHING: u8 = 0x02;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct OverallCurrentState {
    pub position: Option<CurrentPosition>,
    pub latch: Option<bool>,
    pub speed: Option<u8>,
    pub secure_state: Option<bool>,
}

#[derive(Debug, serde::Serialize)]
pub struct OverallTargetState {
    pub position: Option<TargetPosition>,
    pub latch: Option<bool>,
    pub speed: Option<u8>,
}

// Command encoders

/// Encode MoveTo command (0x01)
pub fn encode_move_to(position: Option<TargetPosition>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
    if let Some(x) = position { tlv_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
    if let Some(x) = latch { tlv_fields.push((1, tlv::TlvItemValueEnc::Bool(x)).into()); }
    if let Some(x) = speed { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

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

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

/// Decode CurrentErrorList attribute (0x0002)
pub fn decode_current_error_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ClosureError>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            if let tlv::TlvItemValue::Int(i) = &item.value {
                if let Some(enum_val) = ClosureError::from_u8(*i as u8) {
                    res.push(enum_val);
                }
            }
        }
    }
    Ok(res)
}

/// Decode OverallCurrentState attribute (0x0003)
pub fn decode_overall_current_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallCurrentState>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(OverallCurrentState {
                position: item.get_int(&[0]).and_then(|v| CurrentPosition::from_u8(v as u8)),
                latch: item.get_bool(&[1]),
                speed: item.get_int(&[2]).map(|v| v as u8),
                secure_state: item.get_bool(&[3]),
        }))
    //} 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 OverallTargetState attribute (0x0004)
pub fn decode_overall_target_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallTargetState>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(OverallTargetState {
                position: item.get_int(&[0]).and_then(|v| TargetPosition::from_u8(v as u8)),
                latch: item.get_bool(&[1]),
                speed: item.get_int(&[2]).map(|v| v as u8),
        }))
    //} 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 LatchControlModes attribute (0x0005)
pub fn decode_latch_control_modes(inp: &tlv::TlvItemValue) -> anyhow::Result<LatchControlModes> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected Integer"))
    }
}


// JSON dispatcher function

/// Decode attribute value and return as JSON string
///
/// # Parameters
/// * `cluster_id` - The cluster identifier
/// * `attribute_id` - The attribute identifier
/// * `tlv_value` - The TLV value to decode
///
/// # Returns
/// JSON string representation of the decoded value or error
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
    // Verify this is the correct cluster
    if cluster_id != 0x0104 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0104, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_countdown_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_main_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_current_error_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_overall_current_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_overall_target_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_latch_control_modes(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, "CountdownTime"),
        (0x0001, "MainState"),
        (0x0002, "CurrentErrorList"),
        (0x0003, "OverallCurrentState"),
        (0x0004, "OverallTargetState"),
        (0x0005, "LatchControlModes"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "Stop"),
        (0x01, "MoveTo"),
        (0x02, "Calibrate"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("Stop"),
        0x01 => Some("MoveTo"),
        0x02 => Some("Calibrate"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![]),
        0x01 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "position", kind: crate::clusters::codec::FieldKind::Enum { name: "TargetPosition", variants: &[(0, "Movetofullyclosed"), (1, "Movetofullyopen"), (2, "Movetopedestrianposition"), (3, "Movetoventilationposition"), (4, "Movetosignatureposition")] }, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "latch", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "speed", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
        ]),
        0x02 => Some(vec![]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => Ok(vec![]),
        0x01 => {
        let position = crate::clusters::codec::json_util::get_opt_u64(args, "position")?
            .and_then(|n| TargetPosition::from_u8(n as u8));
        let latch = crate::clusters::codec::json_util::get_opt_bool(args, "latch")?;
        let speed = crate::clusters::codec::json_util::get_opt_u8(args, "speed")?;
        encode_move_to(position, latch, speed)
        }
        0x02 => Ok(vec![]),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

// Typed facade (invokes + reads)

/// Invoke `Stop` command on cluster `Closure Control`.
pub async fn stop(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_STOP, &[]).await?;
    Ok(())
}

/// Invoke `MoveTo` command on cluster `Closure Control`.
pub async fn move_to(conn: &crate::controller::Connection, endpoint: u16, position: Option<TargetPosition>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_MOVETO, &encode_move_to(position, latch, speed)?).await?;
    Ok(())
}

/// Invoke `Calibrate` command on cluster `Closure Control`.
pub async fn calibrate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_CALIBRATE, &[]).await?;
    Ok(())
}

/// Read `CountdownTime` attribute from cluster `Closure Control`.
pub async fn read_countdown_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_COUNTDOWNTIME).await?;
    decode_countdown_time(&tlv)
}

/// Read `MainState` attribute from cluster `Closure Control`.
pub async fn read_main_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<MainState> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_MAINSTATE).await?;
    decode_main_state(&tlv)
}

/// Read `CurrentErrorList` attribute from cluster `Closure Control`.
pub async fn read_current_error_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ClosureError>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_CURRENTERRORLIST).await?;
    decode_current_error_list(&tlv)
}

/// Read `OverallCurrentState` attribute from cluster `Closure Control`.
pub async fn read_overall_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallCurrentState>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLCURRENTSTATE).await?;
    decode_overall_current_state(&tlv)
}

/// Read `OverallTargetState` attribute from cluster `Closure Control`.
pub async fn read_overall_target_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallTargetState>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLTARGETSTATE).await?;
    decode_overall_target_state(&tlv)
}

/// Read `LatchControlModes` attribute from cluster `Closure Control`.
pub async fn read_latch_control_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<LatchControlModes> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_LATCHCONTROLMODES).await?;
    decode_latch_control_modes(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct OperationalErrorEvent {
    pub error_state: Option<Vec<ClosureError>>,
}

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

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

// Event decoders

/// Decode OperationalError event (0x00, priority: critical)
pub fn decode_operational_error_event(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalErrorEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(OperationalErrorEvent {
                                error_state: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let items: Vec<ClosureError> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { ClosureError::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

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

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