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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! Matter TLV encoders and decoders for Media Playback Cluster
//! Cluster ID: 0x0506
//!
//! This file is automatically generated from MediaPlayback.xml

#![allow(clippy::too_many_arguments)]

use crate::tlv;
use anyhow;
use serde_json;


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};

// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Characteristic {
    /// Textual information meant for display when no other text representation is selected. It is used to clarify dialogue, alternate languages, texted graphics or location/person IDs that are not otherwise covered in the dubbed/localized audio.
    Forcedsubtitles = 0,
    /// Textual or audio media component containing a textual description (intended for audio synthesis) or an audio description describing a visual component
    Describesvideo = 1,
    /// Simplified or reduced captions as specified in [United States Code Title 47 CFR 79.103(c)(9)].
    Easytoread = 2,
    /// A media characteristic that indicates that a track selection option includes frame-based content.
    Framebased = 3,
    /// Main media component(s) which is/are intended for presentation if no other information is provided
    Mainprogram = 4,
    /// A media characteristic that indicates that a track or media selection option contains original content.
    Originalcontent = 5,
    /// A media characteristic that indicates that a track or media selection option contains a language translation and verbal interpretation of spoken dialog.
    Voiceovertranslation = 6,
    /// Textual media component containing transcriptions of spoken dialog and auditory cues such as sound effects and music for the hearing impaired.
    Caption = 7,
    /// Textual transcriptions of spoken dialog.
    Subtitle = 8,
    /// Textual media component containing transcriptions of spoken dialog and auditory cues such as sound effects and music for the hearing impaired.
    Alternate = 9,
    /// Media content component that is supplementary to a media content component of a different media component type.
    Supplementary = 10,
    /// Experience that contains a commentary (e.g. director’s commentary) (typically audio)
    Commentary = 11,
    /// Experience that contains an element that is presented in a different language from the original (e.g. dubbed audio, translated captions)
    Dubbedtranslation = 12,
    /// Textual or audio media component containing a textual description (intended for audio synthesis) or an audio description describing a visual component
    Description = 13,
    /// Media component containing information intended to be processed by application specific elements.
    Metadata = 14,
    /// Experience containing an element for improved intelligibility of the dialogue.
    Enhancedaudiointelligibility = 15,
    /// Experience that provides information, about a current emergency, that is intended to enable the protection of life, health, safety, and property, and may also include critical details regarding the emergency and how to respond to the emergency.
    Emergency = 16,
    /// Textual representation of a songs’ lyrics, usually in the same language as the associated song as specified in [SMPTE ST 2067-2].
    Karaoke = 17,
}

impl Characteristic {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Characteristic::Forcedsubtitles),
            1 => Some(Characteristic::Describesvideo),
            2 => Some(Characteristic::Easytoread),
            3 => Some(Characteristic::Framebased),
            4 => Some(Characteristic::Mainprogram),
            5 => Some(Characteristic::Originalcontent),
            6 => Some(Characteristic::Voiceovertranslation),
            7 => Some(Characteristic::Caption),
            8 => Some(Characteristic::Subtitle),
            9 => Some(Characteristic::Alternate),
            10 => Some(Characteristic::Supplementary),
            11 => Some(Characteristic::Commentary),
            12 => Some(Characteristic::Dubbedtranslation),
            13 => Some(Characteristic::Description),
            14 => Some(Characteristic::Metadata),
            15 => Some(Characteristic::Enhancedaudiointelligibility),
            16 => Some(Characteristic::Emergency),
            17 => Some(Characteristic::Karaoke),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum PlaybackState {
    /// Media is currently playing (includes FF and REW)
    Playing = 0,
    /// Media is currently paused
    Paused = 1,
    /// Media is not currently playing
    Notplaying = 2,
    /// Media is not currently buffering and playback will start when buffer has been filled
    Buffering = 3,
}

