use crate::tlv;
use anyhow;
use serde_json;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneEventStoppedReason {
Actionstopped = 0,
Timeout = 1,
}
impl ZoneEventStoppedReason {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ZoneEventStoppedReason::Actionstopped),
1 => Some(ZoneEventStoppedReason::Timeout),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ZoneEventStoppedReason> for u8 {
fn from(val: ZoneEventStoppedReason) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneEventTriggeredReason {
Motion = 0,
}
impl ZoneEventTriggeredReason {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ZoneEventTriggeredReason::Motion),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ZoneEventTriggeredReason> for u8 {
fn from(val: ZoneEventTriggeredReason) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneSource {
Mfg = 0,
User = 1,
}
impl ZoneSource {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ZoneSource::Mfg),
1 => Some(ZoneSource::User),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ZoneSource> for u8 {
fn from(val: ZoneSource) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneType {
Twodcartzone = 0,
}
impl ZoneType {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ZoneType::Twodcartzone),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ZoneType> for u8 {
fn from(val: ZoneType) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ZoneUse {
Motion = 0,
Privacy = 1,
Focus = 2,
}
impl ZoneUse {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ZoneUse::Motion),
1 => Some(ZoneUse::Privacy),
2 => Some(ZoneUse::Focus),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ZoneUse> for u8 {
fn from(val: ZoneUse) -> Self {
val as u8
}
}
#[derive(Debug, serde::Serialize)]
pub struct TwoDCartesianVertex {
pub x: Option<u16>,
pub y: Option<u16>,
}
#[derive(Debug, serde::Serialize)]
pub struct TwoDCartesianZone {
pub name: Option<String>,
pub use_: Option<ZoneUse>,
pub vertices: Option<Vec<TwoDCartesianVertex>>,
pub color: Option<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct ZoneInformation {
pub zone_id: Option<u8>,
pub zone_type: Option<ZoneType>,
pub zone_source: Option<ZoneSource>,
pub two_d_cartesian_zone: Option<TwoDCartesianZone>,
}
#[derive(Debug, serde::Serialize)]
pub struct ZoneTriggerControl {
pub zone_id: Option<u8>,
pub initial_duration: Option<u32>,
pub augmentation_duration: Option<u32>,
pub max_duration: Option<u32>,
pub blind_duration: Option<u32>,
pub sensitivity: Option<u8>,
}
pub fn encode_create_two_d_cartesian_zone(zone: TwoDCartesianZone) -> anyhow::Result<Vec<u8>> {
let mut zone_fields = Vec::new();
if let Some(x) = zone.name { zone_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
if let Some(x) = zone.use_ { zone_fields.push((1, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
if let Some(listv) = zone.vertices {
let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
let mut nested_fields = Vec::new();
if let Some(x) = inner.x { nested_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
if let Some(x) = inner.y { nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
(0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
}).collect();
zone_fields.push((2, tlv::TlvItemValueEnc::Array(inner_vec)).into());
}
if let Some(x) = zone.color { zone_fields.push((3, tlv::TlvItemValueEnc::String(x.clone())).into()); }
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::StructInvisible(zone_fields)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_update_two_d_cartesian_zone(zone_id: u8, zone: TwoDCartesianZone) -> anyhow::Result<Vec<u8>> {
let mut zone_fields = Vec::new();
if let Some(x) = zone.name { zone_fields.push((0, tlv::TlvItemValueEnc::String(x.clone())).into()); }
if let Some(x) = zone.use_ { zone_fields.push((1, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
if let Some(listv) = zone.vertices {
let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
let mut nested_fields = Vec::new();
if let Some(x) = inner.x { nested_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
if let Some(x) = inner.y { nested_fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
(0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
}).collect();
zone_fields.push((2, tlv::TlvItemValueEnc::Array(inner_vec)).into());
}
if let Some(x) = zone.color { zone_fields.push((3, tlv::TlvItemValueEnc::String(x.clone())).into()); }
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(zone_id)).into(),
(1, tlv::TlvItemValueEnc::StructInvisible(zone_fields)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_remove_zone(zone_id: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(zone_id)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_create_or_update_trigger(trigger: ZoneTriggerControl) -> anyhow::Result<Vec<u8>> {
let mut trigger_fields = Vec::new();
if let Some(x) = trigger.initial_duration { trigger_fields.push((1, tlv::TlvItemValueEnc::UInt32(x)).into()); }
if let Some(x) = trigger.augmentation_duration { trigger_fields.push((2, tlv::TlvItemValueEnc::UInt32(x)).into()); }
if let Some(x) = trigger.max_duration { trigger_fields.push((3, tlv::TlvItemValueEnc::UInt32(x)).into()); }
if let Some(x) = trigger.blind_duration { trigger_fields.push((4, tlv::TlvItemValueEnc::UInt32(x)).into()); }
if let Some(x) = trigger.sensitivity { trigger_fields.push((5, tlv::TlvItemValueEnc::UInt8(x)).into()); }
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::StructInvisible(trigger_fields)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_remove_trigger(zone_id: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(zone_id)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_max_user_defined_zones(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
pub fn decode_max_zones(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
pub fn decode_zones(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ZoneInformation>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(ZoneInformation {
zone_id: item.get_int(&[0]).map(|v| v as u8),
zone_type: item.get_int(&[1]).and_then(|v| ZoneType::from_u8(v as u8)),
zone_source: item.get_int(&[2]).and_then(|v| ZoneSource::from_u8(v as u8)),
two_d_cartesian_zone: {
if let Some(nested_tlv) = item.get(&[3]) {
if let tlv::TlvItemValue::List(_) = nested_tlv {
let nested_item = tlv::TlvItem { tag: 3, value: nested_tlv.clone() };
Some(TwoDCartesianZone {
name: nested_item.get_string_owned(&[0]),
use_: nested_item.get_int(&[1]).and_then(|v| ZoneUse::from_u8(v as u8)),
vertices: {
if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[2]) {
let mut items = Vec::new();
for list_item in l {
items.push(TwoDCartesianVertex {
x: list_item.get_int(&[0]).map(|v| v as u16),
y: list_item.get_int(&[1]).map(|v| v as u16),
});
}
Some(items)
} else {
None
}
},
color: nested_item.get_string_owned(&[3]),
})
} else {
None
}
} else {
None
}
},
});
}
}
Ok(res)
}
pub fn decode_triggers(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ZoneTriggerControl>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(ZoneTriggerControl {
zone_id: item.get_int(&[0]).map(|v| v as u8),
initial_duration: item.get_int(&[1]).map(|v| v as u32),
augmentation_duration: item.get_int(&[2]).map(|v| v as u32),
max_duration: item.get_int(&[3]).map(|v| v as u32),
blind_duration: item.get_int(&[4]).map(|v| v as u32),
sensitivity: item.get_int(&[5]).map(|v| v as u8),
});
}
}
Ok(res)
}
pub fn decode_sensitivity_max(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
pub fn decode_sensitivity(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
pub fn decode_two_d_cartesian_max(inp: &tlv::TlvItemValue) -> anyhow::Result<TwoDCartesianVertex> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(TwoDCartesianVertex {
x: item.get_int(&[0]).map(|v| v as u16),
y: item.get_int(&[1]).map(|v| v as u16),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0550 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0550, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_max_user_defined_zones(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_max_zones(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_zones(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0003 => {
match decode_triggers(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0004 => {
match decode_sensitivity_max(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0005 => {
match decode_sensitivity(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0006 => {
match decode_two_d_cartesian_max(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, "MaxUserDefinedZones"),
(0x0001, "MaxZones"),
(0x0002, "Zones"),
(0x0003, "Triggers"),
(0x0004, "SensitivityMax"),
(0x0005, "Sensitivity"),
(0x0006, "TwoDCartesianMax"),
]
}
#[derive(Debug, serde::Serialize)]
pub struct CreateTwoDCartesianZoneResponse {
pub zone_id: Option<u8>,
}
pub fn decode_create_two_d_cartesian_zone_response(inp: &tlv::TlvItemValue) -> anyhow::Result<CreateTwoDCartesianZoneResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(CreateTwoDCartesianZoneResponse {
zone_id: item.get_int(&[0]).map(|v| v as u8),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
#[derive(Debug, serde::Serialize)]
pub struct ZoneTriggeredEvent {
pub zone: Option<u8>,
pub reason: Option<ZoneEventTriggeredReason>,
}
#[derive(Debug, serde::Serialize)]
pub struct ZoneStoppedEvent {
pub zone: Option<u8>,
pub reason: Option<ZoneEventStoppedReason>,
}
pub fn decode_zone_triggered_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ZoneTriggeredEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(ZoneTriggeredEvent {
zone: item.get_int(&[0]).map(|v| v as u8),
reason: item.get_int(&[1]).and_then(|v| ZoneEventTriggeredReason::from_u8(v as u8)),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_zone_stopped_event(inp: &tlv::TlvItemValue) -> anyhow::Result<ZoneStoppedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(ZoneStoppedEvent {
zone: item.get_int(&[0]).map(|v| v as u8),
reason: item.get_int(&[1]).and_then(|v| ZoneEventStoppedReason::from_u8(v as u8)),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}