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
//! Matter TLV encoders and decoders for Channel Cluster
//! Cluster ID: 0x0504
//!
//! This file is automatically generated from Channel.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 ChannelType {
    /// The channel is sourced from a satellite provider.
    Satellite = 0,
    /// The channel is sourced from a cable provider.
    Cable = 1,
    /// The channel is sourced from a terrestrial provider.
    Terrestrial = 2,
    /// The channel is sourced from an OTT provider.
    Ott = 3,
}

impl ChannelType {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ChannelType::Satellite),
            1 => Some(ChannelType::Cable),
            2 => Some(ChannelType::Terrestrial),
            3 => Some(ChannelType::Ott),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum LineupInfoType {
    /// Multi System Operator
    Mso = 0,
}

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

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Status {
    /// Command succeeded
    Success = 0,
    /// More than one equal match for the ChannelInfoStruct passed in.
    Multiplematches = 1,
    /// No matches for the ChannelInfoStruct passed in.
    Nomatches = 2,
}

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

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

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

// Bitmap definitions

/// RecordingFlag bitmap type
pub type RecordingFlag = u8;

/// Constants for RecordingFlag
pub mod recordingflag {
    /// The program is scheduled for recording.
    pub const SCHEDULED: u8 = 0x01;
    /// The program series is scheduled for recording.
    pub const RECORD_SERIES: u8 = 0x02;
    /// The program is recorded and available to be played.
    pub const RECORDED: u8 = 0x04;
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct ChannelInfo {
    pub major_number: Option<u16>,
    pub minor_number: Option<u16>,
    pub name: Option<String>,
    pub call_sign: Option<String>,
    pub affiliate_call_sign: Option<String>,
    pub identifier: Option<String>,
    pub type_: Option<ChannelType>,
}

#[derive(Debug, serde::Serialize)]
pub struct ChannelPaging {
    pub previous_token: Option<PageToken>,
    pub next_token: Option<PageToken>,
}

#[derive(Debug, serde::Serialize)]
pub struct LineupInfo {
    pub operator_name: Option<String>,
    pub lineup_name: Option<String>,
    pub postal_code: Option<String>,
    pub lineup_info_type: Option<LineupInfoType>,
}

#[derive(Debug, serde::Serialize)]
pub struct PageToken {
    pub limit: Option<u16>,
    pub after: Option<String>,
    pub before: Option<String>,
}

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

#[derive(Debug, serde::Serialize)]
pub struct ProgramCategory {
    pub category: Option<String>,
    pub sub_category: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct Program {
    pub identifier: Option<String>,
    pub channel: Option<ChannelInfo>,
    pub start_time: Option<u64>,
    pub end_time: Option<u64>,
    pub title: Option<String>,
    pub subtitle: Option<String>,
    pub description: Option<String>,
    pub audio_languages: Option<Vec<String>>,
    pub ratings: Option<Vec<String>>,
    pub thumbnail_url: Option<String>,
    pub poster_art_url: Option<String>,
    pub dvbi_url: Option<String>,
    pub release_date: Option<String>,
    pub parental_guidance_text: Option<String>,
    pub recording_flag: Option<RecordingFlag>,
    pub series_info: Option<SeriesInfo>,
    pub category_list: Option<Vec<ProgramCategory>>,
    pub cast_list: Option<Vec<ProgramCast>>,
}

#[derive(Debug, serde::Serialize)]
pub struct SeriesInfo {
    pub season: Option<String>,
    pub episode: Option<String>,
}

// Command encoders

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

/// Encode ChangeChannelByNumber command (0x02)
pub fn encode_change_channel_by_number(major_number: u16, minor_number: u16) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt16(major_number)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(minor_number)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SkipChannel command (0x03)
pub fn encode_skip_channel(count: i16) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Int16(count)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode GetProgramGuide command (0x04)
pub fn encode_get_program_guide(start_time: u64, end_time: u64, channel_list: Vec<ChannelInfo>, page_token: Option<PageToken>, recording_flag: Option<RecordingFlag>, data: Vec<u8>) -> anyhow::Result<Vec<u8>> {
            // Encode optional struct PageTokenStruct
            let page_token_enc = if let Some(s) = page_token {
                let mut fields = Vec::new();
                if let Some(x) = s.limit { fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                if let Some(x) = s.after { fields.push((1, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                if let Some(x) = s.before { fields.push((2, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                tlv::TlvItemValueEnc::StructInvisible(fields)
            } else {
                tlv::TlvItemValueEnc::StructInvisible(Vec::new())
            };
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(start_time)).into(),
        (1, tlv::TlvItemValueEnc::UInt64(end_time)).into(),
        (2, tlv::TlvItemValueEnc::Array(channel_list.into_iter().map(|v| {
                    let mut fields = Vec::new();
                    if let Some(x) = v.major_number { fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.minor_number { fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
                    if let Some(x) = v.name { fields.push((2, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    if let Some(x) = v.call_sign { fields.push((3, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    if let Some(x) = v.affiliate_call_sign { fields.push((4, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    if let Some(x) = v.identifier { fields.push((5, tlv::TlvItemValueEnc::String(x.clone())).into()); }
                    if let Some(x) = v.type_ { fields.push((6, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
                    (0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
                }).collect())).into(),
        (3, page_token_enc).into(),
        (5, tlv::TlvItemValueEnc::UInt8(recording_flag.unwrap_or_default())).into(),
        (7, tlv::TlvItemValueEnc::OctetString(data)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RecordProgram command (0x06)
pub fn encode_record_program(program_identifier: String, should_record_series: bool, data: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::String(program_identifier)).into(),
        (1, tlv::TlvItemValueEnc::Bool(should_record_series)).into(),
        (3, tlv::TlvItemValueEnc::OctetString(data)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode CancelRecordProgram command (0x07)
pub fn encode_cancel_record_program(program_identifier: String, should_record_series: bool, data: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::String(program_identifier)).into(),
        (1, tlv::TlvItemValueEnc::Bool(should_record_series)).into(),
        (3, tlv::TlvItemValueEnc::OctetString(data)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode ChannelList attribute (0x0000)
pub fn decode_channel_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ChannelInfo>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(ChannelInfo {
                major_number: item.get_int(&[0]).map(|v| v as u16),
                minor_number: item.get_int(&[1]).map(|v| v as u16),
                name: item.get_string_owned(&[2]),
                call_sign: item.get_string_owned(&[3]),
                affiliate_call_sign: item.get_string_owned(&[4]),
                identifier: item.get_string_owned(&[5]),
                type_: item.get_int(&[6]).and_then(|v| ChannelType::from_u8(v as u8)),
            });
        }
    }
    Ok(res)
}

/// Decode Lineup attribute (0x0001)
pub fn decode_lineup(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<LineupInfo>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(LineupInfo {
                operator_name: item.get_string_owned(&[0]),
                lineup_name: item.get_string_owned(&[1]),
                postal_code: item.get_string_owned(&[2]),
                lineup_info_type: item.get_int(&[3]).and_then(|v| LineupInfoType::from_u8(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 CurrentChannel attribute (0x0002)
pub fn decode_current_channel(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<ChannelInfo>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(ChannelInfo {
                major_number: item.get_int(&[0]).map(|v| v as u16),
                minor_number: item.get_int(&[1]).map(|v| v as u16),
                name: item.get_string_owned(&[2]),
                call_sign: item.get_string_owned(&[3]),
                affiliate_call_sign: item.get_string_owned(&[4]),
                identifier: item.get_string_owned(&[5]),
                type_: item.get_int(&[6]).and_then(|v| ChannelType::from_u8(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"))
    }
}


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

    match attribute_id {
        0x0000 => {
            match decode_channel_list(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_lineup(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_current_channel(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, "ChannelList"),
        (0x0001, "Lineup"),
        (0x0002, "CurrentChannel"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct ChangeChannelResponse {
    pub status: Option<Status>,
    pub data: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct ProgramGuideResponse {
    pub paging: Option<ChannelPaging>,
    pub program_list: Option<Vec<Program>>,
}

// Command response decoders

/// Decode ChangeChannelResponse command response (01)
pub fn decode_change_channel_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ChangeChannelResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ChangeChannelResponse {
                status: item.get_int(&[0]).and_then(|v| Status::from_u8(v as u8)),
                data: item.get_string_owned(&[1]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ProgramGuideResponse command response (05)
pub fn decode_program_guide_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ProgramGuideResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ProgramGuideResponse {
                paging: {
                    if let Some(nested_tlv) = item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(ChannelPaging {
                previous_token: {
                    if let Some(nested_tlv) = nested_item.get(&[0]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
                            Some(PageToken {
                limit: nested_item.get_int(&[0]).map(|v| v as u16),
                after: nested_item.get_string_owned(&[1]),
                before: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                next_token: {
                    if let Some(nested_tlv) = nested_item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(PageToken {
                limit: nested_item.get_int(&[0]).map(|v| v as u16),
                after: nested_item.get_string_owned(&[1]),
                before: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                program_list: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[1]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(Program {
                identifier: list_item.get_string_owned(&[0]),
                channel: {
                    if let Some(nested_tlv) = list_item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(ChannelInfo {
                major_number: nested_item.get_int(&[0]).map(|v| v as u16),
                minor_number: nested_item.get_int(&[1]).map(|v| v as u16),
                name: nested_item.get_string_owned(&[2]),
                call_sign: nested_item.get_string_owned(&[3]),
                affiliate_call_sign: nested_item.get_string_owned(&[4]),
                identifier: nested_item.get_string_owned(&[5]),
                type_: nested_item.get_int(&[6]).and_then(|v| ChannelType::from_u8(v as u8)),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                start_time: list_item.get_int(&[2]),
                end_time: list_item.get_int(&[3]),
                title: list_item.get_string_owned(&[4]),
                subtitle: list_item.get_string_owned(&[5]),
                description: list_item.get_string_owned(&[6]),
                audio_languages: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[7]) {
                        let items: Vec<String> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::String(v) = &e.value { Some(v.clone()) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                ratings: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[8]) {
                        let items: Vec<String> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::String(v) = &e.value { Some(v.clone()) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                thumbnail_url: list_item.get_string_owned(&[9]),
                poster_art_url: list_item.get_string_owned(&[10]),
                dvbi_url: list_item.get_string_owned(&[11]),
                release_date: list_item.get_string_owned(&[12]),
                parental_guidance_text: list_item.get_string_owned(&[13]),
                recording_flag: list_item.get_int(&[14]).map(|v| v as u8),
                series_info: {
                    if let Some(nested_tlv) = list_item.get(&[15]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 15, value: nested_tlv.clone() };
                            Some(SeriesInfo {
                season: nested_item.get_string_owned(&[0]),
                episode: nested_item.get_string_owned(&[1]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                category_list: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[16]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(ProgramCategory {
                category: list_item.get_string_owned(&[0]),
                sub_category: list_item.get_string_owned(&[1]),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                cast_list: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[17]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(ProgramCast {
                name: list_item.get_string_owned(&[0]),
                role: list_item.get_string_owned(&[1]),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}