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: TargetPosition, latch: bool, speed: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(position.to_u8())).into(),
(1, tlv::TlvItemValueEnc::Bool(latch)).into(),
(2, tlv::TlvItemValueEnc::UInt8(speed)).into(),
]),
};
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"),
]
}
#[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"))
}
}