#![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 DelayedAllOffEffectVariant {
Delayedofffastfade = 0,
Nofade = 1,
Delayedoffslowfade = 2,
}
impl DelayedAllOffEffectVariant {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(DelayedAllOffEffectVariant::Delayedofffastfade),
1 => Some(DelayedAllOffEffectVariant::Nofade),
2 => Some(DelayedAllOffEffectVariant::Delayedoffslowfade),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<DelayedAllOffEffectVariant> for u8 {
fn from(val: DelayedAllOffEffectVariant) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum DyingLightEffectVariant {
Dyinglightfadeoff = 0,
}
impl DyingLightEffectVariant {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(DyingLightEffectVariant::Dyinglightfadeoff),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<DyingLightEffectVariant> for u8 {
fn from(val: DyingLightEffectVariant) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum EffectIdentifier {
Delayedalloff = 0,
Dyinglight = 1,
}
impl EffectIdentifier {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(EffectIdentifier::Delayedalloff),
1 => Some(EffectIdentifier::Dyinglight),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<EffectIdentifier> for u8 {
fn from(val: EffectIdentifier) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StartUpOnOff {
Off = 0,
On = 1,
Toggle = 2,
}
impl StartUpOnOff {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(StartUpOnOff::Off),
1 => Some(StartUpOnOff::On),
2 => Some(StartUpOnOff::Toggle),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<StartUpOnOff> for u8 {
fn from(val: StartUpOnOff) -> Self {
val as u8
}
}
pub type OnOffControl = u8;
pub mod onoffcontrol {
pub const ACCEPT_ONLY_WHEN_ON: u8 = 0x01;
}
pub fn encode_off_with_effect(effect_identifier: EffectIdentifier, effect_variant: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(effect_identifier.to_u8())).into(),
(1, tlv::TlvItemValueEnc::UInt8(effect_variant)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_on_with_timed_off(on_off_control: OnOffControl, on_time: u16, off_wait_time: u16) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(on_off_control)).into(),
(1, tlv::TlvItemValueEnc::UInt16(on_time)).into(),
(2, tlv::TlvItemValueEnc::UInt16(off_wait_time)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_on_off(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
if let tlv::TlvItemValue::Bool(v) = inp {
Ok(*v)
} else {
Err(anyhow::anyhow!("Expected Bool"))
}
}
pub fn decode_global_scene_control(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
if let tlv::TlvItemValue::Bool(v) = inp {
Ok(*v)
} else {
Err(anyhow::anyhow!("Expected Bool"))
}
}
pub fn decode_on_time(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u16)
} else {
Err(anyhow::anyhow!("Expected UInt16"))
}
}
pub fn decode_off_wait_time(inp: &tlv::TlvItemValue) -> anyhow::Result<u16> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u16)
} else {
Err(anyhow::anyhow!("Expected UInt16"))
}
}
pub fn decode_start_up_on_off(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<StartUpOnOff>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(StartUpOnOff::from_u8(*v as u8))
} else {
Ok(None)
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0006 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0006, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_on_off(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x4000 => {
match decode_global_scene_control(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x4001 => {
match decode_on_time(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x4002 => {
match decode_off_wait_time(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x4003 => {
match decode_start_up_on_off(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, "OnOff"),
(0x4000, "GlobalSceneControl"),
(0x4001, "OnTime"),
(0x4002, "OffWaitTime"),
(0x4003, "StartUpOnOff"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "Off"),
(0x01, "On"),
(0x02, "Toggle"),
(0x40, "OffWithEffect"),
(0x41, "OnWithRecallGlobalScene"),
(0x42, "OnWithTimedOff"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("Off"),
0x01 => Some("On"),
0x02 => Some("Toggle"),
0x40 => Some("OffWithEffect"),
0x41 => Some("OnWithRecallGlobalScene"),
0x42 => Some("OnWithTimedOff"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x00 => Some(vec![]),
0x01 => Some(vec![]),
0x02 => Some(vec![]),
0x40 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "effect_identifier", kind: crate::clusters::codec::FieldKind::Enum { name: "EffectIdentifier", variants: &[(0, "Delayedalloff"), (1, "Dyinglight")] }, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 1, name: "effect_variant", kind: crate::clusters::codec::FieldKind::U8, optional: false, nullable: false },
]),
0x41 => Some(vec![]),
0x42 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "on_off_control", kind: crate::clusters::codec::FieldKind::Bitmap { name: "OnOffControl", bits: &[(1, "ACCEPT_ONLY_WHEN_ON")] }, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 1, name: "on_time", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 2, name: "off_wait_time", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
]),
_ => None,
}
}
pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
match cmd_id {
0x00 => Ok(vec![]),
0x01 => Ok(vec![]),
0x02 => Ok(vec![]),
0x40 => {
let effect_identifier = {
let n = crate::clusters::codec::json_util::get_u64(args, "effect_identifier")?;
EffectIdentifier::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid EffectIdentifier: {}", n))?
};
let effect_variant = crate::clusters::codec::json_util::get_u8(args, "effect_variant")?;
encode_off_with_effect(effect_identifier, effect_variant)
}
0x41 => Ok(vec![]),
0x42 => {
let on_off_control = crate::clusters::codec::json_util::get_u8(args, "on_off_control")?;
let on_time = crate::clusters::codec::json_util::get_u16(args, "on_time")?;
let off_wait_time = crate::clusters::codec::json_util::get_u16(args, "off_wait_time")?;
encode_on_with_timed_off(on_off_control, on_time, off_wait_time)
}
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
pub async fn off(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_OFF, &[]).await?;
Ok(())
}
pub async fn on(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_ON, &[]).await?;
Ok(())
}
pub async fn toggle(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_TOGGLE, &[]).await?;
Ok(())
}
pub async fn off_with_effect(conn: &crate::controller::Connection, endpoint: u16, effect_identifier: EffectIdentifier, effect_variant: u8) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_OFFWITHEFFECT, &encode_off_with_effect(effect_identifier, effect_variant)?).await?;
Ok(())
}
pub async fn on_with_recall_global_scene(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_ONWITHRECALLGLOBALSCENE, &[]).await?;
Ok(())
}
pub async fn on_with_timed_off(conn: &crate::controller::Connection, endpoint: u16, on_off_control: OnOffControl, on_time: u16, off_wait_time: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_CMD_ID_ONWITHTIMEDOFF, &encode_on_with_timed_off(on_off_control, on_time, off_wait_time)?).await?;
Ok(())
}
pub async fn read_on_off(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_ONOFF).await?;
decode_on_off(&tlv)
}
pub async fn read_global_scene_control(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_GLOBALSCENECONTROL).await?;
decode_global_scene_control(&tlv)
}
pub async fn read_on_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_ONTIME).await?;
decode_on_time(&tlv)
}
pub async fn read_off_wait_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u16> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_OFFWAITTIME).await?;
decode_off_wait_time(&tlv)
}
pub async fn read_start_up_on_off(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<StartUpOnOff>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ON_OFF, crate::clusters::defs::CLUSTER_ON_OFF_ATTR_ID_STARTUPONOFF).await?;
decode_start_up_on_off(&tlv)
}