impl PlaybackState {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(PlaybackState::Playing),
            1 => Some(PlaybackState::Paused),
            2 => Some(PlaybackState::Notplaying),
            3 => Some(PlaybackState::Buffering),
            _ => None,
        }
    }

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

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Status {
    /// Succeeded
    Success = 0,
    /// Requested playback command is invalid in the current playback state.
    Invalidstateforcommand = 1,
    /// Requested playback command is not allowed in the current playback state. For example, attempting to fast-forward during a commercial might return NotAllowed.
    Notallowed = 2,
    /// This endpoint is not active for playback.
    Notactive = 3,
    /// The FastForward or Rewind Command was issued but the media is already playing back at the fastest speed supported by the server in the respective direction.
    Speedoutofrange = 4,
    /// The Seek Command was issued with a value of position outside of the allowed seek range of the media.
    Seekoutofrange = 5,
}

impl Status {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Status::Success),
            1 => Some(Status::Invalidstateforcommand),
            2 => Some(Status::Notallowed),
            3 => Some(Status::Notactive),
            4 => Some(Status::Speedoutofrange),
            5 => Some(Status::Seekoutofrange),
            _ => 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
    }
}

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct PlaybackPosition {
    pub updated_at: Option<u64>,
    pub position: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct TrackAttributes {
    pub language_code: Option<String>,
    pub characteristics: Option<Vec<Characteristic>>,
    pub display_name: Option<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct Track {
    pub id: Option<String>,
    pub track_attributes: Option<TrackAttributes>,
}

// Command encoders

/// Encode Rewind command (0x06)
pub fn encode_rewind(audio_advance_unmuted: bool) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Bool(audio_advance_unmuted)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode FastForward command (0x07)
pub fn encode_fast_forward(audio_advance_unmuted: bool) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::Bool(audio_advance_unmuted)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SkipForward command (0x08)
pub fn encode_skip_forward(delta_position_milliseconds: u64) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(delta_position_milliseconds)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode SkipBackward command (0x09)
pub fn encode_skip_backward(delta_position_milliseconds: u64) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(delta_position_milliseconds)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode Seek command (0x0B)
pub fn encode_seek(position: u64) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt64(position)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode ActivateAudioTrack command (0x0C)
pub fn encode_activate_audio_track(track_id: String, audio_output_index: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::String(track_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(audio_output_index.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

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

// Attribute decoders

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

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

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

/// Decode SampledPosition attribute (0x0003)
pub fn decode_sampled_position(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<PlaybackPosition>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(PlaybackPosition {
                updated_at: item.get_int(&[0]),
                position: item.get_int(&[1]),
        }))
    //} 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 PlaybackSpeed attribute (0x0004)
pub fn decode_playback_speed(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}

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

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

/// Decode ActiveAudioTrack attribute (0x0007)
pub fn decode_active_audio_track(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Track>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(Track {
                id: item.get_string_owned(&[0]),
                track_attributes: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TrackAttributes {
                language_code: nested_item.get_string_owned(&[0]),
                characteristics: {
                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[1]) {
                        let items: Vec<Characteristic> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Characteristic::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                display_name: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        }))
    //} 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 AvailableAudioTracks attribute (0x0008)
pub fn decode_available_audio_tracks(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Track>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Track {
                id: item.get_string_owned(&[0]),
                track_attributes: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TrackAttributes {
                language_code: nested_item.get_string_owned(&[0]),
                characteristics: {
                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[1]) {
                        let items: Vec<Characteristic> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Characteristic::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                display_name: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}

/// Decode ActiveTextTrack attribute (0x0009)
pub fn decode_active_text_track(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<Track>> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        // Struct with fields
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(Some(Track {
                id: item.get_string_owned(&[0]),
                track_attributes: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TrackAttributes {
                language_code: nested_item.get_string_owned(&[0]),
                characteristics: {
                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[1]) {
                        let items: Vec<Characteristic> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Characteristic::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                display_name: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
        }))
    //} 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 AvailableTextTracks attribute (0x000A)
pub fn decode_available_text_tracks(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<Track>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(Track {
                id: item.get_string_owned(&[0]),
                track_attributes: {
                    if let Some(nested_tlv) = item.get(&[1]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
                            Some(TrackAttributes {
                language_code: nested_item.get_string_owned(&[0]),
                characteristics: {
                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[1]) {
                        let items: Vec<Characteristic> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { Characteristic::from_u8(*v as u8) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                display_name: nested_item.get_string_owned(&[2]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}


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

    match attribute_id {
        0x0000 => {
            match decode_current_state(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_start_time(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_duration(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_sampled_position(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0004 => {
            match decode_playback_speed(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0005 => {
            match decode_seek_range_end(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0006 => {
            match decode_seek_range_start(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0007 => {
            match decode_active_audio_track(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0008 => {
            match decode_available_audio_tracks(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0009 => {
            match decode_active_text_track(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x000A => {
            match decode_available_text_tracks(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, "CurrentState"),
        (0x0001, "StartTime"),
        (0x0002, "Duration"),
        (0x0003, "SampledPosition"),
        (0x0004, "PlaybackSpeed"),
        (0x0005, "SeekRangeEnd"),
        (0x0006, "SeekRangeStart"),
        (0x0007, "ActiveAudioTrack"),
        (0x0008, "AvailableAudioTracks"),
        (0x0009, "ActiveTextTrack"),
        (0x000A, "AvailableTextTracks"),
    ]
}

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "Play"),
        (0x01, "Pause"),
        (0x02, "Stop"),
        (0x03, "StartOver"),
        (0x04, "Previous"),
        (0x05, "Next"),
        (0x06, "Rewind"),
        (0x07, "FastForward"),
        (0x08, "SkipForward"),
        (0x09, "SkipBackward"),
        (0x0B, "Seek"),
        (0x0C, "ActivateAudioTrack"),
        (0x0D, "ActivateTextTrack"),
        (0x0E, "DeactivateTextTrack"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("Play"),
        0x01 => Some("Pause"),
        0x02 => Some("Stop"),
        0x03 => Some("StartOver"),
        0x04 => Some("Previous"),
        0x05 => Some("Next"),
        0x06 => Some("Rewind"),
        0x07 => Some("FastForward"),
        0x08 => Some("SkipForward"),
        0x09 => Some("SkipBackward"),
        0x0B => Some("Seek"),
        0x0C => Some("ActivateAudioTrack"),
        0x0D => Some("ActivateTextTrack"),
        0x0E => Some("DeactivateTextTrack"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![]),
        0x01 => Some(vec![]),
        0x02 => Some(vec![]),
        0x03 => Some(vec![]),
        0x04 => Some(vec![]),
        0x05 => Some(vec![]),
        0x06 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "audio_advance_unmuted", kind: crate::clusters::codec::FieldKind::Bool, optional: false, nullable: false },
        ]),
        0x07 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "audio_advance_unmuted", kind: crate::clusters::codec::FieldKind::Bool, optional: false, nullable: false },
        ]),
        0x08 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "delta_position_milliseconds", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
        ]),
        0x09 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "delta_position_milliseconds", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
        ]),
        0x0B => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "position", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
        ]),
        0x0C => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "track_id", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "audio_output_index", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: true },
        ]),
        0x0D => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "track_id", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
        ]),
        0x0E => 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 => Ok(vec![]),
        0x02 => Ok(vec![]),
        0x03 => Ok(vec![]),
        0x04 => Ok(vec![]),
        0x05 => Ok(vec![]),
        0x06 => {
        let audio_advance_unmuted = crate::clusters::codec::json_util::get_bool(args, "audio_advance_unmuted")?;
        encode_rewind(audio_advance_unmuted)
        }
        0x07 => {
        let audio_advance_unmuted = crate::clusters::codec::json_util::get_bool(args, "audio_advance_unmuted")?;
        encode_fast_forward(audio_advance_unmuted)
        }
        0x08 => {
        let delta_position_milliseconds = crate::clusters::codec::json_util::get_u64(args, "delta_position_milliseconds")?;
        encode_skip_forward(delta_position_milliseconds)
        }
        0x09 => {
        let delta_position_milliseconds = crate::clusters::codec::json_util::get_u64(args, "delta_position_milliseconds")?;
        encode_skip_backward(delta_position_milliseconds)
        }
        0x0B => {
        let position = crate::clusters::codec::json_util::get_u64(args, "position")?;
        encode_seek(position)
        }
        0x0C => {
        let track_id = crate::clusters::codec::json_util::get_string(args, "track_id")?;
        let audio_output_index = crate::clusters::codec::json_util::get_opt_u8(args, "audio_output_index")?;
        encode_activate_audio_track(track_id, audio_output_index)
        }
        0x0D => {
        let track_id = crate::clusters::codec::json_util::get_string(args, "track_id")?;
        encode_activate_text_track(track_id)
        }
        0x0E => Ok(vec![]),
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

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

// Command response decoders

/// Decode PlaybackResponse command response (0A)
pub fn decode_playback_response(inp: &tlv::TlvItemValue) -> anyhow::Result<PlaybackResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(PlaybackResponse {
                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"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `Play` command on cluster `Media Playback`.
pub async fn play(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_PLAY, &[]).await?;
    decode_playback_response(&tlv)
}

/// Invoke `Pause` command on cluster `Media Playback`.
pub async fn pause(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_PAUSE, &[]).await?;
    decode_playback_response(&tlv)
}

/// Invoke `Stop` command on cluster `Media Playback`.
pub async fn stop(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_STOP, &[]).await?;
    decode_playback_response(&tlv)
}

/// Invoke `StartOver` command on cluster `Media Playback`.
pub async fn start_over(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_STARTOVER, &[]).await?;
    decode_playback_response(&tlv)
}

/// Invoke `Previous` command on cluster `Media Playback`.
pub async fn previous(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_PREVIOUS, &[]).await?;
    decode_playback_response(&tlv)
}

/// Invoke `Next` command on cluster `Media Playback`.
pub async fn next(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_NEXT, &[]).await?;
    decode_playback_response(&tlv)
}

/// Invoke `Rewind` command on cluster `Media Playback`.
pub async fn rewind(conn: &crate::controller::Connection, endpoint: u16, audio_advance_unmuted: bool) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_REWIND, &encode_rewind(audio_advance_unmuted)?).await?;
    decode_playback_response(&tlv)
}

/// Invoke `FastForward` command on cluster `Media Playback`.
pub async fn fast_forward(conn: &crate::controller::Connection, endpoint: u16, audio_advance_unmuted: bool) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_FASTFORWARD, &encode_fast_forward(audio_advance_unmuted)?).await?;
    decode_playback_response(&tlv)
}

/// Invoke `SkipForward` command on cluster `Media Playback`.
pub async fn skip_forward(conn: &crate::controller::Connection, endpoint: u16, delta_position_milliseconds: u64) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_SKIPFORWARD, &encode_skip_forward(delta_position_milliseconds)?).await?;
    decode_playback_response(&tlv)
}

/// Invoke `SkipBackward` command on cluster `Media Playback`.
pub async fn skip_backward(conn: &crate::controller::Connection, endpoint: u16, delta_position_milliseconds: u64) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_SKIPBACKWARD, &encode_skip_backward(delta_position_milliseconds)?).await?;
    decode_playback_response(&tlv)
}

/// Invoke `Seek` command on cluster `Media Playback`.
pub async fn seek(conn: &crate::controller::Connection, endpoint: u16, position: u64) -> anyhow::Result<PlaybackResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_SEEK, &encode_seek(position)?).await?;
    decode_playback_response(&tlv)
}

/// Invoke `ActivateAudioTrack` command on cluster `Media Playback`.
pub async fn activate_audio_track(conn: &crate::controller::Connection, endpoint: u16, track_id: String, audio_output_index: Option<u8>) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_ACTIVATEAUDIOTRACK, &encode_activate_audio_track(track_id, audio_output_index)?).await?;
    Ok(())
}

/// Invoke `ActivateTextTrack` command on cluster `Media Playback`.
pub async fn activate_text_track(conn: &crate::controller::Connection, endpoint: u16, track_id: String) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_ACTIVATETEXTTRACK, &encode_activate_text_track(track_id)?).await?;
    Ok(())
}

/// Invoke `DeactivateTextTrack` command on cluster `Media Playback`.
pub async fn deactivate_text_track(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_CMD_ID_DEACTIVATETEXTTRACK, &[]).await?;
    Ok(())
}

/// Read `CurrentState` attribute from cluster `Media Playback`.
pub async fn read_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<PlaybackState> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_CURRENTSTATE).await?;
    decode_current_state(&tlv)
}

/// Read `StartTime` attribute from cluster `Media Playback`.
pub async fn read_start_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_STARTTIME).await?;
    decode_start_time(&tlv)
}

