matc/clusters/codec/
push_av_stream_transport.rs

1//! Matter TLV encoders and decoders for Push AV Stream Transport Cluster
2//! Cluster ID: 0x0555
3//!
4//! This file is automatically generated from PushAVStreamTransport.xml
5
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Import serialization helpers for octet strings
14use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
15
16// Enum definitions
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
19#[repr(u8)]
20pub enum CMAFInterface {
21    /// CMAF Interface-1 Mode
22    Interface1 = 0,
23    /// CMAF Interface-2 Mode with DASH Support
24    Interface2dash = 1,
25    /// CMAF Interface-2 Mode with HLS Support
26    Interface2hls = 2,
27}
28
29impl CMAFInterface {
30    /// Convert from u8 value
31    pub fn from_u8(value: u8) -> Option<Self> {
32        match value {
33            0 => Some(CMAFInterface::Interface1),
34            1 => Some(CMAFInterface::Interface2dash),
35            2 => Some(CMAFInterface::Interface2hls),
36            _ => None,
37        }
38    }
39
40    /// Convert to u8 value
41    pub fn to_u8(self) -> u8 {
42        self as u8
43    }
44}
45
46impl From<CMAFInterface> for u8 {
47    fn from(val: CMAFInterface) -> Self {
48        val as u8
49    }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
53#[repr(u8)]
54pub enum ContainerFormat {
55    /// CMAF container format
56    Cmaf = 0,
57}
58
59impl ContainerFormat {
60    /// Convert from u8 value
61    pub fn from_u8(value: u8) -> Option<Self> {
62        match value {
63            0 => Some(ContainerFormat::Cmaf),
64            _ => None,
65        }
66    }
67
68    /// Convert to u8 value
69    pub fn to_u8(self) -> u8 {
70        self as u8
71    }
72}
73
74impl From<ContainerFormat> for u8 {
75    fn from(val: ContainerFormat) -> Self {
76        val as u8
77    }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
81#[repr(u8)]
82pub enum IngestMethods {
83    /// CMAF ingestion format
84    Cmafingest = 0,
85}
86
87impl IngestMethods {
88    /// Convert from u8 value
89    pub fn from_u8(value: u8) -> Option<Self> {
90        match value {
91            0 => Some(IngestMethods::Cmafingest),
92            _ => None,
93        }
94    }
95
96    /// Convert to u8 value
97    pub fn to_u8(self) -> u8 {
98        self as u8
99    }
100}
101
102impl From<IngestMethods> for u8 {
103    fn from(val: IngestMethods) -> Self {
104        val as u8
105    }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
109#[repr(u8)]
110pub enum StatusCode {
111    /// The specified TLSEndpointID cannot be found.
112    Invalidtlsendpoint = 2,
113    /// The specified VideoStreamID or AudioStreamID cannot be found.
114    Invalidstream = 3,
115    /// The specified URL is invalid.
116    Invalidurl = 4,
117    /// A specified ZoneID was invalid.
118    Invalidzone = 5,
119    /// The specified combination of Ingestion method and Container format is not supported.
120    Invalidcombination = 6,
121    /// The trigger type is invalid for this command.
122    Invalidtriggertype = 7,
123    /// The Stream Transport Status is invalid for this command.
124    Invalidtransportstatus = 8,
125    /// The requested Container options are not supported with the streams indicated.
126    Invalidoptions = 9,
127    /// The requested StreamUsage is not allowed.
128    Invalidstreamusage = 10,
129    /// Time sync has not occurred yet.
130    Invalidtime = 11,
131    /// The requested pre roll length is not compatible with the streams key frame interval.
132    Invalidprerolllength = 12,
133    /// The requested Streams info contained duplicate entries.
134    Duplicatestreamvalues = 13,
135}
136
137impl StatusCode {
138    /// Convert from u8 value
139    pub fn from_u8(value: u8) -> Option<Self> {
140        match value {
141            2 => Some(StatusCode::Invalidtlsendpoint),
142            3 => Some(StatusCode::Invalidstream),
143            4 => Some(StatusCode::Invalidurl),
144            5 => Some(StatusCode::Invalidzone),
145            6 => Some(StatusCode::Invalidcombination),
146            7 => Some(StatusCode::Invalidtriggertype),
147            8 => Some(StatusCode::Invalidtransportstatus),
148            9 => Some(StatusCode::Invalidoptions),
149            10 => Some(StatusCode::Invalidstreamusage),
150            11 => Some(StatusCode::Invalidtime),
151            12 => Some(StatusCode::Invalidprerolllength),
152            13 => Some(StatusCode::Duplicatestreamvalues),
153            _ => None,
154        }
155    }
156
157    /// Convert to u8 value
158    pub fn to_u8(self) -> u8 {
159        self as u8
160    }
161}
162
163impl From<StatusCode> for u8 {
164    fn from(val: StatusCode) -> Self {
165        val as u8
166    }
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
170#[repr(u8)]
171pub enum TransportStatus {
172    /// Push Transport can transport AV Streams
173    Active = 0,
174    /// Push Transport cannot transport AV Streams
175    Inactive = 1,
176}
177
178impl TransportStatus {
179    /// Convert from u8 value
180    pub fn from_u8(value: u8) -> Option<Self> {
181        match value {
182            0 => Some(TransportStatus::Active),
183            1 => Some(TransportStatus::Inactive),
184            _ => None,
185        }
186    }
187
188    /// Convert to u8 value
189    pub fn to_u8(self) -> u8 {
190        self as u8
191    }
192}
193
194impl From<TransportStatus> for u8 {
195    fn from(val: TransportStatus) -> Self {
196        val as u8
197    }
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
201#[repr(u8)]
202pub enum TransportTriggerType {
203    /// Triggered only via a command invocation
204    Command = 0,
205    /// Triggered via motion detection or command
206    Motion = 1,
207    /// Triggered always when transport status is Active
208    Continuous = 2,
209}
210
211impl TransportTriggerType {
212    /// Convert from u8 value
213    pub fn from_u8(value: u8) -> Option<Self> {
214        match value {
215            0 => Some(TransportTriggerType::Command),
216            1 => Some(TransportTriggerType::Motion),
217            2 => Some(TransportTriggerType::Continuous),
218            _ => None,
219        }
220    }
221
222    /// Convert to u8 value
223    pub fn to_u8(self) -> u8 {
224        self as u8
225    }
226}
227
228impl From<TransportTriggerType> for u8 {
229    fn from(val: TransportTriggerType) -> Self {
230        val as u8
231    }
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
235#[repr(u8)]
236pub enum TriggerActivationReason {
237    /// Trigger has been activated by user action
238    Userinitiated = 0,
239    /// Trigger has been activated by automation
240    Automation = 1,
241    /// Trigger has been activated for emergency reasons
242    Emergency = 2,
243    /// Trigger has been activated by a doorbell press
244    Doorbellpressed = 3,
245}
246
247impl TriggerActivationReason {
248    /// Convert from u8 value
249    pub fn from_u8(value: u8) -> Option<Self> {
250        match value {
251            0 => Some(TriggerActivationReason::Userinitiated),
252            1 => Some(TriggerActivationReason::Automation),
253            2 => Some(TriggerActivationReason::Emergency),
254            3 => Some(TriggerActivationReason::Doorbellpressed),
255            _ => None,
256        }
257    }
258
259    /// Convert to u8 value
260    pub fn to_u8(self) -> u8 {
261        self as u8
262    }
263}
264
265impl From<TriggerActivationReason> for u8 {
266    fn from(val: TriggerActivationReason) -> Self {
267        val as u8
268    }
269}
270
271// Struct definitions
272
273#[derive(Debug, serde::Serialize)]
274pub struct AudioStream {
275    pub audio_stream_name: Option<String>,
276    pub audio_stream_id: Option<u8>,
277}
278
279#[derive(Debug, serde::Serialize)]
280pub struct CMAFContainerOptions {
281    pub cmaf_interface: Option<CMAFInterface>,
282    pub segment_duration: Option<u16>,
283    pub chunk_duration: Option<u16>,
284    pub session_group: Option<u8>,
285    pub track_name: Option<String>,
286    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
287    pub cenc_key: Option<Vec<u8>>,
288    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
289    pub cenc_key_id: Option<Vec<u8>>,
290    pub metadata_enabled: Option<bool>,
291}
292
293#[derive(Debug, serde::Serialize)]
294pub struct ContainerOptions {
295    pub container_type: Option<ContainerFormat>,
296    pub cmaf_container_options: Option<CMAFContainerOptions>,
297}
298
299#[derive(Debug, serde::Serialize)]
300pub struct SupportedFormat {
301    pub container_format: Option<ContainerFormat>,
302    pub ingest_method: Option<IngestMethods>,
303}
304
305#[derive(Debug, serde::Serialize)]
306pub struct TransportConfiguration {
307    pub connection_id: Option<u8>,
308    pub transport_status: Option<TransportStatus>,
309    pub transport_options: Option<TransportOptions>,
310}
311
312#[derive(Debug, serde::Serialize)]
313pub struct TransportMotionTriggerTimeControl {
314    pub initial_duration: Option<u16>,
315    pub augmentation_duration: Option<u16>,
316    pub max_duration: Option<u32>,
317    pub blind_duration: Option<u16>,
318}
319
320#[derive(Debug, serde::Serialize)]
321pub struct TransportOptions {
322    pub stream_usage: Option<u8>,
323    pub video_stream_id: Option<u8>,
324    pub audio_stream_id: Option<u8>,
325    pub tls_endpoint_id: Option<u8>,
326    pub url: Option<String>,
327    pub trigger_options: Option<TransportTriggerOptions>,
328    pub ingest_method: Option<IngestMethods>,
329    pub container_options: Option<ContainerOptions>,
330    pub expiry_time: Option<u64>,
331    pub video_streams: Option<Vec<VideoStream>>,
332    pub audio_streams: Option<Vec<AudioStream>>,
333}
334
335#[derive(Debug, serde::Serialize)]
336pub struct TransportTriggerOptions {
337    pub trigger_type: Option<TransportTriggerType>,
338    pub motion_zones: Option<Vec<TransportZoneOptions>>,
339    pub motion_sensitivity: Option<u8>,
340    pub motion_time_control: Option<TransportMotionTriggerTimeControl>,
341    pub max_pre_roll_len: Option<u16>,
342}
343
344#[derive(Debug, serde::Serialize)]
345pub struct TransportZoneOptions {
346    pub zone: Option<u8>,
347    pub sensitivity: Option<u8>,
348}
349
350#[derive(Debug, serde::Serialize)]
351pub struct VideoStream {
352    pub video_stream_name: Option<String>,
353    pub video_stream_id: Option<u8>,
354}
355
356// Command encoders
357
358/// Encode AllocatePushTransport command (0x00)
359pub fn encode_allocate_push_transport(transport_options: TransportOptions) -> anyhow::Result<Vec<u8>> {
360            // Encode struct TransportOptionsStruct
361            let mut transport_options_fields = Vec::new();
362            if let Some(x) = transport_options.stream_usage { transport_options_fields.push((0, tlv::TlvItemValueEnc::UInt8(x)).into()); }
363            // TODO: encoding for field video_stream_id (VideoStreamID) not implemented
364            // TODO: encoding for field audio_stream_id (AudioStreamID) not implemented
365            // TODO: encoding for field tls_endpoint_id (TLSEndpointID) not implemented
366            if let Some(x) = transport_options.url { transport_options_fields.push((4, tlv::TlvItemValueEnc::String(x.clone())).into()); }
367            if let Some(inner) = transport_options.trigger_options {
368                let mut trigger_options_nested_fields = Vec::new();
369                if let Some(x) = inner.trigger_type { trigger_options_nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
370                if let Some(listv) = inner.motion_zones {
371                    let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
372                        let mut nested_fields = Vec::new();
373                            // TODO: encoding for field zone (ZoneID) not implemented
374                            if let Some(x) = inner.sensitivity { nested_fields.push((1, tlv::TlvItemValueEnc::UInt8(x)).into()); }
375                        (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
376                    }).collect();
377                    trigger_options_nested_fields.push((1, tlv::TlvItemValueEnc::Array(inner_vec)).into());
378                }
379                if let Some(x) = inner.motion_sensitivity { trigger_options_nested_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
380                if let Some(inner) = inner.motion_time_control {
381                    let mut motion_time_control_nested_fields = Vec::new();
382                    if let Some(x) = inner.initial_duration { motion_time_control_nested_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
383                    if let Some(x) = inner.augmentation_duration { motion_time_control_nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
384                    if let Some(x) = inner.max_duration { motion_time_control_nested_fields.push((2, tlv::TlvItemValueEnc::UInt32(x)).into()); }
385                    if let Some(x) = inner.blind_duration { motion_time_control_nested_fields.push((3, tlv::TlvItemValueEnc::UInt16(x)).into()); }
386                    trigger_options_nested_fields.push((3, tlv::TlvItemValueEnc::StructInvisible(motion_time_control_nested_fields)).into());
387                }
388                if let Some(x) = inner.max_pre_roll_len { trigger_options_nested_fields.push((4, tlv::TlvItemValueEnc::UInt16(x)).into()); }
389                transport_options_fields.push((5, tlv::TlvItemValueEnc::StructInvisible(trigger_options_nested_fields)).into());
390            }
391            if let Some(x) = transport_options.ingest_method { transport_options_fields.push((6, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
392            if let Some(inner) = transport_options.container_options {
393                let mut container_options_nested_fields = Vec::new();
394                if let Some(x) = inner.container_type { container_options_nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
395                if let Some(inner) = inner.cmaf_container_options {
396                    let mut cmaf_container_options_nested_fields = Vec::new();
397                    if let Some(x) = inner.cmaf_interface { cmaf_container_options_nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
398                    if let Some(x) = inner.segment_duration { cmaf_container_options_nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
399                    if let Some(x) = inner.chunk_duration { cmaf_container_options_nested_fields.push((2, tlv::TlvItemValueEnc::UInt16(x)).into()); }
400                    if let Some(x) = inner.session_group { cmaf_container_options_nested_fields.push((3, tlv::TlvItemValueEnc::UInt8(x)).into()); }
401                    if let Some(x) = inner.track_name { cmaf_container_options_nested_fields.push((4, tlv::TlvItemValueEnc::String(x.clone())).into()); }
402                    if let Some(x) = inner.cenc_key { cmaf_container_options_nested_fields.push((5, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
403                    if let Some(x) = inner.cenc_key_id { cmaf_container_options_nested_fields.push((6, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
404                    if let Some(x) = inner.metadata_enabled { cmaf_container_options_nested_fields.push((7, tlv::TlvItemValueEnc::Bool(x)).into()); }
405                    container_options_nested_fields.push((1, tlv::TlvItemValueEnc::StructInvisible(cmaf_container_options_nested_fields)).into());
406                }
407                transport_options_fields.push((7, tlv::TlvItemValueEnc::StructInvisible(container_options_nested_fields)).into());
408            }
409            if let Some(x) = transport_options.expiry_time { transport_options_fields.push((8, tlv::TlvItemValueEnc::UInt64(x)).into()); }
410            if let Some(listv) = transport_options.video_streams {
411                let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
412                    let mut nested_fields = Vec::new();
413                        if let Some(x) = inner.video_stream_name { nested_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
414                        // TODO: encoding for field video_stream_id (VideoStreamID) not implemented
415                    (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
416                }).collect();
417                transport_options_fields.push((9, tlv::TlvItemValueEnc::Array(inner_vec)).into());
418            }
419            if let Some(listv) = transport_options.audio_streams {
420                let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
421                    let mut nested_fields = Vec::new();
422                        if let Some(x) = inner.audio_stream_name { nested_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
423                        // TODO: encoding for field audio_stream_id (AudioStreamID) not implemented
424                    (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
425                }).collect();
426                transport_options_fields.push((10, tlv::TlvItemValueEnc::Array(inner_vec)).into());
427            }
428    let tlv = tlv::TlvItemEnc {
429        tag: 0,
430        value: tlv::TlvItemValueEnc::StructInvisible(vec![
431        (0, tlv::TlvItemValueEnc::StructInvisible(transport_options_fields)).into(),
432        ]),
433    };
434    Ok(tlv.encode()?)
435}
436
437/// Encode DeallocatePushTransport command (0x02)
438pub fn encode_deallocate_push_transport(connection_id: u8) -> anyhow::Result<Vec<u8>> {
439    let tlv = tlv::TlvItemEnc {
440        tag: 0,
441        value: tlv::TlvItemValueEnc::StructInvisible(vec![
442        (0, tlv::TlvItemValueEnc::UInt8(connection_id)).into(),
443        ]),
444    };
445    Ok(tlv.encode()?)
446}
447
448/// Encode ModifyPushTransport command (0x03)
449pub fn encode_modify_push_transport(connection_id: u8, transport_options: TransportOptions) -> anyhow::Result<Vec<u8>> {
450            // Encode struct TransportOptionsStruct
451            let mut transport_options_fields = Vec::new();
452            if let Some(x) = transport_options.stream_usage { transport_options_fields.push((0, tlv::TlvItemValueEnc::UInt8(x)).into()); }
453            // TODO: encoding for field video_stream_id (VideoStreamID) not implemented
454            // TODO: encoding for field audio_stream_id (AudioStreamID) not implemented
455            // TODO: encoding for field tls_endpoint_id (TLSEndpointID) not implemented
456            if let Some(x) = transport_options.url { transport_options_fields.push((4, tlv::TlvItemValueEnc::String(x.clone())).into()); }
457            if let Some(inner) = transport_options.trigger_options {
458                let mut trigger_options_nested_fields = Vec::new();
459                if let Some(x) = inner.trigger_type { trigger_options_nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
460                if let Some(listv) = inner.motion_zones {
461                    let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
462                        let mut nested_fields = Vec::new();
463                            // TODO: encoding for field zone (ZoneID) not implemented
464                            if let Some(x) = inner.sensitivity { nested_fields.push((1, tlv::TlvItemValueEnc::UInt8(x)).into()); }
465                        (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
466                    }).collect();
467                    trigger_options_nested_fields.push((1, tlv::TlvItemValueEnc::Array(inner_vec)).into());
468                }
469                if let Some(x) = inner.motion_sensitivity { trigger_options_nested_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
470                if let Some(inner) = inner.motion_time_control {
471                    let mut motion_time_control_nested_fields = Vec::new();
472                    if let Some(x) = inner.initial_duration { motion_time_control_nested_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
473                    if let Some(x) = inner.augmentation_duration { motion_time_control_nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
474                    if let Some(x) = inner.max_duration { motion_time_control_nested_fields.push((2, tlv::TlvItemValueEnc::UInt32(x)).into()); }
475                    if let Some(x) = inner.blind_duration { motion_time_control_nested_fields.push((3, tlv::TlvItemValueEnc::UInt16(x)).into()); }
476                    trigger_options_nested_fields.push((3, tlv::TlvItemValueEnc::StructInvisible(motion_time_control_nested_fields)).into());
477                }
478                if let Some(x) = inner.max_pre_roll_len { trigger_options_nested_fields.push((4, tlv::TlvItemValueEnc::UInt16(x)).into()); }
479                transport_options_fields.push((5, tlv::TlvItemValueEnc::StructInvisible(trigger_options_nested_fields)).into());
480            }
481            if let Some(x) = transport_options.ingest_method { transport_options_fields.push((6, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
482            if let Some(inner) = transport_options.container_options {
483                let mut container_options_nested_fields = Vec::new();
484                if let Some(x) = inner.container_type { container_options_nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
485                if let Some(inner) = inner.cmaf_container_options {
486                    let mut cmaf_container_options_nested_fields = Vec::new();
487                    if let Some(x) = inner.cmaf_interface { cmaf_container_options_nested_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
488                    if let Some(x) = inner.segment_duration { cmaf_container_options_nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
489                    if let Some(x) = inner.chunk_duration { cmaf_container_options_nested_fields.push((2, tlv::TlvItemValueEnc::UInt16(x)).into()); }
490                    if let Some(x) = inner.session_group { cmaf_container_options_nested_fields.push((3, tlv::TlvItemValueEnc::UInt8(x)).into()); }
491                    if let Some(x) = inner.track_name { cmaf_container_options_nested_fields.push((4, tlv::TlvItemValueEnc::String(x.clone())).into()); }
492                    if let Some(x) = inner.cenc_key { cmaf_container_options_nested_fields.push((5, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
493                    if let Some(x) = inner.cenc_key_id { cmaf_container_options_nested_fields.push((6, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
494                    if let Some(x) = inner.metadata_enabled { cmaf_container_options_nested_fields.push((7, tlv::TlvItemValueEnc::Bool(x)).into()); }
495                    container_options_nested_fields.push((1, tlv::TlvItemValueEnc::StructInvisible(cmaf_container_options_nested_fields)).into());
496                }
497                transport_options_fields.push((7, tlv::TlvItemValueEnc::StructInvisible(container_options_nested_fields)).into());
498            }
499            if let Some(x) = transport_options.expiry_time { transport_options_fields.push((8, tlv::TlvItemValueEnc::UInt64(x)).into()); }
500            if let Some(listv) = transport_options.video_streams {
501                let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
502                    let mut nested_fields = Vec::new();
503                        if let Some(x) = inner.video_stream_name { nested_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
504                        // TODO: encoding for field video_stream_id (VideoStreamID) not implemented
505                    (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
506                }).collect();
507                transport_options_fields.push((9, tlv::TlvItemValueEnc::Array(inner_vec)).into());
508            }
509            if let Some(listv) = transport_options.audio_streams {
510                let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
511                    let mut nested_fields = Vec::new();
512                        if let Some(x) = inner.audio_stream_name { nested_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
513                        // TODO: encoding for field audio_stream_id (AudioStreamID) not implemented
514                    (0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
515                }).collect();
516                transport_options_fields.push((10, tlv::TlvItemValueEnc::Array(inner_vec)).into());
517            }
518    let tlv = tlv::TlvItemEnc {
519        tag: 0,
520        value: tlv::TlvItemValueEnc::StructInvisible(vec![
521        (0, tlv::TlvItemValueEnc::UInt8(connection_id)).into(),
522        (1, tlv::TlvItemValueEnc::StructInvisible(transport_options_fields)).into(),
523        ]),
524    };
525    Ok(tlv.encode()?)
526}
527
528/// Encode SetTransportStatus command (0x04)
529pub fn encode_set_transport_status(connection_id: Option<u8>, transport_status: TransportStatus) -> anyhow::Result<Vec<u8>> {
530    let tlv = tlv::TlvItemEnc {
531        tag: 0,
532        value: tlv::TlvItemValueEnc::StructInvisible(vec![
533        (0, tlv::TlvItemValueEnc::UInt8(connection_id.unwrap_or(0))).into(),
534        (1, tlv::TlvItemValueEnc::UInt8(transport_status.to_u8())).into(),
535        ]),
536    };
537    Ok(tlv.encode()?)
538}
539
540/// Encode ManuallyTriggerTransport command (0x05)
541pub fn encode_manually_trigger_transport(connection_id: u8, activation_reason: TriggerActivationReason, time_control: TransportMotionTriggerTimeControl, user_defined: Vec<u8>) -> anyhow::Result<Vec<u8>> {
542            // Encode struct TransportMotionTriggerTimeControlStruct
543            let mut time_control_fields = Vec::new();
544            if let Some(x) = time_control.initial_duration { time_control_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
545            if let Some(x) = time_control.augmentation_duration { time_control_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
546            if let Some(x) = time_control.max_duration { time_control_fields.push((2, tlv::TlvItemValueEnc::UInt32(x)).into()); }
547            if let Some(x) = time_control.blind_duration { time_control_fields.push((3, tlv::TlvItemValueEnc::UInt16(x)).into()); }
548    let tlv = tlv::TlvItemEnc {
549        tag: 0,
550        value: tlv::TlvItemValueEnc::StructInvisible(vec![
551        (0, tlv::TlvItemValueEnc::UInt8(connection_id)).into(),
552        (1, tlv::TlvItemValueEnc::UInt8(activation_reason.to_u8())).into(),
553        (2, tlv::TlvItemValueEnc::StructInvisible(time_control_fields)).into(),
554        (3, tlv::TlvItemValueEnc::OctetString(user_defined)).into(),
555        ]),
556    };
557    Ok(tlv.encode()?)
558}
559
560/// Encode FindTransport command (0x06)
561pub fn encode_find_transport(connection_id: Option<u8>) -> anyhow::Result<Vec<u8>> {
562    let tlv = tlv::TlvItemEnc {
563        tag: 0,
564        value: tlv::TlvItemValueEnc::StructInvisible(vec![
565        (0, tlv::TlvItemValueEnc::UInt8(connection_id.unwrap_or(0))).into(),
566        ]),
567    };
568    Ok(tlv.encode()?)
569}
570
571// Attribute decoders
572
573/// Decode SupportedFormats attribute (0x0000)
574pub fn decode_supported_formats(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<SupportedFormat>> {
575    let mut res = Vec::new();
576    if let tlv::TlvItemValue::List(v) = inp {
577        for item in v {
578            res.push(SupportedFormat {
579                container_format: item.get_int(&[0]).and_then(|v| ContainerFormat::from_u8(v as u8)),
580                ingest_method: item.get_int(&[1]).and_then(|v| IngestMethods::from_u8(v as u8)),
581            });
582        }
583    }
584    Ok(res)
585}
586
587/// Decode CurrentConnections attribute (0x0001)
588pub fn decode_current_connections(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TransportConfiguration>> {
589    let mut res = Vec::new();
590    if let tlv::TlvItemValue::List(v) = inp {
591        for item in v {
592            res.push(TransportConfiguration {
593                connection_id: item.get_int(&[0]).map(|v| v as u8),
594                transport_status: item.get_int(&[1]).and_then(|v| TransportStatus::from_u8(v as u8)),
595                transport_options: {
596                    if let Some(nested_tlv) = item.get(&[2]) {
597                        if let tlv::TlvItemValue::List(_) = nested_tlv {
598                            let nested_item = tlv::TlvItem { tag: 2, value: nested_tlv.clone() };
599                            Some(TransportOptions {
600                stream_usage: nested_item.get_int(&[0]).map(|v| v as u8),
601                video_stream_id: nested_item.get_int(&[1]).map(|v| v as u8),
602                audio_stream_id: nested_item.get_int(&[2]).map(|v| v as u8),
603                tls_endpoint_id: nested_item.get_int(&[3]).map(|v| v as u8),
604                url: nested_item.get_string_owned(&[4]),
605                trigger_options: {
606                    if let Some(nested_tlv) = nested_item.get(&[5]) {
607                        if let tlv::TlvItemValue::List(_) = nested_tlv {
608                            let nested_item = tlv::TlvItem { tag: 5, value: nested_tlv.clone() };
609                            Some(TransportTriggerOptions {
610                trigger_type: nested_item.get_int(&[0]).and_then(|v| TransportTriggerType::from_u8(v as u8)),
611                motion_zones: {
612                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[1]) {
613                        let mut items = Vec::new();
614                        for list_item in l {
615                            items.push(TransportZoneOptions {
616                zone: list_item.get_int(&[0]).map(|v| v as u8),
617                sensitivity: list_item.get_int(&[1]).map(|v| v as u8),
618                            });
619                        }
620                        Some(items)
621                    } else {
622                        None
623                    }
624                },
625                motion_sensitivity: nested_item.get_int(&[2]).map(|v| v as u8),
626                motion_time_control: {
627                    if let Some(nested_tlv) = nested_item.get(&[3]) {
628                        if let tlv::TlvItemValue::List(_) = nested_tlv {
629                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
630                            Some(TransportMotionTriggerTimeControl {
631                initial_duration: nested_item.get_int(&[0]).map(|v| v as u16),
632                augmentation_duration: nested_item.get_int(&[1]).map(|v| v as u16),
633                max_duration: nested_item.get_int(&[2]).map(|v| v as u32),
634                blind_duration: nested_item.get_int(&[3]).map(|v| v as u16),
635                            })
636                        } else {
637                            None
638                        }
639                    } else {
640                        None
641                    }
642                },
643                max_pre_roll_len: nested_item.get_int(&[4]).map(|v| v as u16),
644                            })
645                        } else {
646                            None
647                        }
648                    } else {
649                        None
650                    }
651                },
652                ingest_method: nested_item.get_int(&[6]).and_then(|v| IngestMethods::from_u8(v as u8)),
653                container_options: {
654                    if let Some(nested_tlv) = nested_item.get(&[7]) {
655                        if let tlv::TlvItemValue::List(_) = nested_tlv {
656                            let nested_item = tlv::TlvItem { tag: 7, value: nested_tlv.clone() };
657                            Some(ContainerOptions {
658                container_type: nested_item.get_int(&[0]).and_then(|v| ContainerFormat::from_u8(v as u8)),
659                cmaf_container_options: {
660                    if let Some(nested_tlv) = nested_item.get(&[1]) {
661                        if let tlv::TlvItemValue::List(_) = nested_tlv {
662                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
663                            Some(CMAFContainerOptions {
664                cmaf_interface: nested_item.get_int(&[0]).and_then(|v| CMAFInterface::from_u8(v as u8)),
665                segment_duration: nested_item.get_int(&[1]).map(|v| v as u16),
666                chunk_duration: nested_item.get_int(&[2]).map(|v| v as u16),
667                session_group: nested_item.get_int(&[3]).map(|v| v as u8),
668                track_name: nested_item.get_string_owned(&[4]),
669                cenc_key: nested_item.get_octet_string_owned(&[5]),
670                cenc_key_id: nested_item.get_octet_string_owned(&[6]),
671                metadata_enabled: nested_item.get_bool(&[7]),
672                            })
673                        } else {
674                            None
675                        }
676                    } else {
677                        None
678                    }
679                },
680                            })
681                        } else {
682                            None
683                        }
684                    } else {
685                        None
686                    }
687                },
688                expiry_time: nested_item.get_int(&[8]),
689                video_streams: {
690                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[9]) {
691                        let mut items = Vec::new();
692                        for list_item in l {
693                            items.push(VideoStream {
694                video_stream_name: list_item.get_string_owned(&[0]),
695                video_stream_id: list_item.get_int(&[1]).map(|v| v as u8),
696                            });
697                        }
698                        Some(items)
699                    } else {
700                        None
701                    }
702                },
703                audio_streams: {
704                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[10]) {
705                        let mut items = Vec::new();
706                        for list_item in l {
707                            items.push(AudioStream {
708                audio_stream_name: list_item.get_string_owned(&[0]),
709                audio_stream_id: list_item.get_int(&[1]).map(|v| v as u8),
710                            });
711                        }
712                        Some(items)
713                    } else {
714                        None
715                    }
716                },
717                            })
718                        } else {
719                            None
720                        }
721                    } else {
722                        None
723                    }
724                },
725            });
726        }
727    }
728    Ok(res)
729}
730
731
732// JSON dispatcher function
733
734/// Decode attribute value and return as JSON string
735///
736/// # Parameters
737/// * `cluster_id` - The cluster identifier
738/// * `attribute_id` - The attribute identifier
739/// * `tlv_value` - The TLV value to decode
740///
741/// # Returns
742/// JSON string representation of the decoded value or error
743pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
744    // Verify this is the correct cluster
745    if cluster_id != 0x0555 {
746        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0555, got {}\"}}", cluster_id);
747    }
748
749    match attribute_id {
750        0x0000 => {
751            match decode_supported_formats(tlv_value) {
752                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
753                Err(e) => format!("{{\"error\": \"{}\"}}", e),
754            }
755        }
756        0x0001 => {
757            match decode_current_connections(tlv_value) {
758                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
759                Err(e) => format!("{{\"error\": \"{}\"}}", e),
760            }
761        }
762        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
763    }
764}
765
766/// Get list of all attributes supported by this cluster
767///
768/// # Returns
769/// Vector of tuples containing (attribute_id, attribute_name)
770pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
771    vec![
772        (0x0000, "SupportedFormats"),
773        (0x0001, "CurrentConnections"),
774    ]
775}
776
777// Command listing
778
779pub fn get_command_list() -> Vec<(u32, &'static str)> {
780    vec![
781        (0x00, "AllocatePushTransport"),
782        (0x02, "DeallocatePushTransport"),
783        (0x03, "ModifyPushTransport"),
784        (0x04, "SetTransportStatus"),
785        (0x05, "ManuallyTriggerTransport"),
786        (0x06, "FindTransport"),
787    ]
788}
789
790pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
791    match cmd_id {
792        0x00 => Some("AllocatePushTransport"),
793        0x02 => Some("DeallocatePushTransport"),
794        0x03 => Some("ModifyPushTransport"),
795        0x04 => Some("SetTransportStatus"),
796        0x05 => Some("ManuallyTriggerTransport"),
797        0x06 => Some("FindTransport"),
798        _ => None,
799    }
800}
801
802pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
803    match cmd_id {
804        0x00 => Some(vec![
805            crate::clusters::codec::CommandField { tag: 0, name: "transport_options", kind: crate::clusters::codec::FieldKind::Struct { name: "TransportOptionsStruct" }, optional: false, nullable: false },
806        ]),
807        0x02 => Some(vec![
808            crate::clusters::codec::CommandField { tag: 0, name: "connection_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
809        ]),
810        0x03 => Some(vec![
811            crate::clusters::codec::CommandField { tag: 0, name: "connection_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
812            crate::clusters::codec::CommandField { tag: 1, name: "transport_options", kind: crate::clusters::codec::FieldKind::Struct { name: "TransportOptionsStruct" }, optional: false, nullable: false },
813        ]),
814        0x04 => Some(vec![
815            crate::clusters::codec::CommandField { tag: 0, name: "connection_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
816            crate::clusters::codec::CommandField { tag: 1, name: "transport_status", kind: crate::clusters::codec::FieldKind::Enum { name: "TransportStatus", variants: &[(0, "Active"), (1, "Inactive")] }, optional: false, nullable: false },
817        ]),
818        0x05 => Some(vec![
819            crate::clusters::codec::CommandField { tag: 0, name: "connection_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
820            crate::clusters::codec::CommandField { tag: 1, name: "activation_reason", kind: crate::clusters::codec::FieldKind::Enum { name: "TriggerActivationReason", variants: &[(0, "Userinitiated"), (1, "Automation"), (2, "Emergency"), (3, "Doorbellpressed")] }, optional: false, nullable: false },
821            crate::clusters::codec::CommandField { tag: 2, name: "time_control", kind: crate::clusters::codec::FieldKind::Struct { name: "TransportMotionTriggerTimeControlStruct" }, optional: true, nullable: false },
822            crate::clusters::codec::CommandField { tag: 3, name: "user_defined", kind: crate::clusters::codec::FieldKind::OctetString, optional: true, nullable: false },
823        ]),
824        0x06 => Some(vec![
825            crate::clusters::codec::CommandField { tag: 0, name: "connection_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
826        ]),
827        _ => None,
828    }
829}
830
831pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
832    match cmd_id {
833        0x00 => Err(anyhow::anyhow!("command \"AllocatePushTransport\" has complex args: use raw mode")),
834        0x02 => {
835        let connection_id = crate::clusters::codec::json_util::get_u8(args, "connection_id")?;
836        encode_deallocate_push_transport(connection_id)
837        }
838        0x03 => Err(anyhow::anyhow!("command \"ModifyPushTransport\" has complex args: use raw mode")),
839        0x04 => {
840        let connection_id = crate::clusters::codec::json_util::get_opt_u8(args, "connection_id")?;
841        let transport_status = {
842            let n = crate::clusters::codec::json_util::get_u64(args, "transport_status")?;
843            TransportStatus::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid TransportStatus: {}", n))?
844        };
845        encode_set_transport_status(connection_id, transport_status)
846        }
847        0x05 => Err(anyhow::anyhow!("command \"ManuallyTriggerTransport\" has complex args: use raw mode")),
848        0x06 => {
849        let connection_id = crate::clusters::codec::json_util::get_opt_u8(args, "connection_id")?;
850        encode_find_transport(connection_id)
851        }
852        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
853    }
854}
855
856#[derive(Debug, serde::Serialize)]
857pub struct AllocatePushTransportResponse {
858    pub transport_configuration: Option<TransportConfiguration>,
859}
860
861#[derive(Debug, serde::Serialize)]
862pub struct FindTransportResponse {
863    pub transport_configurations: Option<Vec<TransportConfiguration>>,
864}
865
866// Command response decoders
867
868/// Decode AllocatePushTransportResponse command response (01)
869pub fn decode_allocate_push_transport_response(inp: &tlv::TlvItemValue) -> anyhow::Result<AllocatePushTransportResponse> {
870    if let tlv::TlvItemValue::List(_fields) = inp {
871        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
872        Ok(AllocatePushTransportResponse {
873                transport_configuration: {
874                    if let Some(nested_tlv) = item.get(&[0]) {
875                        if let tlv::TlvItemValue::List(_) = nested_tlv {
876                            let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
877                            Some(TransportConfiguration {
878                connection_id: nested_item.get_int(&[0]).map(|v| v as u8),
879                transport_status: nested_item.get_int(&[1]).and_then(|v| TransportStatus::from_u8(v as u8)),
880                transport_options: {
881                    if let Some(nested_tlv) = nested_item.get(&[2]) {
882                        if let tlv::TlvItemValue::List(_) = nested_tlv {
883                            let nested_item = tlv::TlvItem { tag: 2, value: nested_tlv.clone() };
884                            Some(TransportOptions {
885                stream_usage: nested_item.get_int(&[0]).map(|v| v as u8),
886                video_stream_id: nested_item.get_int(&[1]).map(|v| v as u8),
887                audio_stream_id: nested_item.get_int(&[2]).map(|v| v as u8),
888                tls_endpoint_id: nested_item.get_int(&[3]).map(|v| v as u8),
889                url: nested_item.get_string_owned(&[4]),
890                trigger_options: {
891                    if let Some(nested_tlv) = nested_item.get(&[5]) {
892                        if let tlv::TlvItemValue::List(_) = nested_tlv {
893                            let nested_item = tlv::TlvItem { tag: 5, value: nested_tlv.clone() };
894                            Some(TransportTriggerOptions {
895                trigger_type: nested_item.get_int(&[0]).and_then(|v| TransportTriggerType::from_u8(v as u8)),
896                motion_zones: {
897                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[1]) {
898                        let mut items = Vec::new();
899                        for list_item in l {
900                            items.push(TransportZoneOptions {
901                zone: list_item.get_int(&[0]).map(|v| v as u8),
902                sensitivity: list_item.get_int(&[1]).map(|v| v as u8),
903                            });
904                        }
905                        Some(items)
906                    } else {
907                        None
908                    }
909                },
910                motion_sensitivity: nested_item.get_int(&[2]).map(|v| v as u8),
911                motion_time_control: {
912                    if let Some(nested_tlv) = nested_item.get(&[3]) {
913                        if let tlv::TlvItemValue::List(_) = nested_tlv {
914                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
915                            Some(TransportMotionTriggerTimeControl {
916                initial_duration: nested_item.get_int(&[0]).map(|v| v as u16),
917                augmentation_duration: nested_item.get_int(&[1]).map(|v| v as u16),
918                max_duration: nested_item.get_int(&[2]).map(|v| v as u32),
919                blind_duration: nested_item.get_int(&[3]).map(|v| v as u16),
920                            })
921                        } else {
922                            None
923                        }
924                    } else {
925                        None
926                    }
927                },
928                max_pre_roll_len: nested_item.get_int(&[4]).map(|v| v as u16),
929                            })
930                        } else {
931                            None
932                        }
933                    } else {
934                        None
935                    }
936                },
937                ingest_method: nested_item.get_int(&[6]).and_then(|v| IngestMethods::from_u8(v as u8)),
938                container_options: {
939                    if let Some(nested_tlv) = nested_item.get(&[7]) {
940                        if let tlv::TlvItemValue::List(_) = nested_tlv {
941                            let nested_item = tlv::TlvItem { tag: 7, value: nested_tlv.clone() };
942                            Some(ContainerOptions {
943                container_type: nested_item.get_int(&[0]).and_then(|v| ContainerFormat::from_u8(v as u8)),
944                cmaf_container_options: {
945                    if let Some(nested_tlv) = nested_item.get(&[1]) {
946                        if let tlv::TlvItemValue::List(_) = nested_tlv {
947                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
948                            Some(CMAFContainerOptions {
949                cmaf_interface: nested_item.get_int(&[0]).and_then(|v| CMAFInterface::from_u8(v as u8)),
950                segment_duration: nested_item.get_int(&[1]).map(|v| v as u16),
951                chunk_duration: nested_item.get_int(&[2]).map(|v| v as u16),
952                session_group: nested_item.get_int(&[3]).map(|v| v as u8),
953                track_name: nested_item.get_string_owned(&[4]),
954                cenc_key: nested_item.get_octet_string_owned(&[5]),
955                cenc_key_id: nested_item.get_octet_string_owned(&[6]),
956                metadata_enabled: nested_item.get_bool(&[7]),
957                            })
958                        } else {
959                            None
960                        }
961                    } else {
962                        None
963                    }
964                },
965                            })
966                        } else {
967                            None
968                        }
969                    } else {
970                        None
971                    }
972                },
973                expiry_time: nested_item.get_int(&[8]),
974                video_streams: {
975                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[9]) {
976                        let mut items = Vec::new();
977                        for list_item in l {
978                            items.push(VideoStream {
979                video_stream_name: list_item.get_string_owned(&[0]),
980                video_stream_id: list_item.get_int(&[1]).map(|v| v as u8),
981                            });
982                        }
983                        Some(items)
984                    } else {
985                        None
986                    }
987                },
988                audio_streams: {
989                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[10]) {
990                        let mut items = Vec::new();
991                        for list_item in l {
992                            items.push(AudioStream {
993                audio_stream_name: list_item.get_string_owned(&[0]),
994                audio_stream_id: list_item.get_int(&[1]).map(|v| v as u8),
995                            });
996                        }
997                        Some(items)
998                    } else {
999                        None
1000                    }
1001                },
1002                            })
1003                        } else {
1004                            None
1005                        }
1006                    } else {
1007                        None
1008                    }
1009                },
1010                            })
1011                        } else {
1012                            None
1013                        }
1014                    } else {
1015                        None
1016                    }
1017                },
1018        })
1019    } else {
1020        Err(anyhow::anyhow!("Expected struct fields"))
1021    }
1022}
1023
1024/// Decode FindTransportResponse command response (07)
1025pub fn decode_find_transport_response(inp: &tlv::TlvItemValue) -> anyhow::Result<FindTransportResponse> {
1026    if let tlv::TlvItemValue::List(_fields) = inp {
1027        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
1028        Ok(FindTransportResponse {
1029                transport_configurations: {
1030                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
1031                        let mut items = Vec::new();
1032                        for list_item in l {
1033                            items.push(TransportConfiguration {
1034                connection_id: list_item.get_int(&[0]).map(|v| v as u8),
1035                transport_status: list_item.get_int(&[1]).and_then(|v| TransportStatus::from_u8(v as u8)),
1036                transport_options: {
1037                    if let Some(nested_tlv) = list_item.get(&[2]) {
1038                        if let tlv::TlvItemValue::List(_) = nested_tlv {
1039                            let nested_item = tlv::TlvItem { tag: 2, value: nested_tlv.clone() };
1040                            Some(TransportOptions {
1041                stream_usage: nested_item.get_int(&[0]).map(|v| v as u8),
1042                video_stream_id: nested_item.get_int(&[1]).map(|v| v as u8),
1043                audio_stream_id: nested_item.get_int(&[2]).map(|v| v as u8),
1044                tls_endpoint_id: nested_item.get_int(&[3]).map(|v| v as u8),
1045                url: nested_item.get_string_owned(&[4]),
1046                trigger_options: {
1047                    if let Some(nested_tlv) = nested_item.get(&[5]) {
1048                        if let tlv::TlvItemValue::List(_) = nested_tlv {
1049                            let nested_item = tlv::TlvItem { tag: 5, value: nested_tlv.clone() };
1050                            Some(TransportTriggerOptions {
1051                trigger_type: nested_item.get_int(&[0]).and_then(|v| TransportTriggerType::from_u8(v as u8)),
1052                motion_zones: {
1053                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[1]) {
1054                        let mut items = Vec::new();
1055                        for list_item in l {
1056                            items.push(TransportZoneOptions {
1057                zone: list_item.get_int(&[0]).map(|v| v as u8),
1058                sensitivity: list_item.get_int(&[1]).map(|v| v as u8),
1059                            });
1060                        }
1061                        Some(items)
1062                    } else {
1063                        None
1064                    }
1065                },
1066                motion_sensitivity: nested_item.get_int(&[2]).map(|v| v as u8),
1067                motion_time_control: {
1068                    if let Some(nested_tlv) = nested_item.get(&[3]) {
1069                        if let tlv::TlvItemValue::List(_) = nested_tlv {
1070                            let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
1071                            Some(TransportMotionTriggerTimeControl {
1072                initial_duration: nested_item.get_int(&[0]).map(|v| v as u16),
1073                augmentation_duration: nested_item.get_int(&[1]).map(|v| v as u16),
1074                max_duration: nested_item.get_int(&[2]).map(|v| v as u32),
1075                blind_duration: nested_item.get_int(&[3]).map(|v| v as u16),
1076                            })
1077                        } else {
1078                            None
1079                        }
1080                    } else {
1081                        None
1082                    }
1083                },
1084                max_pre_roll_len: nested_item.get_int(&[4]).map(|v| v as u16),
1085                            })
1086                        } else {
1087                            None
1088                        }
1089                    } else {
1090                        None
1091                    }
1092                },
1093                ingest_method: nested_item.get_int(&[6]).and_then(|v| IngestMethods::from_u8(v as u8)),
1094                container_options: {
1095                    if let Some(nested_tlv) = nested_item.get(&[7]) {
1096                        if let tlv::TlvItemValue::List(_) = nested_tlv {
1097                            let nested_item = tlv::TlvItem { tag: 7, value: nested_tlv.clone() };
1098                            Some(ContainerOptions {
1099                container_type: nested_item.get_int(&[0]).and_then(|v| ContainerFormat::from_u8(v as u8)),
1100                cmaf_container_options: {
1101                    if let Some(nested_tlv) = nested_item.get(&[1]) {
1102                        if let tlv::TlvItemValue::List(_) = nested_tlv {
1103                            let nested_item = tlv::TlvItem { tag: 1, value: nested_tlv.clone() };
1104                            Some(CMAFContainerOptions {
1105                cmaf_interface: nested_item.get_int(&[0]).and_then(|v| CMAFInterface::from_u8(v as u8)),
1106                segment_duration: nested_item.get_int(&[1]).map(|v| v as u16),
1107                chunk_duration: nested_item.get_int(&[2]).map(|v| v as u16),
1108                session_group: nested_item.get_int(&[3]).map(|v| v as u8),
1109                track_name: nested_item.get_string_owned(&[4]),
1110                cenc_key: nested_item.get_octet_string_owned(&[5]),
1111                cenc_key_id: nested_item.get_octet_string_owned(&[6]),
1112                metadata_enabled: nested_item.get_bool(&[7]),
1113                            })
1114                        } else {
1115                            None
1116                        }
1117                    } else {
1118                        None
1119                    }
1120                },
1121                            })
1122                        } else {
1123                            None
1124                        }
1125                    } else {
1126                        None
1127                    }
1128                },
1129                expiry_time: nested_item.get_int(&[8]),
1130                video_streams: {
1131                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[9]) {
1132                        let mut items = Vec::new();
1133                        for list_item in l {
1134                            items.push(VideoStream {
1135                video_stream_name: list_item.get_string_owned(&[0]),
1136                video_stream_id: list_item.get_int(&[1]).map(|v| v as u8),
1137                            });
1138                        }
1139                        Some(items)
1140                    } else {
1141                        None
1142                    }
1143                },
1144                audio_streams: {
1145                    if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[10]) {
1146                        let mut items = Vec::new();
1147                        for list_item in l {
1148                            items.push(AudioStream {
1149                audio_stream_name: list_item.get_string_owned(&[0]),
1150                audio_stream_id: list_item.get_int(&[1]).map(|v| v as u8),
1151                            });
1152                        }
1153                        Some(items)
1154                    } else {
1155                        None
1156                    }
1157                },
1158                            })
1159                        } else {
1160                            None
1161                        }
1162                    } else {
1163                        None
1164                    }
1165                },
1166                            });
1167                        }
1168                        Some(items)
1169                    } else {
1170                        None
1171                    }
1172                },
1173        })
1174    } else {
1175        Err(anyhow::anyhow!("Expected struct fields"))
1176    }
1177}
1178
1179// Typed facade (invokes + reads)
1180
1181/// Invoke `AllocatePushTransport` command on cluster `Push AV Stream Transport`.
1182pub async fn allocate_push_transport(conn: &crate::controller::Connection, endpoint: u16, transport_options: TransportOptions) -> anyhow::Result<AllocatePushTransportResponse> {
1183    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_CMD_ID_ALLOCATEPUSHTRANSPORT, &encode_allocate_push_transport(transport_options)?).await?;
1184    decode_allocate_push_transport_response(&tlv)
1185}
1186
1187/// Invoke `DeallocatePushTransport` command on cluster `Push AV Stream Transport`.
1188pub async fn deallocate_push_transport(conn: &crate::controller::Connection, endpoint: u16, connection_id: u8) -> anyhow::Result<()> {
1189    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_CMD_ID_DEALLOCATEPUSHTRANSPORT, &encode_deallocate_push_transport(connection_id)?).await?;
1190    Ok(())
1191}
1192
1193/// Invoke `ModifyPushTransport` command on cluster `Push AV Stream Transport`.
1194pub async fn modify_push_transport(conn: &crate::controller::Connection, endpoint: u16, connection_id: u8, transport_options: TransportOptions) -> anyhow::Result<()> {
1195    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_CMD_ID_MODIFYPUSHTRANSPORT, &encode_modify_push_transport(connection_id, transport_options)?).await?;
1196    Ok(())
1197}
1198
1199/// Invoke `SetTransportStatus` command on cluster `Push AV Stream Transport`.
1200pub async fn set_transport_status(conn: &crate::controller::Connection, endpoint: u16, connection_id: Option<u8>, transport_status: TransportStatus) -> anyhow::Result<()> {
1201    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_CMD_ID_SETTRANSPORTSTATUS, &encode_set_transport_status(connection_id, transport_status)?).await?;
1202    Ok(())
1203}
1204
1205/// Invoke `ManuallyTriggerTransport` command on cluster `Push AV Stream Transport`.
1206pub async fn manually_trigger_transport(conn: &crate::controller::Connection, endpoint: u16, connection_id: u8, activation_reason: TriggerActivationReason, time_control: TransportMotionTriggerTimeControl, user_defined: Vec<u8>) -> anyhow::Result<()> {
1207    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_CMD_ID_MANUALLYTRIGGERTRANSPORT, &encode_manually_trigger_transport(connection_id, activation_reason, time_control, user_defined)?).await?;
1208    Ok(())
1209}
1210
1211/// Invoke `FindTransport` command on cluster `Push AV Stream Transport`.
1212pub async fn find_transport(conn: &crate::controller::Connection, endpoint: u16, connection_id: Option<u8>) -> anyhow::Result<FindTransportResponse> {
1213    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_CMD_ID_FINDTRANSPORT, &encode_find_transport(connection_id)?).await?;
1214    decode_find_transport_response(&tlv)
1215}
1216
1217/// Read `SupportedFormats` attribute from cluster `Push AV Stream Transport`.
1218pub async fn read_supported_formats(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<SupportedFormat>> {
1219    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_ATTR_ID_SUPPORTEDFORMATS).await?;
1220    decode_supported_formats(&tlv)
1221}
1222
1223/// Read `CurrentConnections` attribute from cluster `Push AV Stream Transport`.
1224pub async fn read_current_connections(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TransportConfiguration>> {
1225    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_PUSH_AV_STREAM_TRANSPORT, crate::clusters::defs::CLUSTER_PUSH_AV_STREAM_TRANSPORT_ATTR_ID_CURRENTCONNECTIONS).await?;
1226    decode_current_connections(&tlv)
1227}
1228
1229#[derive(Debug, serde::Serialize)]
1230pub struct PushTransportBeginEvent {
1231    pub connection_id: Option<u8>,
1232    pub trigger_type: Option<TransportTriggerType>,
1233    pub activation_reason: Option<TriggerActivationReason>,
1234    pub container_type: Option<ContainerFormat>,
1235    pub cmaf_session_number: Option<u64>,
1236    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
1237    pub vendor_specific_context: Option<Vec<u8>>,
1238}
1239
1240#[derive(Debug, serde::Serialize)]
1241pub struct PushTransportEndEvent {
1242    pub connection_id: Option<u8>,
1243    pub container_type: Option<ContainerFormat>,
1244    pub cmaf_session_number: Option<u64>,
1245}
1246
1247// Event decoders
1248
1249/// Decode PushTransportBegin event (0x00, priority: info)
1250pub fn decode_push_transport_begin_event(inp: &tlv::TlvItemValue) -> anyhow::Result<PushTransportBeginEvent> {
1251    if let tlv::TlvItemValue::List(_fields) = inp {
1252        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
1253        Ok(PushTransportBeginEvent {
1254                                connection_id: item.get_int(&[0]).map(|v| v as u8),
1255                                trigger_type: item.get_int(&[1]).and_then(|v| TransportTriggerType::from_u8(v as u8)),
1256                                activation_reason: item.get_int(&[2]).and_then(|v| TriggerActivationReason::from_u8(v as u8)),
1257                                container_type: item.get_int(&[3]).and_then(|v| ContainerFormat::from_u8(v as u8)),
1258                                cmaf_session_number: item.get_int(&[4]),
1259                                vendor_specific_context: item.get_octet_string_owned(&[5]),
1260        })
1261    } else {
1262        Err(anyhow::anyhow!("Expected struct fields"))
1263    }
1264}
1265
1266/// Decode PushTransportEnd event (0x01, priority: info)
1267pub fn decode_push_transport_end_event(inp: &tlv::TlvItemValue) -> anyhow::Result<PushTransportEndEvent> {
1268    if let tlv::TlvItemValue::List(_fields) = inp {
1269        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
1270        Ok(PushTransportEndEvent {
1271                                connection_id: item.get_int(&[0]).map(|v| v as u8),
1272                                container_type: item.get_int(&[1]).and_then(|v| ContainerFormat::from_u8(v as u8)),
1273                                cmaf_session_number: item.get_int(&[2]),
1274        })
1275    } else {
1276        Err(anyhow::anyhow!("Expected struct fields"))
1277    }
1278}
1279