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
//! Matter TLV encoders and decoders for Wi-Fi Network Diagnostics Cluster
//! Cluster ID: 0x0036
//!
//! This file is automatically generated from DiagnosticsWiFi.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 AssociationFailureCause {
    /// The reason for the failure is unknown.
    Unknown = 0,
    /// An error occurred during association.
    Associationfailed = 1,
    /// An error occurred during authentication.
    Authenticationfailed = 2,
    /// The specified SSID could not be found.
    Ssidnotfound = 3,
}

impl AssociationFailureCause {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(AssociationFailureCause::Unknown),
            1 => Some(AssociationFailureCause::Associationfailed),
            2 => Some(AssociationFailureCause::Authenticationfailed),
            3 => Some(AssociationFailureCause::Ssidnotfound),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ConnectionStatus {
    /// Indicate the node is connected
    Connected = 0,
    /// Indicate the node is not connected
    Notconnected = 1,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum SecurityType {
    /// Indicate the usage of an unspecified Wi-Fi security type
    Unspecified = 0,
    /// Indicate the usage of no Wi-Fi security
    None = 1,
    /// Indicate the usage of WEP Wi-Fi security
    Wep = 2,
    /// Indicate the usage of WPA Wi-Fi security
    Wpa = 3,
    /// Indicate the usage of WPA2 Wi-Fi security
    Wpa2 = 4,
    /// Indicate the usage of WPA3 Wi-Fi security
    Wpa3 = 5,
}

impl SecurityType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(SecurityType::Unspecified),
            1 => Some(SecurityType::None),
            2 => Some(SecurityType::Wep),
            3 => Some(SecurityType::Wpa),
            4 => Some(SecurityType::Wpa2),
            5 => Some(SecurityType::Wpa3),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum WiFiVersion {
    /// Indicate the network interface is currently using IEEE 802.11a against the wireless access point.
    A = 0,
    /// Indicate the network interface is currently using IEEE 802.11b against the wireless access point.
    B = 1,
    /// Indicate the network interface is currently using IEEE 802.11g against the wireless access point.
    G = 2,
    /// Indicate the network interface is currently using IEEE 802.11n against the wireless access point.
    N = 3,
    /// Indicate the network interface is currently using IEEE 802.11ac against the wireless access point.
    Ac = 4,
    /// Indicate the network interface is currently using IEEE 802.11ax against the wireless access point.
    Ax = 5,
    /// Indicate the network interface is currently using IEEE 802.11ah against the wireless access point.
    Ah = 6,
}

impl WiFiVersion {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(WiFiVersion::A),
            1 => Some(WiFiVersion::B),
            2 => Some(WiFiVersion::G),
            3 => Some(WiFiVersion::N),
            4 => Some(WiFiVersion::Ac),
            5 => Some(WiFiVersion::Ax),
            6 => Some(WiFiVersion::Ah),
            _ => None,
        }
    }

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

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

// Command encoders

// Attribute decoders

/// Decode BSSID attribute (0x0000)
pub fn decode_bssid(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Vec<u8>>> {
    if let tlv::TlvItemValue::OctetString(v) = inp {
        Ok(Some(v.clone()))
    } else {
        Ok(None)
    }
}

/// Decode SecurityType attribute (0x0001)
pub fn decode_security_type(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<SecurityType>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(SecurityType::from_u8(*v as u8))
    } else {
        Ok(None)
    }
}

/// Decode WiFiVersion attribute (0x0002)
pub fn decode_wifi_version(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<WiFiVersion>> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(WiFiVersion::from_u8(*v as u8))
    } else {
        Ok(None)
    }
}

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

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

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

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

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

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

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

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

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

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


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

    match attribute_id {
        0x0000 => {
            match decode_bssid(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_security_type(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_wifi_version(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_channel_number(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_rssi(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_beacon_lost_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_beacon_rx_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_packet_multicast_rx_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_packet_multicast_tx_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_packet_unicast_rx_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_packet_unicast_tx_count(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000B => {
            match decode_current_max_rate(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000C => {
            match decode_overrun_count(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, "BSSID"),
        (0x0001, "SecurityType"),
        (0x0002, "WiFiVersion"),
        (0x0003, "ChannelNumber"),
        (0x0004, "RSSI"),
        (0x0005, "BeaconLostCount"),
        (0x0006, "BeaconRxCount"),
        (0x0007, "PacketMulticastRxCount"),
        (0x0008, "PacketMulticastTxCount"),
        (0x0009, "PacketUnicastRxCount"),
        (0x000A, "PacketUnicastTxCount"),
        (0x000B, "CurrentMaxRate"),
        (0x000C, "OverrunCount"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct DisconnectionEvent {
    pub reason_code: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct AssociationFailureEvent {
    pub association_failure_cause: Option<AssociationFailureCause>,
    pub status: Option<u16>,
}

#[derive(Debug, serde::Serialize)]
pub struct ConnectionStatusEvent {
    pub connection_status: Option<ConnectionStatus>,
}

// Event decoders

/// Decode Disconnection event (0x00, priority: info)
pub fn decode_disconnection_event(inp: &tlv::TlvItemValue) -> anyhow::Result<DisconnectionEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(DisconnectionEvent {
                                reason_code: item.get_int(&[0]).map(|v| v as u16),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode AssociationFailure event (0x01, priority: info)
pub fn decode_association_failure_event(inp: &tlv::TlvItemValue) -> anyhow::Result<AssociationFailureEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(AssociationFailureEvent {
                                association_failure_cause: item.get_int(&[0]).and_then(|v| AssociationFailureCause::from_u8(v as u8)),
                                status: item.get_int(&[1]).map(|v| v as u16),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ConnectionStatus event (0x02, priority: info)
pub fn decode_connection_status_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ConnectionStatusEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ConnectionStatusEvent {
                                connection_status: item.get_int(&[0]).and_then(|v| ConnectionStatus::from_u8(v as u8)),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}