/// Read `Duration` attribute from cluster `Media Playback`.
pub async fn read_duration(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_DURATION).await?;
    decode_duration(&tlv)
}

/// Read `SampledPosition` attribute from cluster `Media Playback`.
pub async fn read_sampled_position(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<PlaybackPosition>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_SAMPLEDPOSITION).await?;
    decode_sampled_position(&tlv)
}

/// Read `PlaybackSpeed` attribute from cluster `Media Playback`.
pub async fn read_playback_speed(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_PLAYBACKSPEED).await?;
    decode_playback_speed(&tlv)
}

/// Read `SeekRangeEnd` attribute from cluster `Media Playback`.
pub async fn read_seek_range_end(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_SEEKRANGEEND).await?;
    decode_seek_range_end(&tlv)
}

/// Read `SeekRangeStart` attribute from cluster `Media Playback`.
pub async fn read_seek_range_start(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_SEEKRANGESTART).await?;
    decode_seek_range_start(&tlv)
}

/// Read `ActiveAudioTrack` attribute from cluster `Media Playback`.
pub async fn read_active_audio_track(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Track>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_ACTIVEAUDIOTRACK).await?;
    decode_active_audio_track(&tlv)
}

/// Read `AvailableAudioTracks` attribute from cluster `Media Playback`.
pub async fn read_available_audio_tracks(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Track>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_AVAILABLEAUDIOTRACKS).await?;
    decode_available_audio_tracks(&tlv)
}

