matc/clusters/codec/
mode_select.rs

1//! Matter TLV encoders and decoders for Mode Select Cluster
2//! Cluster ID: 0x0050
3//!
4//! This file is automatically generated from ModeSelect.xml
5
6#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13// Struct definitions
14
15#[derive(Debug, serde::Serialize)]
16pub struct ModeOption {
17    pub label: Option<String>,
18    pub mode: Option<u8>,
19    pub semantic_tags: Option<Vec<SemanticTag>>,
20}
21
22#[derive(Debug, serde::Serialize)]
23pub struct SemanticTag {
24    pub mfg_code: Option<u16>,
25    pub value: Option<u16>,
26}
27
28// Command encoders
29
30/// Encode ChangeToMode command (0x00)
31pub fn encode_change_to_mode(new_mode: u8) -> anyhow::Result<Vec<u8>> {
32    let tlv = tlv::TlvItemEnc {
33        tag: 0,
34        value: tlv::TlvItemValueEnc::StructInvisible(vec![
35        (0, tlv::TlvItemValueEnc::UInt8(new_mode)).into(),
36        ]),
37    };
38    Ok(tlv.encode()?)
39}
40
41// Attribute decoders
42
43/// Decode Description attribute (0x0000)
44pub fn decode_description(inp: &tlv::TlvItemValue) -> anyhow::Result<String> {
45    if let tlv::TlvItemValue::String(v) = inp {
46        Ok(v.clone())
47    } else {
48        Err(anyhow::anyhow!("Expected String"))
49    }
50}
51
52/// Decode StandardNamespace attribute (0x0001)
53pub fn decode_standard_namespace(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u16>> {
54    if let tlv::TlvItemValue::Int(v) = inp {
55        Ok(Some(*v as u16))
56    } else {
57        Ok(None)
58    }
59}
60
61/// Decode SupportedModes attribute (0x0002)
62pub fn decode_supported_modes(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ModeOption>> {
63    let mut res = Vec::new();
64    if let tlv::TlvItemValue::List(v) = inp {
65        for item in v {
66            res.push(ModeOption {
67                label: item.get_string_owned(&[0]),
68                mode: item.get_int(&[1]).map(|v| v as u8),
69                semantic_tags: {
70                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
71                        let mut items = Vec::new();
72                        for list_item in l {
73                            items.push(SemanticTag {
74                mfg_code: list_item.get_int(&[0]).map(|v| v as u16),
75                value: list_item.get_int(&[1]).map(|v| v as u16),
76                            });
77                        }
78                        Some(items)
79                    } else {
80                        None
81                    }
82                },
83            });
84        }
85    }
86    Ok(res)
87}
88
89/// Decode CurrentMode attribute (0x0003)
90pub fn decode_current_mode(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
91    if let tlv::TlvItemValue::Int(v) = inp {
92        Ok(*v as u8)
93    } else {
94        Err(anyhow::anyhow!("Expected UInt8"))
95    }
96}
97
98/// Decode StartUpMode attribute (0x0004)
99pub fn decode_start_up_mode(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
100    if let tlv::TlvItemValue::Int(v) = inp {
101        Ok(Some(*v as u8))
102    } else {
103        Ok(None)
104    }
105}
106
107/// Decode OnMode attribute (0x0005)
108pub fn decode_on_mode(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
109    if let tlv::TlvItemValue::Int(v) = inp {
110        Ok(Some(*v as u8))
111    } else {
112        Ok(None)
113    }
114}
115
116
117// JSON dispatcher function
118
119/// Decode attribute value and return as JSON string
120///
121/// # Parameters
122/// * `cluster_id` - The cluster identifier
123/// * `attribute_id` - The attribute identifier
124/// * `tlv_value` - The TLV value to decode
125///
126/// # Returns
127/// JSON string representation of the decoded value or error
128pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
129    // Verify this is the correct cluster
130    if cluster_id != 0x0050 {
131        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0050, got {}\"}}", cluster_id);
132    }
133
134    match attribute_id {
135        0x0000 => {
136            match decode_description(tlv_value) {
137                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
138                Err(e) => format!("{{\"error\": \"{}\"}}", e),
139            }
140        }
141        0x0001 => {
142            match decode_standard_namespace(tlv_value) {
143                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
144                Err(e) => format!("{{\"error\": \"{}\"}}", e),
145            }
146        }
147        0x0002 => {
148            match decode_supported_modes(tlv_value) {
149                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
150                Err(e) => format!("{{\"error\": \"{}\"}}", e),
151            }
152        }
153        0x0003 => {
154            match decode_current_mode(tlv_value) {
155                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
156                Err(e) => format!("{{\"error\": \"{}\"}}", e),
157            }
158        }
159        0x0004 => {
160            match decode_start_up_mode(tlv_value) {
161                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
162                Err(e) => format!("{{\"error\": \"{}\"}}", e),
163            }
164        }
165        0x0005 => {
166            match decode_on_mode(tlv_value) {
167                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
168                Err(e) => format!("{{\"error\": \"{}\"}}", e),
169            }
170        }
171        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
172    }
173}
174
175/// Get list of all attributes supported by this cluster
176///
177/// # Returns
178/// Vector of tuples containing (attribute_id, attribute_name)
179pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
180    vec![
181        (0x0000, "Description"),
182        (0x0001, "StandardNamespace"),
183        (0x0002, "SupportedModes"),
184        (0x0003, "CurrentMode"),
185        (0x0004, "StartUpMode"),
186        (0x0005, "OnMode"),
187    ]
188}
189
190// Command listing
191
192pub fn get_command_list() -> Vec<(u32, &'static str)> {
193    vec![
194        (0x00, "ChangeToMode"),
195    ]
196}
197
198pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
199    match cmd_id {
200        0x00 => Some("ChangeToMode"),
201        _ => None,
202    }
203}
204
205pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
206    match cmd_id {
207        0x00 => Some(vec![
208            crate::clusters::codec::CommandField { tag: 0, name: "new_mode", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
209        ]),
210        _ => None,
211    }
212}
213
214pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
215    match cmd_id {
216        0x00 => {
217        let new_mode = crate::clusters::codec::json_util::get_u8(args, "new_mode")?;
218        encode_change_to_mode(new_mode)
219        }
220        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
221    }
222}
223
224// Typed facade (invokes + reads)
225
226/// Invoke `ChangeToMode` command on cluster `Mode Select`.
227pub async fn change_to_mode(conn: &crate::controller::Connection, endpoint: u16, new_mode: u8) -> anyhow::Result<()> {
228    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_CMD_ID_CHANGETOMODE, &encode_change_to_mode(new_mode)?).await?;
229    Ok(())
230}
231
232/// Read `Description` attribute from cluster `Mode Select`.
233pub async fn read_description(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<String> {
234    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_DESCRIPTION).await?;
235    decode_description(&tlv)
236}
237
238/// Read `StandardNamespace` attribute from cluster `Mode Select`.
239pub async fn read_standard_namespace(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
240    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_STANDARDNAMESPACE).await?;
241    decode_standard_namespace(&tlv)
242}
243
244/// Read `SupportedModes` attribute from cluster `Mode Select`.
245pub async fn read_supported_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ModeOption>> {
246    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_SUPPORTEDMODES).await?;
247    decode_supported_modes(&tlv)
248}
249
250/// Read `CurrentMode` attribute from cluster `Mode Select`.
251pub async fn read_current_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
252    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_CURRENTMODE).await?;
253    decode_current_mode(&tlv)
254}
255
256/// Read `StartUpMode` attribute from cluster `Mode Select`.
257pub async fn read_start_up_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
258    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_STARTUPMODE).await?;
259    decode_start_up_mode(&tlv)
260}
261
262/// Read `OnMode` attribute from cluster `Mode Select`.
263pub async fn read_on_mode(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
264    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_MODE_SELECT, crate::clusters::defs::CLUSTER_MODE_SELECT_ATTR_ID_ONMODE).await?;
265    decode_on_mode(&tlv)
266}
267