#![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 AirQuality {
Unknown = 0,
Good = 1,
Fair = 2,
Moderate = 3,
Poor = 4,
Verypoor = 5,
Extremelypoor = 6,
}
impl AirQuality {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(AirQuality::Unknown),
1 => Some(AirQuality::Good),
2 => Some(AirQuality::Fair),
3 => Some(AirQuality::Moderate),
4 => Some(AirQuality::Poor),
5 => Some(AirQuality::Verypoor),
6 => Some(AirQuality::Extremelypoor),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<AirQuality> for u8 {
fn from(val: AirQuality) -> Self {
val as u8
}
}
pub fn decode_air_quality(inp: &tlv::TlvItemValue) -> anyhow::Result<AirQuality> {
if let tlv::TlvItemValue::Int(v) = inp {
AirQuality::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} 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 != 0x005B {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x005B, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_air_quality(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, "AirQuality"),
]
}
pub async fn read_air_quality(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<AirQuality> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_AIR_QUALITY, crate::clusters::defs::CLUSTER_AIR_QUALITY_ATTR_ID_AIRQUALITY).await?;
decode_air_quality(&tlv)
}