/// Read `ActiveTextTrack` attribute from cluster `Media Playback`.
pub async fn read_active_text_track(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<Track>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_ACTIVETEXTTRACK).await?;
    decode_active_text_track(&tlv)
}

/// Read `AvailableTextTracks` attribute from cluster `Media Playback`.
pub async fn read_available_text_tracks(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<Track>> {
    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MEDIA_PLAYBACK, crate::clusters::defs::CLUSTER_MEDIA_PLAYBACK_ATTR_ID_AVAILABLETEXTTRACKS).await?;
    decode_available_text_tracks(&tlv)
}

#[derive(Debug, serde::Serialize)]
pub struct StateChangedEvent {
    pub current_state: Option<PlaybackState>,
    pub start_time: Option<u64>,
    pub duration: Option<u64>,
    pub sampled_position: Option<PlaybackPosition>,
    pub playback_speed: Option<u8>,
    pub seek_range_end: Option<u64>,
    pub seek_range_start: Option<u64>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub data: Option<Vec<u8>>,
    pub audio_advance_unmuted: Option<bool>,
}

// Event decoders

/// Decode StateChanged event (0x00, priority: info)
pub fn decode_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<StateChangedEvent> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(StateChangedEvent {
                                current_state: item.get_int(&[0]).and_then(|v| PlaybackState::from_u8(v as u8)),
                                start_time: item.get_int(&[1]),
                                duration: item.get_int(&[2]),
                                sampled_position: {
                    if let Some(nested_tlv) = item.get(&[3]) {
                        if let tlv::TlvItemValue::List(_) = nested_tlv {
                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
                            Some(PlaybackPosition {
                updated_at: nested_item.get_int(&[0]),
                position: nested_item.get_int(&[1]),
                            })
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                },
                                playback_speed: item.get_int(&[4]).map(|v| v as u8),
                                seek_range_end: item.get_int(&[5]),
                                seek_range_start: item.get_int(&[6]),
                                data: item.get_octet_string_owned(&[7]),
                                audio_advance_unmuted: item.get_bool(&[8]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}