matc/clusters/codec/
identify.rs

1//! Matter TLV encoders and decoders for Identify Cluster
2//! Cluster ID: 0x0003
3//!
4//! This file is automatically generated from Identify.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 EffectIdentifier {
18    /// e.g., Light is turned on/off once.
19    Blink = 0,
20    /// e.g., Light is turned on/off over 1 second and repeated 15 times.
21    Breathe = 1,
22    /// e.g., Colored light turns green for 1 second; non-colored light flashes twice.
23    Okay = 2,
24    /// e.g., Colored light turns orange for 8 seconds; non-colored light switches to the maximum brightness for 0.5s and then minimum brightness for 7.5s.
25    Channelchange = 11,
26    /// Complete the current effect sequence before terminating. e.g., if in the middle of a breathe effect (as above), first complete the current 1s breathe effect and then terminate the effect.
27    Finisheffect = 254,
28    /// Terminate the effect as soon as possible.
29    Stopeffect = 255,
30}
31
32impl EffectIdentifier {
33    /// Convert from u8 value
34    pub fn from_u8(value: u8) -> Option<Self> {
35        match value {
36            0 => Some(EffectIdentifier::Blink),
37            1 => Some(EffectIdentifier::Breathe),
38            2 => Some(EffectIdentifier::Okay),
39            11 => Some(EffectIdentifier::Channelchange),
40            254 => Some(EffectIdentifier::Finisheffect),
41            255 => Some(EffectIdentifier::Stopeffect),
42            _ => None,
43        }
44    }
45
46    /// Convert to u8 value
47    pub fn to_u8(self) -> u8 {
48        self as u8
49    }
50}
51
52impl From<EffectIdentifier> for u8 {
53    fn from(val: EffectIdentifier) -> Self {
54        val as u8
55    }
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
59#[repr(u8)]
60pub enum EffectVariant {
61    /// Indicates the default effect is used
62    Default = 0,
63}
64
65impl EffectVariant {
66    /// Convert from u8 value
67    pub fn from_u8(value: u8) -> Option<Self> {
68        match value {
69            0 => Some(EffectVariant::Default),
70            _ => None,
71        }
72    }
73
74    /// Convert to u8 value
75    pub fn to_u8(self) -> u8 {
76        self as u8
77    }
78}
79
80impl From<EffectVariant> for u8 {
81    fn from(val: EffectVariant) -> Self {
82        val as u8
83    }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
87#[repr(u8)]
88pub enum IdentifyType {
89    /// No presentation.
90    None = 0,
91    /// Light output of a lighting product.
92    Lightoutput = 1,
93    /// Typically a small LED.
94    Visibleindicator = 2,
95    Audiblebeep = 3,
96    /// Presentation will be visible on display screen.
97    Display = 4,
98    /// Presentation will be conveyed by actuator functionality such as through a window blind operation or in-wall relay.
99    Actuator = 5,
100}
101
102impl IdentifyType {
103    /// Convert from u8 value
104    pub fn from_u8(value: u8) -> Option<Self> {
105        match value {
106            0 => Some(IdentifyType::None),
107            1 => Some(IdentifyType::Lightoutput),
108            2 => Some(IdentifyType::Visibleindicator),
109            3 => Some(IdentifyType::Audiblebeep),
110            4 => Some(IdentifyType::Display),
111            5 => Some(IdentifyType::Actuator),
112            _ => None,
113        }
114    }
115
116    /// Convert to u8 value
117    pub fn to_u8(self) -> u8 {
118        self as u8
119    }
120}
121
122impl From<IdentifyType> for u8 {
123    fn from(val: IdentifyType) -> Self {
124        val as u8
125    }
126}
127
128// Command encoders
129
130/// Encode Identify command (0x00)
131pub fn encode_identify(identify_time: u16) -> anyhow::Result<Vec<u8>> {
132    let tlv = tlv::TlvItemEnc {
133        tag: 0,
134        value: tlv::TlvItemValueEnc::StructInvisible(vec![
135        (0, tlv::TlvItemValueEnc::UInt16(identify_time)).into(),
136        ]),
137    };
138    Ok(tlv.encode()?)
139}
140
141/// Encode TriggerEffect command (0x40)
142pub fn encode_trigger_effect(effect_identifier: EffectIdentifier, effect_variant: EffectVariant) -> anyhow::Result<Vec<u8>> {
143    let tlv = tlv::TlvItemEnc {
144        tag: 0,
145        value: tlv::TlvItemValueEnc::StructInvisible(vec![
146        (0, tlv::TlvItemValueEnc::UInt8(effect_identifier.to_u8())).into(),
147        (1, tlv::TlvItemValueEnc::UInt8(effect_variant.to_u8())).into(),
148        ]),
149    };
150    Ok(tlv.encode()?)
151}
152
153// Attribute decoders
154
155/// Decode IdentifyTime attribute (0x0000)
156pub fn decode_identify_time(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
157    if let tlv::TlvItemValue::Int(v) = inp {
158        Ok(*v as u16)
159    } else {
160        Err(anyhow::anyhow!("Expected UInt16"))
161    }
162}
163
164/// Decode IdentifyType attribute (0x0001)
165pub fn decode_identify_type(inp: &tlv::TlvItemValue) -> anyhow::Result<IdentifyType> {
166    if let tlv::TlvItemValue::Int(v) = inp {
167        IdentifyType::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
168    } else {
169        Err(anyhow::anyhow!("Expected Integer"))
170    }
171}
172
173
174// JSON dispatcher function
175
176/// Decode attribute value and return as JSON string
177///
178/// # Parameters
179/// * `cluster_id` - The cluster identifier
180/// * `attribute_id` - The attribute identifier
181/// * `tlv_value` - The TLV value to decode
182///
183/// # Returns
184/// JSON string representation of the decoded value or error
185pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
186    // Verify this is the correct cluster
187    if cluster_id != 0x0003 {
188        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0003, got {}\"}}", cluster_id);
189    }
190
191    match attribute_id {
192        0x0000 => {
193            match decode_identify_time(tlv_value) {
194                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
195                Err(e) => format!("{{\"error\": \"{}\"}}", e),
196            }
197        }
198        0x0001 => {
199            match decode_identify_type(tlv_value) {
200                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
201                Err(e) => format!("{{\"error\": \"{}\"}}", e),
202            }
203        }
204        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
205    }
206}
207
208/// Get list of all attributes supported by this cluster
209///
210/// # Returns
211/// Vector of tuples containing (attribute_id, attribute_name)
212pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
213    vec![
214        (0x0000, "IdentifyTime"),
215        (0x0001, "IdentifyType"),
216    ]
217}
218
219// Command listing
220
221pub fn get_command_list() -> Vec<(u32, &'static str)> {
222    vec![
223        (0x00, "Identify"),
224        (0x40, "TriggerEffect"),
225    ]
226}
227
228pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
229    match cmd_id {
230        0x00 => Some("Identify"),
231        0x40 => Some("TriggerEffect"),
232        _ => None,
233    }
234}
235
236pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
237    match cmd_id {
238        0x00 => Some(vec![
239            crate::clusters::codec::CommandField { tag: 0, name: "identify_time", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
240        ]),
241        0x40 => Some(vec![
242            crate::clusters::codec::CommandField { tag: 0, name: "effect_identifier", kind: crate::clusters::codec::FieldKind::Enum { name: "EffectIdentifier", variants: &[(0, "Blink"), (1, "Breathe"), (2, "Okay"), (11, "Channelchange"), (254, "Finisheffect"), (255, "Stopeffect")] }, optional: false, nullable: false },
243            crate::clusters::codec::CommandField { tag: 1, name: "effect_variant", kind: crate::clusters::codec::FieldKind::Enum { name: "EffectVariant", variants: &[(0, "Default")] }, optional: false, nullable: false },
244        ]),
245        _ => None,
246    }
247}
248
249pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
250    match cmd_id {
251        0x00 => {
252        let identify_time = crate::clusters::codec::json_util::get_u16(args, "identify_time")?;
253        encode_identify(identify_time)
254        }
255        0x40 => {
256        let effect_identifier = {
257            let n = crate::clusters::codec::json_util::get_u64(args, "effect_identifier")?;
258            EffectIdentifier::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid EffectIdentifier: {}", n))?
259        };
260        let effect_variant = {
261            let n = crate::clusters::codec::json_util::get_u64(args, "effect_variant")?;
262            EffectVariant::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid EffectVariant: {}", n))?
263        };
264        encode_trigger_effect(effect_identifier, effect_variant)
265        }
266        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
267    }
268}
269
270// Typed facade (invokes + reads)
271
272/// Invoke `Identify` command on cluster `Identify`.
273pub async fn identify(conn: &crate::controller::Connection, endpoint: u16, identify_time: u16) -> anyhow::Result<()> {
274    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_CMD_ID_IDENTIFY, &encode_identify(identify_time)?).await?;
275    Ok(())
276}
277
278/// Invoke `TriggerEffect` command on cluster `Identify`.
279pub async fn trigger_effect(conn: &crate::controller::Connection, endpoint: u16, effect_identifier: EffectIdentifier, effect_variant: EffectVariant) -> anyhow::Result<()> {
280    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_CMD_ID_TRIGGEREFFECT, &encode_trigger_effect(effect_identifier, effect_variant)?).await?;
281    Ok(())
282}
283
284/// Read `IdentifyTime` attribute from cluster `Identify`.
285pub async fn read_identify_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
286    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_ATTR_ID_IDENTIFYTIME).await?;
287    decode_identify_time(&tlv)
288}
289
290/// Read `IdentifyType` attribute from cluster `Identify`.
291pub async fn read_identify_type(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<IdentifyType> {
292    let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_IDENTIFY, crate::clusters::defs::CLUSTER_IDENTIFY_ATTR_ID_IDENTIFYTYPE).await?;
293    decode_identify_type(&tlv)
294}
295