matc/clusters/codec/
audio_output.rs

1//! Matter TLV encoders and decoders for Audio Output Cluster
2//! Cluster ID: 0x050B
3//!
4//! This file is automatically generated from AudioOutput.xml
5
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Enum definitions
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16#[repr(u8)]
17pub enum OutputType {
18    /// HDMI
19    Hdmi = 0,
20    Bt = 1,
21    Optical = 2,
22    Headphone = 3,
23    Internal = 4,
24    Other = 5,
25}
26
27impl OutputType {
28    /// Convert from u8 value
29    pub fn from_u8(value: u8) -> Option<Self> {
30        match value {
31            0 => Some(OutputType::Hdmi),
32            1 => Some(OutputType::Bt),
33            2 => Some(OutputType::Optical),
34            3 => Some(OutputType::Headphone),
35            4 => Some(OutputType::Internal),
36            5 => Some(OutputType::Other),
37            _ => None,
38        }
39    }
40
41    /// Convert to u8 value
42    pub fn to_u8(self) -> u8 {
43        self as u8
44    }
45}
46
47impl From<OutputType> for u8 {
48    fn from(val: OutputType) -> Self {
49        val as u8
50    }
51}
52
53// Struct definitions
54
55#[derive(Debug, serde::Serialize)]
56pub struct OutputInfo {
57    pub index: Option<u8>,
58    pub output_type: Option<OutputType>,
59    pub name: Option<String>,
60}
61
62// Command encoders
63
64/// Encode SelectOutput command (0x00)
65pub fn encode_select_output(index: u8) -> anyhow::Result<Vec<u8>> {
66    let tlv = tlv::TlvItemEnc {
67        tag: 0,
68        value: tlv::TlvItemValueEnc::StructInvisible(vec![
69        (0, tlv::TlvItemValueEnc::UInt8(index)).into(),
70        ]),
71    };
72    Ok(tlv.encode()?)
73}
74
75/// Encode RenameOutput command (0x01)
76pub fn encode_rename_output(index: u8, name: String) -> anyhow::Result<Vec<u8>> {
77    let tlv = tlv::TlvItemEnc {
78        tag: 0,
79        value: tlv::TlvItemValueEnc::StructInvisible(vec![
80        (0, tlv::TlvItemValueEnc::UInt8(index)).into(),
81        (1, tlv::TlvItemValueEnc::String(name)).into(),
82        ]),
83    };
84    Ok(tlv.encode()?)
85}
86
87// Attribute decoders
88
89/// Decode OutputList attribute (0x0000)
90pub fn decode_output_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<OutputInfo>> {
91    let mut res = Vec::new();
92    if let tlv::TlvItemValue::List(v) = inp {
93        for item in v {
94            res.push(OutputInfo {
95                index: item.get_int(&[0]).map(|v| v as u8),
96                output_type: item.get_int(&[1]).and_then(|v| OutputType::from_u8(v as u8)),
97                name: item.get_string_owned(&[2]),
98            });
99        }
100    }
101    Ok(res)
102}
103
104/// Decode CurrentOutput attribute (0x0001)
105pub fn decode_current_output(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
106    if let tlv::TlvItemValue::Int(v) = inp {
107        Ok(*v as u8)
108    } else {
109        Err(anyhow::anyhow!("Expected UInt8"))
110    }
111}
112
113
114// JSON dispatcher function
115
116/// Decode attribute value and return as JSON string
117///
118/// # Parameters
119/// * `cluster_id` - The cluster identifier
120/// * `attribute_id` - The attribute identifier
121/// * `tlv_value` - The TLV value to decode
122///
123/// # Returns
124/// JSON string representation of the decoded value or error
125pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
126    // Verify this is the correct cluster
127    if cluster_id != 0x050B {
128        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x050B, got {}\"}}", cluster_id);
129    }
130
131    match attribute_id {
132        0x0000 => {
133            match decode_output_list(tlv_value) {
134                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
135                Err(e) => format!("{{\"error\": \"{}\"}}", e),
136            }
137        }
138        0x0001 => {
139            match decode_current_output(tlv_value) {
140                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
141                Err(e) => format!("{{\"error\": \"{}\"}}", e),
142            }
143        }
144        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
145    }
146}
147
148/// Get list of all attributes supported by this cluster
149///
150/// # Returns
151/// Vector of tuples containing (attribute_id, attribute_name)
152pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
153    vec![
154        (0x0000, "OutputList"),
155        (0x0001, "CurrentOutput"),
156    ]
157}
158
159// Command listing
160
161pub fn get_command_list() -> Vec<(u32, &'static str)> {
162    vec![
163        (0x00, "SelectOutput"),
164        (0x01, "RenameOutput"),
165    ]
166}
167
168pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
169    match cmd_id {
170        0x00 => Some("SelectOutput"),
171        0x01 => Some("RenameOutput"),
172        _ => None,
173    }
174}
175
176pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
177    match cmd_id {
178        0x00 => Some(vec![
179            crate::clusters::codec::CommandField { tag: 0, name: "index", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
180        ]),
181        0x01 => Some(vec![
182            crate::clusters::codec::CommandField { tag: 0, name: "index", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
183            crate::clusters::codec::CommandField { tag: 1, name: "name", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: false },
184        ]),
185        _ => None,
186    }
187}
188
189pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
190    match cmd_id {
191        0x00 => {
192        let index = crate::clusters::codec::json_util::get_u8(args, "index")?;
193        encode_select_output(index)
194        }
195        0x01 => {
196        let index = crate::clusters::codec::json_util::get_u8(args, "index")?;
197        let name = crate::clusters::codec::json_util::get_string(args, "name")?;
198        encode_rename_output(index, name)
199        }
200        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
201    }
202}
203
204// Typed facade (invokes + reads)
205
206/// Invoke `SelectOutput` command on cluster `Audio Output`.
207pub async fn select_output(conn: &crate::controller::Connection, endpoint: u16, index: u8) -> anyhow::Result<()> {
208    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_CMD_ID_SELECTOUTPUT, &encode_select_output(index)?).await?;
209    Ok(())
210}
211
212/// Invoke `RenameOutput` command on cluster `Audio Output`.
213pub async fn rename_output(conn: &crate::controller::Connection, endpoint: u16, index: u8, name: String) -> anyhow::Result<()> {
214    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_CMD_ID_RENAMEOUTPUT, &encode_rename_output(index, name)?).await?;
215    Ok(())
216}
217
218/// Read `OutputList` attribute from cluster `Audio Output`.
219pub async fn read_output_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<OutputInfo>> {
220    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_ATTR_ID_OUTPUTLIST).await?;
221    decode_output_list(&tlv)
222}
223
224/// Read `CurrentOutput` attribute from cluster `Audio Output`.
225pub async fn read_current_output(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
226    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_AUDIO_OUTPUT, crate::clusters::defs::CLUSTER_AUDIO_OUTPUT_ATTR_ID_CURRENTOUTPUT).await?;
227    decode_current_output(&tlv)
228}
229