#![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 ThreeLevel {
Low = 0,
Medium = 1,
High = 2,
}
impl ThreeLevel {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(ThreeLevel::Low),
1 => Some(ThreeLevel::Medium),
2 => Some(ThreeLevel::High),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<ThreeLevel> for u8 {
fn from(val: ThreeLevel) -> Self {
val as u8
}
}
#[derive(Debug, serde::Serialize)]
pub struct ElectricalGridConditions {
pub period_start: Option<u64>,
pub period_end: Option<u64>,
pub grid_carbon_intensity: Option<i16>,
pub grid_carbon_level: Option<ThreeLevel>,
pub local_carbon_intensity: Option<i16>,
pub local_carbon_level: Option<ThreeLevel>,
}
pub fn decode_local_generation_available(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<bool>> {
if let tlv::TlvItemValue::Bool(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_current_conditions(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<ElectricalGridConditions>> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(Some(ElectricalGridConditions {
period_start: item.get_int(&[0]),
period_end: item.get_int(&[1]),
grid_carbon_intensity: item.get_int(&[2]).map(|v| v as i16),
grid_carbon_level: item.get_int(&[3]).and_then(|v| ThreeLevel::from_u8(v as u8)),
local_carbon_intensity: item.get_int(&[4]).map(|v| v as i16),
local_carbon_level: item.get_int(&[5]).and_then(|v| ThreeLevel::from_u8(v as u8)),
}))
} else {
Ok(None)
}
}
pub fn decode_forecast_conditions(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<ElectricalGridConditions>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(ElectricalGridConditions {
period_start: item.get_int(&[0]),
period_end: item.get_int(&[1]),
grid_carbon_intensity: item.get_int(&[2]).map(|v| v as i16),
grid_carbon_level: item.get_int(&[3]).and_then(|v| ThreeLevel::from_u8(v as u8)),
local_carbon_intensity: item.get_int(&[4]).map(|v| v as i16),
local_carbon_level: item.get_int(&[5]).and_then(|v| ThreeLevel::from_u8(v as u8)),
});
}
}
Ok(res)
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x00A0 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x00A0, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_local_generation_available(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_current_conditions(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_forecast_conditions(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, "LocalGenerationAvailable"),
(0x0001, "CurrentConditions"),
(0x0002, "ForecastConditions"),
]
}
pub async fn read_local_generation_available(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<bool>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_GRID_CONDITIONS, crate::clusters::defs::CLUSTER_ELECTRICAL_GRID_CONDITIONS_ATTR_ID_LOCALGENERATIONAVAILABLE).await?;
decode_local_generation_available(&tlv)
}
pub async fn read_current_conditions(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<ElectricalGridConditions>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_GRID_CONDITIONS, crate::clusters::defs::CLUSTER_ELECTRICAL_GRID_CONDITIONS_ATTR_ID_CURRENTCONDITIONS).await?;
decode_current_conditions(&tlv)
}
pub async fn read_forecast_conditions(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<ElectricalGridConditions>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ELECTRICAL_GRID_CONDITIONS, crate::clusters::defs::CLUSTER_ELECTRICAL_GRID_CONDITIONS_ATTR_ID_FORECASTCONDITIONS).await?;
decode_forecast_conditions(&tlv)
}
#[derive(Debug, serde::Serialize)]
pub struct CurrentConditionsChangedEvent {
pub current_conditions: Option<ElectricalGridConditions>,
}
pub fn decode_current_conditions_changed_event(inp: &tlv::TlvItemValue) -> anyhow::Result<CurrentConditionsChangedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(CurrentConditionsChangedEvent {
current_conditions: {
if let Some(nested_tlv) = item.get(&[0]) {
if let tlv::TlvItemValue::List(_) = nested_tlv {
let nested_item = tlv::TlvItem { tag: 0, value: nested_tlv.clone() };
Some(ElectricalGridConditions {
period_start: nested_item.get_int(&[0]),
period_end: nested_item.get_int(&[1]),
grid_carbon_intensity: nested_item.get_int(&[2]).map(|v| v as i16),
grid_carbon_level: nested_item.get_int(&[3]).and_then(|v| ThreeLevel::from_u8(v as u8)),
local_carbon_intensity: nested_item.get_int(&[4]).map(|v| v as i16),
local_carbon_level: nested_item.get_int(&[5]).and_then(|v| ThreeLevel::from_u8(v as u8)),
})
} else {
None
}
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}