#![allow(clippy::too_many_arguments)]
use crate::tlv;
use anyhow;
use serde_json;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ClosureError {
Physicallyblocked = 0,
Blockedbysensor = 1,
Temperaturelimited = 2,
Maintenancerequired = 3,
Internalinterference = 4,
}
impl ClosureError {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ClosureError::Physicallyblocked),
1 => Some(ClosureError::Blockedbysensor),
2 => Some(ClosureError::Temperaturelimited),
3 => Some(ClosureError::Maintenancerequired),
4 => Some(ClosureError::Internalinterference),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ClosureError> for u8 {
fn from(val: ClosureError) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum CurrentPosition {
Fullyclosed = 0,
Fullyopened = 1,
Partiallyopened = 2,
Openedforpedestrian = 3,
Openedforventilation = 4,
Openedatsignature = 5,
}
impl CurrentPosition {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(CurrentPosition::Fullyclosed),
1 => Some(CurrentPosition::Fullyopened),
2 => Some(CurrentPosition::Partiallyopened),
3 => Some(CurrentPosition::Openedforpedestrian),
4 => Some(CurrentPosition::Openedforventilation),
5 => Some(CurrentPosition::Openedatsignature),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<CurrentPosition> for u8 {
fn from(val: CurrentPosition) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum MainState {
Stopped = 0,
Moving = 1,
Waitingformotion = 2,
Error = 3,
Calibrating = 4,
Protected = 5,
Disengaged = 6,
Setuprequired = 7,
}
impl MainState {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(MainState::Stopped),
1 => Some(MainState::Moving),
2 => Some(MainState::Waitingformotion),
3 => Some(MainState::Error),
4 => Some(MainState::Calibrating),
5 => Some(MainState::Protected),
6 => Some(MainState::Disengaged),
7 => Some(MainState::Setuprequired),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<MainState> for u8 {
fn from(val: MainState) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TargetPosition {
Movetofullyclosed = 0,
Movetofullyopen = 1,
Movetopedestrianposition = 2,
Movetoventilationposition = 3,
Movetosignatureposition = 4,
}
impl TargetPosition {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(TargetPosition::Movetofullyclosed),
1 => Some(TargetPosition::Movetofullyopen),
2 => Some(TargetPosition::Movetopedestrianposition),
3 => Some(TargetPosition::Movetoventilationposition),
4 => Some(TargetPosition::Movetosignatureposition),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<TargetPosition> for u8 {
fn from(val: TargetPosition) -> Self {
val as u8
}
}
pub type LatchControlModes = u8;
pub mod latchcontrolmodes {
pub const REMOTE_LATCHING: u8 = 0x01;
pub const REMOTE_UNLATCHING: u8 = 0x02;
}
#[derive(Debug, serde::Serialize)]
pub struct OverallCurrentState {
pub position: Option<CurrentPosition>,
pub latch: Option<bool>,
pub speed: Option<u8>,
pub secure_state: Option<bool>,
}
#[derive(Debug, serde::Serialize)]
pub struct OverallTargetState {
pub position: Option<TargetPosition>,
pub latch: Option<bool>,
pub speed: Option<u8>,
}
pub fn encode_move_to(position: Option<TargetPosition>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<Vec<u8>> {
let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
if let Some(x) = position { tlv_fields.push((0, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
if let Some(x) = latch { tlv_fields.push((1, tlv::TlvItemValueEnc::Bool(x)).into()); }
if let Some(x) = speed { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x)).into()); }
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
};
Ok(tlv.encode()?)
}
pub fn decode_countdown_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v as u32))
} else {
Ok(None)
}
}
pub fn decode_main_state(inp: &tlv::TlvItemValue) -> anyhow::Result<MainState> {
if let tlv::TlvItemValue::Int(v) = inp {
MainState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_current_error_list(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ClosureError>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
if let tlv::TlvItemValue::Int(i) = &item.value {
if let Some(enum_val) = ClosureError::from_u8(*i as u8) {
res.push(enum_val);
}
}
}
}
Ok(res)
}
pub fn decode_overall_current_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallCurrentState>> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(Some(OverallCurrentState {
position: item.get_int(&[0]).and_then(|v| CurrentPosition::from_u8(v as u8)),
latch: item.get_bool(&[1]),
speed: item.get_int(&[2]).map(|v| v as u8),
secure_state: item.get_bool(&[3]),
}))
} else {
Ok(None)
}
}
pub fn decode_overall_target_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<OverallTargetState>> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(Some(OverallTargetState {
position: item.get_int(&[0]).and_then(|v| TargetPosition::from_u8(v as u8)),
latch: item.get_bool(&[1]),
speed: item.get_int(&[2]).map(|v| v as u8),
}))
} else {
Ok(None)
}
}
pub fn decode_latch_control_modes(inp: &tlv::TlvItemValue) -> anyhow::Result<LatchControlModes> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0104 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0104, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_countdown_time(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_main_state(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_current_error_list(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0003 => {
match decode_overall_current_state(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0004 => {
match decode_overall_target_state(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0005 => {
match decode_latch_control_modes(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
_ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
}
}
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
vec![
(0x0000, "CountdownTime"),
(0x0001, "MainState"),
(0x0002, "CurrentErrorList"),
(0x0003, "OverallCurrentState"),
(0x0004, "OverallTargetState"),
(0x0005, "LatchControlModes"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "Stop"),
(0x01, "MoveTo"),
(0x02, "Calibrate"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("Stop"),
0x01 => Some("MoveTo"),
0x02 => Some("Calibrate"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x00 => Some(vec![]),
0x01 => Some(vec![
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 },
crate::clusters::codec::CommandField { tag: 1, name: "latch", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
crate::clusters::codec::CommandField { tag: 2, name: "speed", kind: crate::clusters::codec::FieldKind::U8, optional: true, nullable: false },
]),
0x02 => Some(vec![]),
_ => None,
}
}
pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
match cmd_id {
0x00 => Ok(vec![]),
0x01 => {
let position = crate::clusters::codec::json_util::get_opt_u64(args, "position")?
.and_then(|n| TargetPosition::from_u8(n as u8));
let latch = crate::clusters::codec::json_util::get_opt_bool(args, "latch")?;
let speed = crate::clusters::codec::json_util::get_opt_u8(args, "speed")?;
encode_move_to(position, latch, speed)
}
0x02 => Ok(vec![]),
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
pub async fn stop(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_STOP, &[]).await?;
Ok(())
}
pub async fn move_to(conn: &crate::controller::Connection, endpoint: u16, position: Option<TargetPosition>, latch: Option<bool>, speed: Option<u8>) -> anyhow::Result<()> {
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?;
Ok(())
}
pub async fn calibrate(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_CMD_ID_CALIBRATE, &[]).await?;
Ok(())
}
pub async fn read_countdown_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_COUNTDOWNTIME).await?;
decode_countdown_time(&tlv)
}
pub async fn read_main_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<MainState> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_MAINSTATE).await?;
decode_main_state(&tlv)
}
pub async fn read_current_error_list(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ClosureError>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_CURRENTERRORLIST).await?;
decode_current_error_list(&tlv)
}
pub async fn read_overall_current_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallCurrentState>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLCURRENTSTATE).await?;
decode_overall_current_state(&tlv)
}
pub async fn read_overall_target_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<OverallTargetState>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_OVERALLTARGETSTATE).await?;
decode_overall_target_state(&tlv)
}
pub async fn read_latch_control_modes(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<LatchControlModes> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_CLOSURE_CONTROL, crate::clusters::defs::CLUSTER_CLOSURE_CONTROL_ATTR_ID_LATCHCONTROLMODES).await?;
decode_latch_control_modes(&tlv)
}
#[derive(Debug, serde::Serialize)]
pub struct OperationalErrorEvent {
pub error_state: Option<Vec<ClosureError>>,
}
#[derive(Debug, serde::Serialize)]
pub struct EngageStateChangedEvent {
pub engage_value: Option<bool>,
}
#[derive(Debug, serde::Serialize)]
pub struct SecureStateChangedEvent {
pub secure_value: Option<bool>,
}
pub fn decode_operational_error_event(inp: &tlv::TlvItemValue) -> anyhow::Result<OperationalErrorEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(OperationalErrorEvent {
error_state: {
if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
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();
Some(items)
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_engage_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EngageStateChangedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(EngageStateChangedEvent {
engage_value: item.get_bool(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_secure_state_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<SecureStateChangedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(SecureStateChangedEvent {
secure_value: item.get_bool(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}