1#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
15
16#[derive(Debug, serde::Serialize)]
19pub struct SFrame {
20 pub cipher_suite: Option<u16>,
21 #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
22 pub base_key: Option<Vec<u8>>,
23 #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
24 pub kid: Option<Vec<u8>>,
25}
26
27pub struct SolicitOfferParams {
31 pub stream_usage: u8,
32 pub originating_endpoint_id: u16,
33 pub video_stream_id: Option<u8>,
34 pub audio_stream_id: Option<u8>,
35 pub ice_transport_policy: String,
36 pub metadata_enabled: bool,
37 pub s_frame_config: SFrame,
38 pub video_streams: Vec<u8>,
39 pub audio_streams: Vec<u8>,
40}
41
42pub fn encode_solicit_offer(params: SolicitOfferParams) -> anyhow::Result<Vec<u8>> {
44 let mut s_frame_config_fields = Vec::new();
46 if let Some(x) = params.s_frame_config.cipher_suite { s_frame_config_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
47 if let Some(x) = params.s_frame_config.base_key { s_frame_config_fields.push((1, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
48 if let Some(x) = params.s_frame_config.kid { s_frame_config_fields.push((2, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
49 let tlv = tlv::TlvItemEnc {
50 tag: 0,
51 value: tlv::TlvItemValueEnc::StructInvisible(vec![
52 (0, tlv::TlvItemValueEnc::UInt8(params.stream_usage)).into(),
53 (1, tlv::TlvItemValueEnc::UInt16(params.originating_endpoint_id)).into(),
54 (2, tlv::TlvItemValueEnc::UInt8(params.video_stream_id.unwrap_or(0))).into(),
55 (3, tlv::TlvItemValueEnc::UInt8(params.audio_stream_id.unwrap_or(0))).into(),
56 (5, tlv::TlvItemValueEnc::String(params.ice_transport_policy)).into(),
57 (6, tlv::TlvItemValueEnc::Bool(params.metadata_enabled)).into(),
58 (7, tlv::TlvItemValueEnc::StructInvisible(s_frame_config_fields)).into(),
59 (8, tlv::TlvItemValueEnc::StructAnon(params.video_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
60 (9, tlv::TlvItemValueEnc::StructAnon(params.audio_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
61 ]),
62 };
63 Ok(tlv.encode()?)
64}
65
66pub struct ProvideOfferParams {
68 pub web_rtc_session_id: Option<u8>,
69 pub sdp: String,
70 pub stream_usage: u8,
71 pub originating_endpoint_id: u16,
72 pub video_stream_id: Option<u8>,
73 pub audio_stream_id: Option<u8>,
74 pub ice_transport_policy: String,
75 pub metadata_enabled: bool,
76 pub s_frame_config: SFrame,
77 pub video_streams: Vec<u8>,
78 pub audio_streams: Vec<u8>,
79}
80
81pub fn encode_provide_offer(params: ProvideOfferParams) -> anyhow::Result<Vec<u8>> {
83 let mut s_frame_config_fields = Vec::new();
85 if let Some(x) = params.s_frame_config.cipher_suite { s_frame_config_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
86 if let Some(x) = params.s_frame_config.base_key { s_frame_config_fields.push((1, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
87 if let Some(x) = params.s_frame_config.kid { s_frame_config_fields.push((2, tlv::TlvItemValueEnc::OctetString(x.clone())).into()); }
88 let tlv = tlv::TlvItemEnc {
89 tag: 0,
90 value: tlv::TlvItemValueEnc::StructInvisible(vec![
91 (0, tlv::TlvItemValueEnc::UInt8(params.web_rtc_session_id.unwrap_or(0))).into(),
92 (1, tlv::TlvItemValueEnc::String(params.sdp)).into(),
93 (2, tlv::TlvItemValueEnc::UInt8(params.stream_usage)).into(),
94 (3, tlv::TlvItemValueEnc::UInt16(params.originating_endpoint_id)).into(),
95 (4, tlv::TlvItemValueEnc::UInt8(params.video_stream_id.unwrap_or(0))).into(),
96 (5, tlv::TlvItemValueEnc::UInt8(params.audio_stream_id.unwrap_or(0))).into(),
97 (7, tlv::TlvItemValueEnc::String(params.ice_transport_policy)).into(),
98 (8, tlv::TlvItemValueEnc::Bool(params.metadata_enabled)).into(),
99 (9, tlv::TlvItemValueEnc::StructInvisible(s_frame_config_fields)).into(),
100 (10, tlv::TlvItemValueEnc::StructAnon(params.video_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
101 (11, tlv::TlvItemValueEnc::StructAnon(params.audio_streams.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v)).into()).collect())).into(),
102 ]),
103 };
104 Ok(tlv.encode()?)
105}
106
107pub fn encode_provide_answer(web_rtc_session_id: u8, sdp: String) -> anyhow::Result<Vec<u8>> {
109 let tlv = tlv::TlvItemEnc {
110 tag: 0,
111 value: tlv::TlvItemValueEnc::StructInvisible(vec![
112 (0, tlv::TlvItemValueEnc::UInt8(web_rtc_session_id)).into(),
113 (1, tlv::TlvItemValueEnc::String(sdp)).into(),
114 ]),
115 };
116 Ok(tlv.encode()?)
117}
118
119pub fn encode_provide_ice_candidates(web_rtc_session_id: u8) -> anyhow::Result<Vec<u8>> {
121 let tlv = tlv::TlvItemEnc {
122 tag: 0,
123 value: tlv::TlvItemValueEnc::StructInvisible(vec![
124 (0, tlv::TlvItemValueEnc::UInt8(web_rtc_session_id)).into(),
125 ]),
126 };
127 Ok(tlv.encode()?)
128}
129
130pub fn encode_end_session(web_rtc_session_id: u8, reason: u8) -> anyhow::Result<Vec<u8>> {
132 let tlv = tlv::TlvItemEnc {
133 tag: 0,
134 value: tlv::TlvItemValueEnc::StructInvisible(vec![
135 (0, tlv::TlvItemValueEnc::UInt8(web_rtc_session_id)).into(),
136 (1, tlv::TlvItemValueEnc::UInt8(reason)).into(),
137 ]),
138 };
139 Ok(tlv.encode()?)
140}
141
142pub fn decode_current_sessions(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<u8>> {
146 let mut res = Vec::new();
147 if let tlv::TlvItemValue::List(v) = inp {
148 for item in v {
149 if let tlv::TlvItemValue::Int(i) = &item.value {
150 res.push(*i as u8);
151 }
152 }
153 }
154 Ok(res)
155}
156
157
158pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
170 if cluster_id != 0x0553 {
172 return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0553, got {}\"}}", cluster_id);
173 }
174
175 match attribute_id {
176 0x0000 => {
177 match decode_current_sessions(tlv_value) {
178 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
179 Err(e) => format!("{{\"error\": \"{}\"}}", e),
180 }
181 }
182 _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
183 }
184}
185
186pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
191 vec![
192 (0x0000, "CurrentSessions"),
193 ]
194}
195
196pub fn get_command_list() -> Vec<(u32, &'static str)> {
199 vec![
200 (0x00, "SolicitOffer"),
201 (0x02, "ProvideOffer"),
202 (0x04, "ProvideAnswer"),
203 (0x05, "ProvideICECandidates"),
204 (0x06, "EndSession"),
205 ]
206}
207
208pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
209 match cmd_id {
210 0x00 => Some("SolicitOffer"),
211 0x02 => Some("ProvideOffer"),
212 0x04 => Some("ProvideAnswer"),
213 0x05 => Some("ProvideICECandidates"),
214 0x06 => Some("EndSession"),
215 _ => None,
216 }
217}
218
219pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
220 match cmd_id {
221 0x00 => Some(vec![
222 crate::clusters::codec::CommandField { tag: 0, name: "stream_usage", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
223 crate::clusters::codec::CommandField { tag: 1, name: "originating_endpoint_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
224 crate::clusters::codec::CommandField { tag: 2, name: "video_stream_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: true },
225 crate::clusters::codec::CommandField { tag: 3, name: "audio_stream_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: true },
226 crate::clusters::codec::CommandField { tag: 5, name: "ice_transport_policy", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
227 crate::clusters::codec::CommandField { tag: 6, name: "metadata_enabled", kind: crate::clusters::codec::FieldKind::Bool, optional: false, nullable: false },
228 crate::clusters::codec::CommandField { tag: 7, name: "s_frame_config", kind: crate::clusters::codec::FieldKind::Struct { name: "SFrameStruct" }, optional: true, nullable: false },
229 crate::clusters::codec::CommandField { tag: 8, name: "video_streams", kind: crate::clusters::codec::FieldKind::List { entry_type: "VideoStreamID" }, optional: true, nullable: false },
230 crate::clusters::codec::CommandField { tag: 9, name: "audio_streams", kind: crate::clusters::codec::FieldKind::List { entry_type: "AudioStreamID" }, optional: true, nullable: false },
231 ]),
232 0x02 => Some(vec![
233 crate::clusters::codec::CommandField { tag: 0, name: "web_rtc_session_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: true },
234 crate::clusters::codec::CommandField { tag: 1, name: "sdp", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
235 crate::clusters::codec::CommandField { tag: 2, name: "stream_usage", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
236 crate::clusters::codec::CommandField { tag: 3, name: "originating_endpoint_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
237 crate::clusters::codec::CommandField { tag: 4, name: "video_stream_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: true },
238 crate::clusters::codec::CommandField { tag: 5, name: "audio_stream_id", kind: crate::clusters::codec::FieldKind::U32, optional: true, nullable: true },
239 crate::clusters::codec::CommandField { tag: 7, name: "ice_transport_policy", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
240 crate::clusters::codec::CommandField { tag: 8, name: "metadata_enabled", kind: crate::clusters::codec::FieldKind::Bool, optional: false, nullable: false },
241 crate::clusters::codec::CommandField { tag: 9, name: "s_frame_config", kind: crate::clusters::codec::FieldKind::Struct { name: "SFrameStruct" }, optional: true, nullable: false },
242 crate::clusters::codec::CommandField { tag: 10, name: "video_streams", kind: crate::clusters::codec::FieldKind::List { entry_type: "VideoStreamID" }, optional: true, nullable: false },
243 crate::clusters::codec::CommandField { tag: 11, name: "audio_streams", kind: crate::clusters::codec::FieldKind::List { entry_type: "AudioStreamID" }, optional: true, nullable: false },
244 ]),
245 0x04 => Some(vec![
246 crate::clusters::codec::CommandField { tag: 0, name: "web_rtc_session_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
247 crate::clusters::codec::CommandField { tag: 1, name: "sdp", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
248 ]),
249 0x05 => Some(vec![
250 crate::clusters::codec::CommandField { tag: 0, name: "web_rtc_session_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
251 ]),
252 0x06 => Some(vec![
253 crate::clusters::codec::CommandField { tag: 0, name: "web_rtc_session_id", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
254 crate::clusters::codec::CommandField { tag: 1, name: "reason", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
255 ]),
256 _ => None,
257 }
258}
259
260pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
261 match cmd_id {
262 0x00 => Err(anyhow::anyhow!("command \"SolicitOffer\" has complex args: use raw mode")),
263 0x02 => Err(anyhow::anyhow!("command \"ProvideOffer\" has complex args: use raw mode")),
264 0x04 => {
265 let web_rtc_session_id = crate::clusters::codec::json_util::get_u8(args, "web_rtc_session_id")?;
266 let sdp = crate::clusters::codec::json_util::get_string(args, "sdp")?;
267 encode_provide_answer(web_rtc_session_id, sdp)
268 }
269 0x05 => {
270 let web_rtc_session_id = crate::clusters::codec::json_util::get_u8(args, "web_rtc_session_id")?;
271 encode_provide_ice_candidates(web_rtc_session_id)
272 }
273 0x06 => {
274 let web_rtc_session_id = crate::clusters::codec::json_util::get_u8(args, "web_rtc_session_id")?;
275 let reason = crate::clusters::codec::json_util::get_u8(args, "reason")?;
276 encode_end_session(web_rtc_session_id, reason)
277 }
278 _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
279 }
280}
281
282#[derive(Debug, serde::Serialize)]
283pub struct SolicitOfferResponse {
284 pub web_rtc_session_id: Option<u8>,
285 pub deferred_offer: Option<bool>,
286 pub video_stream_id: Option<u8>,
287 pub audio_stream_id: Option<u8>,
288}
289
290#[derive(Debug, serde::Serialize)]
291pub struct ProvideOfferResponse {
292 pub web_rtc_session_id: Option<u8>,
293 pub video_stream_id: Option<u8>,
294 pub audio_stream_id: Option<u8>,
295}
296
297pub fn decode_solicit_offer_response(inp: &tlv::TlvItemValue) -> anyhow::Result<SolicitOfferResponse> {
301 if let tlv::TlvItemValue::List(_fields) = inp {
302 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
303 Ok(SolicitOfferResponse {
304 web_rtc_session_id: item.get_int(&[0]).map(|v| v as u8),
305 deferred_offer: item.get_bool(&[1]),
306 video_stream_id: item.get_int(&[2]).map(|v| v as u8),
307 audio_stream_id: item.get_int(&[3]).map(|v| v as u8),
308 })
309 } else {
310 Err(anyhow::anyhow!("Expected struct fields"))
311 }
312}
313
314pub fn decode_provide_offer_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ProvideOfferResponse> {
316 if let tlv::TlvItemValue::List(_fields) = inp {
317 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
318 Ok(ProvideOfferResponse {
319 web_rtc_session_id: item.get_int(&[0]).map(|v| v as u8),
320 video_stream_id: item.get_int(&[1]).map(|v| v as u8),
321 audio_stream_id: item.get_int(&[2]).map(|v| v as u8),
322 })
323 } else {
324 Err(anyhow::anyhow!("Expected struct fields"))
325 }
326}
327
328pub async fn solicit_offer(conn: &crate::controller::Connection, endpoint: u16, params: SolicitOfferParams) -> anyhow::Result<SolicitOfferResponse> {
332 let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WEBRTC_TRANSPORT_PROVIDER, crate::clusters::defs::CLUSTER_WEBRTC_TRANSPORT_PROVIDER_CMD_ID_SOLICITOFFER, &encode_solicit_offer(params)?).await?;
333 decode_solicit_offer_response(&tlv)
334}
335
336pub async fn provide_offer(conn: &crate::controller::Connection, endpoint: u16, params: ProvideOfferParams) -> anyhow::Result<ProvideOfferResponse> {
338 let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WEBRTC_TRANSPORT_PROVIDER, crate::clusters::defs::CLUSTER_WEBRTC_TRANSPORT_PROVIDER_CMD_ID_PROVIDEOFFER, &encode_provide_offer(params)?).await?;
339 decode_provide_offer_response(&tlv)
340}
341
342pub async fn provide_answer(conn: &crate::controller::Connection, endpoint: u16, web_rtc_session_id: u8, sdp: String) -> anyhow::Result<()> {
344 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WEBRTC_TRANSPORT_PROVIDER, crate::clusters::defs::CLUSTER_WEBRTC_TRANSPORT_PROVIDER_CMD_ID_PROVIDEANSWER, &encode_provide_answer(web_rtc_session_id, sdp)?).await?;
345 Ok(())
346}
347
348pub async fn provide_ice_candidates(conn: &crate::controller::Connection, endpoint: u16, web_rtc_session_id: u8) -> anyhow::Result<()> {
350 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WEBRTC_TRANSPORT_PROVIDER, crate::clusters::defs::CLUSTER_WEBRTC_TRANSPORT_PROVIDER_CMD_ID_PROVIDEICECANDIDATES, &encode_provide_ice_candidates(web_rtc_session_id)?).await?;
351 Ok(())
352}
353
354pub async fn end_session(conn: &crate::controller::Connection, endpoint: u16, web_rtc_session_id: u8, reason: u8) -> anyhow::Result<()> {
356 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_WEBRTC_TRANSPORT_PROVIDER, crate::clusters::defs::CLUSTER_WEBRTC_TRANSPORT_PROVIDER_CMD_ID_ENDSESSION, &encode_end_session(web_rtc_session_id, reason)?).await?;
357 Ok(())
358}
359
360pub async fn read_current_sessions(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<u8>> {
362 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_WEBRTC_TRANSPORT_PROVIDER, crate::clusters::defs::CLUSTER_WEBRTC_TRANSPORT_PROVIDER_ATTR_ID_CURRENTSESSIONS).await?;
363 decode_current_sessions(&tlv)
364}
365