1#![allow(clippy::too_many_arguments)]
7
8use crate::tlv;
9use anyhow;
10use serde_json;
11
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16#[repr(u8)]
17pub enum ClosureError {
18 Physicallyblocked = 0,
20 Blockedbysensor = 1,
22 Temperaturelimited = 2,
24 Maintenancerequired = 3,
26 Internalinterference = 4,
28}
29
30impl ClosureError {
31 pub fn from_u8(value: u8) -> Option<Self> {
33 match value {
34 0 => Some(ClosureError::Physicallyblocked),
35 1 => Some(ClosureError::Blockedbysensor),
36 2 => Some(ClosureError::Temperaturelimited),
37 3 => Some(ClosureError::Maintenancerequired),
38 4 => Some(ClosureError::Internalinterference),
39 _ => None,
40 }
41 }
42
43 pub fn to_u8(self) -> u8 {
45 self as u8
46 }
47}
48
49impl From<ClosureError> for u8 {
50 fn from(val: ClosureError) -> Self {
51 val as u8
52 }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
56#[repr(u8)]
57pub enum CurrentPosition {
58 Fullyclosed = 0,
60 Fullyopened = 1,
62 Partiallyopened = 2,
64 Openedforpedestrian = 3,
66 Openedforventilation = 4,
68 Openedatsignature = 5,
70}
71
72impl CurrentPosition {
73 pub fn from_u8(value: u8) -> Option<Self> {
75 match value {
76 0 => Some(CurrentPosition::Fullyclosed),
77 1 => Some(CurrentPosition::Fullyopened),
78 2 => Some(CurrentPosition::Partiallyopened),
79 3 => Some(CurrentPosition::Openedforpedestrian),
80 4 => Some(CurrentPosition::Openedforventilation),
81 5 => Some(CurrentPosition::Openedatsignature),
82 _ => None,
83 }
84 }
85
86 pub fn to_u8(self) -> u8 {
88 self as u8
89 }
90}
91
92impl From<CurrentPosition> for u8 {
93 fn from(val: CurrentPosition) -> Self {
94 val as u8
95 }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
99#[repr(u8)]
100pub enum MainState {
101 Stopped = 0,
103 Moving = 1,
105 Waitingformotion = 2,
107 Error = 3,
109 Calibrating = 4,
111 Protected = 5,
113 Disengaged = 6,
115 Setuprequired = 7,
117}
118
119impl MainState {
120 pub fn from_u8(value: u8) -> Option<Self> {
122 match value {
123 0 => Some(MainState::Stopped),
124 1 => Some(MainState::Moving),
125 2 => Some(MainState::Waitingformotion),
126 3 => Some(MainState::Error),
127 4 => Some(MainState::Calibrating),
128 5 => Some(MainState::Protected),
129 6 => Some(MainState::Disengaged),
130 7 => Some(MainState::Setuprequired),
131 _ => None,
132 }
133 }
134
135 pub fn to_u8(self) -> u8 {
137 self as u8
138 }
139}
140
141impl From<MainState> for u8 {
142 fn from(val: MainState) -> Self {
143 val as u8
144 }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
148#[repr(u8)]
149pub enum TargetPosition {
150 Movetofullyclosed = 0,
152 Movetofullyopen = 1,
154 Movetopedestrianposition = 2,
156 Movetoventilationposition = 3,
158 Movetosignatureposition = 4,
160}
161
162impl TargetPosition {
163 pub fn from_u8(value: u8) -> Option<Self> {
165 match value {
166 0 => Some(TargetPosition::Movetofullyclosed),
167 1 => Some(TargetPosition::Movetofullyopen),
168 2 => Some(TargetPosition::Movetopedestrianposition),
169 3 => Some(TargetPosition::Movetoventilationposition),
170 4 => Some(TargetPosition::Movetosignatureposition),
171 _ => None,
172 }
173 }
174
175 pub fn to_u8(self) -> u8 {
177 self as u8
178 }
179}
180
181impl From<TargetPosition> for u8 {
182 fn from(val: TargetPosition) -> Self {
183 val as u8
184 }
185}
186
187pub type LatchControlModes = u8;
191
192pub mod latchcontrolmodes {
194 pub const REMOTE_LATCHING: u8 = 0x01;
196 pub const REMOTE_UNLATCHING: u8 = 0x02;
198}
199
200#[derive(Debug, serde::Serialize)]
203pub struct OverallCurrentState {
204 pub position: Option<CurrentPosition>,
205 pub latch: Option<bool>,
206 pub speed: Option<u8>,
207 pub secure_state: Option<bool>,
208}
209
210#[derive(Debug, serde::Serialize)]
211pub struct OverallTargetState {
212 pub position: Option<TargetPosition>,
213 pub latch: Option<bool>,
214 pub speed: Option<u8>,
215}
216
217pub fn encode_move_to(position: TargetPosition, latch: bool, speed: u8) -> anyhow::Result<Vec<u8>> {
221 let tlv = tlv::TlvItemEnc {
222 tag: 0,
223 value: tlv::TlvItemValueEnc::StructInvisible(vec![
224 (0, tlv::TlvItemValueEnc::UInt8(position.to_u8())).into(),
225 (1, tlv::TlvItemValueEnc::Bool(latch)).into(),
226 (2, tlv::TlvItemValueEnc::UInt8(speed)).into(),
227 ]),
228 };
229 Ok(tlv.encode()?)
230}
231
232pub fn decode_countdown_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
236 if let tlv::TlvItemValue::Int(v) = inp {
237 Ok(Some(*v as u32))
238 } else {
239 Ok(None)
240 }
241}
242
243pub fn decode_main_state(inp: &tlv::TlvItemValue) -> anyhow::Result<MainState> {
245 if let tlv::TlvItemValue::Int(v) = inp {
246 MainState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
247 } else {
248 Err(anyhow::anyhow!("Expected Integer"))
249 }
250}
251
252pub fn decode_current_error_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ClosureError>> {
254 let mut res = Vec::new();
255 if let tlv::TlvItemValue::List(v) = inp {
256 for item in v {
257 if let tlv::TlvItemValue::Int(i) = &item.value {
258 if let Some(enum_val) = ClosureError::from_u8(*i as u8) {
259 res.push(enum_val);
260 }
261 }
262 }
263 }
264 Ok(res)
265}
266
267pub fn decode_overall_current_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallCurrentState>> {
269 if let tlv::TlvItemValue::List(_fields) = inp {
270 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
272 Ok(Some(OverallCurrentState {
273 position: item.get_int(&[0]).and_then(|v| CurrentPosition::from_u8(v as u8)),
274 latch: item.get_bool(&[1]),
275 speed: item.get_int(&[2]).map(|v| v as u8),
276 secure_state: item.get_bool(&[3]),
277 }))
278 } else {
282 Ok(None)
283 }
285}
286
287pub fn decode_overall_target_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallTargetState>> {
289 if let tlv::TlvItemValue::List(_fields) = inp {
290 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
292 Ok(Some(OverallTargetState {
293 position: item.get_int(&[0]).and_then(|v| TargetPosition::from_u8(v as u8)),
294 latch: item.get_bool(&[1]),
295 speed: item.get_int(&[2]).map(|v| v as u8),
296 }))
297 } else {
301 Ok(None)
302 }
304}
305
306pub fn decode_latch_control_modes(inp: &tlv::TlvItemValue) -> anyhow::Result<LatchControlModes> {
308 if let tlv::TlvItemValue::Int(v) = inp {
309 Ok(*v as u8)
310 } else {
311 Err(anyhow::anyhow!("Expected Integer"))
312 }
313}
314
315
316pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
328 if cluster_id != 0x0104 {
330 return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0104, got {}\"}}", cluster_id);
331 }
332
333 match attribute_id {
334 0x0000 => {
335 match decode_countdown_time(tlv_value) {
336 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
337 Err(e) => format!("{{\"error\": \"{}\"}}", e),
338 }
339 }
340 0x0001 => {
341 match decode_main_state(tlv_value) {
342 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
343 Err(e) => format!("{{\"error\": \"{}\"}}", e),
344 }
345 }
346 0x0002 => {
347 match decode_current_error_list(tlv_value) {
348 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
349 Err(e) => format!("{{\"error\": \"{}\"}}", e),
350 }
351 }
352 0x0003 => {
353 match decode_overall_current_state(tlv_value) {
354 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
355 Err(e) => format!("{{\"error\": \"{}\"}}", e),
356 }
357 }
358 0x0004 => {
359 match decode_overall_target_state(tlv_value) {
360 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
361 Err(e) => format!("{{\"error\": \"{}\"}}", e),
362 }
363 }
364 0x0005 => {
365 match decode_latch_control_modes(tlv_value) {
366 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
367 Err(e) => format!("{{\"error\": \"{}\"}}", e),
368 }
369 }
370 _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
371 }
372}
373
374pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
379 vec![
380 (0x0000, "CountdownTime"),
381 (0x0001, "MainState"),
382 (0x0002, "CurrentErrorList"),
383 (0x0003, "OverallCurrentState"),
384 (0x0004, "OverallTargetState"),
385 (0x0005, "LatchControlModes"),
386 ]
387}
388
389pub fn get_command_list() -> Vec<(u32, &'static str)> {
392 vec![
393 (0x00, "Stop"),
394 (0x01, "MoveTo"),
395 (0x02, "Calibrate"),
396 ]
397}
398
399pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
400 match cmd_id {
401 0x00 => Some("Stop"),
402 0x01 => Some("MoveTo"),
403 0x02 => Some("Calibrate"),
404 _ => None,
405 }
406}
407
408pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
409 match cmd_id {
410 0x00 => Some(vec![]),
411 0x01 => Some(vec![
412 crate::clusters::codec::CommandField { tag: 0, name: "position", kind: crate::clusters::codec::FieldKind::Enum { name: "TargetPosition", variants: &[(0, "Movetofullyclosed"), (1, "Movetofullyopen"), (2, "Movetopedestrianposition"), (3, "Movetoventilationposition"), (4, "Movetosignatureposition")] }, optional: true, nullable: false },
413 crate::clusters::codec::CommandField { tag: 1, name: "latch", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
414 crate::clusters::codec::CommandField { tag: 2, name: "speed", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
415 ]),
416 0x02 => Some(vec![]),
417 _ => None,
418 }
419}
420
421pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
422 match cmd_id {
423 0x00 => Ok(vec![]),
424 0x01 => {
425 let position = {
426 let n = crate::clusters::codec::json_util::get_u64(args, "position")?;
427 TargetPosition::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid TargetPosition: {}", n))?
428 };
429 let latch = crate::clusters::codec::json_util::get_bool(args, "latch")?;
430 let speed = crate::clusters::codec::json_util::get_u8(args, "speed")?;
431 encode_move_to(position, latch, speed)
432 }
433 0x02 => Ok(vec![]),
434 _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
435 }
436}
437
438pub async fn stop(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
442 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_STOP, &[]).await?;
443 Ok(())
444}
445
446pub async fn move_to(conn: &crate::controller::Connection, endpoint: u16, position: TargetPosition, latch: bool, speed: u8) -> anyhow::Result<()> {
448 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_MOVETO, &encode_move_to(position, latch, speed)?).await?;
449 Ok(())
450}
451
452pub async fn calibrate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
454 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_CALIBRATE, &[]).await?;
455 Ok(())
456}
457
458pub async fn read_countdown_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
460 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_COUNTDOWNTIME).await?;
461 decode_countdown_time(&tlv)
462}
463
464pub async fn read_main_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<MainState> {
466 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_MAINSTATE).await?;
467 decode_main_state(&tlv)
468}
469
470pub async fn read_current_error_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ClosureError>> {
472 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_CURRENTERRORLIST).await?;
473 decode_current_error_list(&tlv)
474}
475
476pub async fn read_overall_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallCurrentState>> {
478 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLCURRENTSTATE).await?;
479 decode_overall_current_state(&tlv)
480}
481
482pub async fn read_overall_target_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallTargetState>> {
484 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLTARGETSTATE).await?;
485 decode_overall_target_state(&tlv)
486}
487
488pub async fn read_latch_control_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<LatchControlModes> {
490 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_LATCHCONTROLMODES).await?;
491 decode_latch_control_modes(&tlv)
492}
493
494#[derive(Debug, serde::Serialize)]
495pub struct OperationalErrorEvent {
496 pub error_state: Option<Vec<ClosureError>>,
497}
498
499#[derive(Debug, serde::Serialize)]
500pub struct EngageStateChangedEvent {
501 pub engage_value: Option<bool>,
502}
503
504#[derive(Debug, serde::Serialize)]
505pub struct SecureStateChangedEvent {
506 pub secure_value: Option<bool>,
507}
508
509pub fn decode_operational_error_event(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalErrorEvent> {
513 if let tlv::TlvItemValue::List(_fields) = inp {
514 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
515 Ok(OperationalErrorEvent {
516 error_state: {
517 if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
518 let items: Vec<ClosureError> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::Int(v) = &e.value { ClosureError::from_u8(*v as u8) } else { None } }).collect();
519 Some(items)
520 } else {
521 None
522 }
523 },
524 })
525 } else {
526 Err(anyhow::anyhow!("Expected struct fields"))
527 }
528}
529
530pub fn decode_engage_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EngageStateChangedEvent> {
532 if let tlv::TlvItemValue::List(_fields) = inp {
533 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
534 Ok(EngageStateChangedEvent {
535 engage_value: item.get_bool(&[0]),
536 })
537 } else {
538 Err(anyhow::anyhow!("Expected struct fields"))
539 }
540}
541
542pub fn decode_secure_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<SecureStateChangedEvent> {
544 if let tlv::TlvItemValue::List(_fields) = inp {
545 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
546 Ok(SecureStateChangedEvent {
547 secure_value: item.get_bool(&[0]),
548 })
549 } else {
550 Err(anyhow::anyhow!("Expected struct fields"))
551 }
552}
553