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: Option<TargetPosition>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<Vec<u8>> {
221 let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
222 if let Some(x) = position { tlv_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
223 if let Some(x) = latch { tlv_fields.push((1, tlv::TlvItemValueEnc::Bool(x)).into()); }
224 if let Some(x) = speed { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
225 let tlv = tlv::TlvItemEnc {
226 tag: 0,
227 value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
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 = crate::clusters::codec::json_util::get_opt_u64(args, "position")?
426 .and_then(|n| TargetPosition::from_u8(n as u8));
427 let latch = crate::clusters::codec::json_util::get_opt_bool(args, "latch")?;
428 let speed = crate::clusters::codec::json_util::get_opt_u8(args, "speed")?;
429 encode_move_to(position, latch, speed)
430 }
431 0x02 => Ok(vec![]),
432 _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
433 }
434}
435
436pub async fn stop(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
440 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_STOP, &[]).await?;
441 Ok(())
442}
443
444pub async fn move_to(conn: &crate::controller::Connection, endpoint: u16, position: Option<TargetPosition>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<()> {
446 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?;
447 Ok(())
448}
449
450pub async fn calibrate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
452 conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_CALIBRATE, &[]).await?;
453 Ok(())
454}
455
456pub async fn read_countdown_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
458 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_COUNTDOWNTIME).await?;
459 decode_countdown_time(&tlv)
460}
461
462pub async fn read_main_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<MainState> {
464 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_MAINSTATE).await?;
465 decode_main_state(&tlv)
466}
467
468pub async fn read_current_error_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ClosureError>> {
470 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_CURRENTERRORLIST).await?;
471 decode_current_error_list(&tlv)
472}
473
474pub async fn read_overall_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallCurrentState>> {
476 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLCURRENTSTATE).await?;
477 decode_overall_current_state(&tlv)
478}
479
480pub async fn read_overall_target_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallTargetState>> {
482 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLTARGETSTATE).await?;
483 decode_overall_target_state(&tlv)
484}
485
486pub async fn read_latch_control_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<LatchControlModes> {
488 let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_LATCHCONTROLMODES).await?;
489 decode_latch_control_modes(&tlv)
490}
491
492#[derive(Debug, serde::Serialize)]
493pub struct OperationalErrorEvent {
494 pub error_state: Option<Vec<ClosureError>>,
495}
496
497#[derive(Debug, serde::Serialize)]
498pub struct EngageStateChangedEvent {
499 pub engage_value: Option<bool>,
500}
501
502#[derive(Debug, serde::Serialize)]
503pub struct SecureStateChangedEvent {
504 pub secure_value: Option<bool>,
505}
506
507pub fn decode_operational_error_event(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalErrorEvent> {
511 if let tlv::TlvItemValue::List(_fields) = inp {
512 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
513 Ok(OperationalErrorEvent {
514 error_state: {
515 if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
516 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();
517 Some(items)
518 } else {
519 None
520 }
521 },
522 })
523 } else {
524 Err(anyhow::anyhow!("Expected struct fields"))
525 }
526}
527
528pub fn decode_engage_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EngageStateChangedEvent> {
530 if let tlv::TlvItemValue::List(_fields) = inp {
531 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
532 Ok(EngageStateChangedEvent {
533 engage_value: item.get_bool(&[0]),
534 })
535 } else {
536 Err(anyhow::anyhow!("Expected struct fields"))
537 }
538}
539
540pub fn decode_secure_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<SecureStateChangedEvent> {
542 if let tlv::TlvItemValue::List(_fields) = inp {
543 let item = tlv::TlvItem { tag: 0, value: inp.clone() };
544 Ok(SecureStateChangedEvent {
545 secure_value: item.get_bool(&[0]),
546 })
547 } else {
548 Err(anyhow::anyhow!("Expected struct fields"))
549 }
550}
551
552
553pub fn decode_event_json(cluster_id: u32, event_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
557 if cluster_id != 0x0104 {
558 return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0104, got {}\"}}", cluster_id);
559 }
560
561 match event_id {
562 0x00 => {
563 match decode_operational_error_event(tlv_value) {
564 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
565 Err(e) => format!("{{\"error\": \"{}\"}}", e),
566 }
567 }
568 0x01 => "{}".to_string(),
569 0x02 => {
570 match decode_engage_state_changed_event(tlv_value) {
571 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
572 Err(e) => format!("{{\"error\": \"{}\"}}", e),
573 }
574 }
575 0x03 => {
576 match decode_secure_state_changed_event(tlv_value) {
577 Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
578 Err(e) => format!("{{\"error\": \"{}\"}}", e),
579 }
580 }
581 _ => format!("{{\"error\": \"Unknown event ID: {}\"}}", event_id),
582 }
583}
584
585pub fn get_event_list() -> Vec<(u32, &'static str)> {
590 vec![
591 (0x00, "OperationalError"),
592 (0x01, "MovementCompleted"),
593 (0x02, "EngageStateChanged"),
594 (0x03, "SecureStateChanged"),
595 ]
596}
597