#![allow(clippy::too_many_arguments)]
use crate::tlv;
use anyhow;
use serde_json;
pub type CommodityPriceDetail = u8;
pub mod commoditypricedetail {
pub const DESCRIPTION: u8 = 0x01;
pub const COMPONENTS: u8 = 0x02;
}
#[derive(Debug, serde::Serialize)]
pub struct CommodityPriceComponent {
pub price: Option<u8>,
pub source: Option<u8>,
pub description: Option<String>,
pub tariff_component_id: Option<u32>,
}
#[derive(Debug, serde::Serialize)]
pub struct CommodityPrice {
pub period_start: Option<u64>,
pub period_end: Option<u64>,
pub price: Option<u8>,
pub price_level: Option<i16>,
pub description: Option<String>,
pub components: Option<Vec<CommodityPriceComponent>>,
}
pub fn encode_get_detailed_price_request(details: CommodityPriceDetail) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(details)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_get_detailed_forecast_request(details: CommodityPriceDetail) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt8(details)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_tariff_unit(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_currency(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u8>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v as u8))
} else {
Ok(None)
}
}
pub fn decode_current_price(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<CommodityPrice>> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(Some(CommodityPrice {
period_start: item.get_int(&[0]),
period_end: item.get_int(&[1]),
price: item.get_int(&[2]).map(|v| v as u8),
price_level: item.get_int(&[3]).map(|v| v as i16),
description: item.get_string_owned(&[4]),
components: {
if let Some(tlv::TlvItemValue::List(l)) = item.get(&[5]) {
let mut items = Vec::new();
for list_item in l {
items.push(CommodityPriceComponent {
price: list_item.get_int(&[0]).map(|v| v as u8),
source: list_item.get_int(&[1]).map(|v| v as u8),
description: list_item.get_string_owned(&[2]),
tariff_component_id: list_item.get_int(&[3]).map(|v| v as u32),
});
}
Some(items)
} else {
None
}
},
}))
} else {
Ok(None)
}
}
pub fn decode_price_forecast(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<CommodityPrice>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(CommodityPrice {
period_start: item.get_int(&[0]),
period_end: item.get_int(&[1]),
price: item.get_int(&[2]).map(|v| v as u8),
price_level: item.get_int(&[3]).map(|v| v as i16),
description: item.get_string_owned(&[4]),
components: {
if let Some(tlv::TlvItemValue::List(l)) = item.get(&[5]) {
let mut items = Vec::new();
for list_item in l {
items.push(CommodityPriceComponent {
price: list_item.get_int(&[0]).map(|v| v as u8),
source: list_item.get_int(&[1]).map(|v| v as u8),
description: list_item.get_string_owned(&[2]),
tariff_component_id: list_item.get_int(&[3]).map(|v| v as u32),
});
}
Some(items)
} else {
None
}
},
});
}
}
Ok(res)
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0095 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0095, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_tariff_unit(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_currency(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_current_price(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0003 => {
match decode_price_forecast(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, "TariffUnit"),
(0x0001, "Currency"),
(0x0002, "CurrentPrice"),
(0x0003, "PriceForecast"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "GetDetailedPriceRequest"),
(0x02, "GetDetailedForecastRequest"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("GetDetailedPriceRequest"),
0x02 => Some("GetDetailedForecastRequest"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x00 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "details", kind: crate::clusters::codec::FieldKind::Bitmap { name: "CommodityPriceDetail", bits: &[(1, "DESCRIPTION"), (2, "COMPONENTS")] }, optional: false, nullable: false },
]),
0x02 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "details", kind: crate::clusters::codec::FieldKind::Bitmap { name: "CommodityPriceDetail", bits: &[(1, "DESCRIPTION"), (2, "COMPONENTS")] }, 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 => {
let details = crate::clusters::codec::json_util::get_u8(args, "details")?;
encode_get_detailed_price_request(details)
}
0x02 => {
let details = crate::clusters::codec::json_util::get_u8(args, "details")?;
encode_get_detailed_forecast_request(details)
}
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
#[derive(Debug, serde::Serialize)]
pub struct GetDetailedPriceResponse {
pub current_price: Option<CommodityPrice>,
}
#[derive(Debug, serde::Serialize)]
pub struct GetDetailedForecastResponse {
pub price_forecast: Option<Vec<CommodityPrice>>,
}
pub fn decode_get_detailed_price_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetDetailedPriceResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(GetDetailedPriceResponse {
current_price: {
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(CommodityPrice {
period_start: nested_item.get_int(&[0]),
period_end: nested_item.get_int(&[1]),
price: nested_item.get_int(&[2]).map(|v| v as u8),
price_level: nested_item.get_int(&[3]).map(|v| v as i16),
description: nested_item.get_string_owned(&[4]),
components: {
if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[5]) {
let mut items = Vec::new();
for list_item in l {
items.push(CommodityPriceComponent {
price: list_item.get_int(&[0]).map(|v| v as u8),
source: list_item.get_int(&[1]).map(|v| v as u8),
description: list_item.get_string_owned(&[2]),
tariff_component_id: list_item.get_int(&[3]).map(|v| v as u32),
});
}
Some(items)
} else {
None
}
},
})
} else {
None
}
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_get_detailed_forecast_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetDetailedForecastResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(GetDetailedForecastResponse {
price_forecast: {
if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
let mut items = Vec::new();
for list_item in l {
items.push(CommodityPrice {
period_start: list_item.get_int(&[0]),
period_end: list_item.get_int(&[1]),
price: list_item.get_int(&[2]).map(|v| v as u8),
price_level: list_item.get_int(&[3]).map(|v| v as i16),
description: list_item.get_string_owned(&[4]),
components: {
if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[5]) {
let mut items = Vec::new();
for list_item in l {
items.push(CommodityPriceComponent {
price: list_item.get_int(&[0]).map(|v| v as u8),
source: list_item.get_int(&[1]).map(|v| v as u8),
description: list_item.get_string_owned(&[2]),
tariff_component_id: list_item.get_int(&[3]).map(|v| v as u32),
});
}
Some(items)
} else {
None
}
},
});
}
Some(items)
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub async fn get_detailed_price_request(conn: &crate::controller::Connection, endpoint: u16, details: CommodityPriceDetail) -> anyhow::Result<GetDetailedPriceResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_PRICE, crate::clusters::defs::CLUSTER_COMMODITY_PRICE_CMD_ID_GETDETAILEDPRICEREQUEST, &encode_get_detailed_price_request(details)?).await?;
decode_get_detailed_price_response(&tlv)
}
pub async fn get_detailed_forecast_request(conn: &crate::controller::Connection, endpoint: u16, details: CommodityPriceDetail) -> anyhow::Result<GetDetailedForecastResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_PRICE, crate::clusters::defs::CLUSTER_COMMODITY_PRICE_CMD_ID_GETDETAILEDFORECASTREQUEST, &encode_get_detailed_forecast_request(details)?).await?;
decode_get_detailed_forecast_response(&tlv)
}
pub async fn read_tariff_unit(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_PRICE, crate::clusters::defs::CLUSTER_COMMODITY_PRICE_ATTR_ID_TARIFFUNIT).await?;
decode_tariff_unit(&tlv)
}
pub async fn read_currency(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_PRICE, crate::clusters::defs::CLUSTER_COMMODITY_PRICE_ATTR_ID_CURRENCY).await?;
decode_currency(&tlv)
}
pub async fn read_current_price(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<CommodityPrice>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_PRICE, crate::clusters::defs::CLUSTER_COMMODITY_PRICE_ATTR_ID_CURRENTPRICE).await?;
decode_current_price(&tlv)
}
pub async fn read_price_forecast(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<CommodityPrice>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_COMMODITY_PRICE, crate::clusters::defs::CLUSTER_COMMODITY_PRICE_ATTR_ID_PRICEFORECAST).await?;
decode_price_forecast(&tlv)
}
#[derive(Debug, serde::Serialize)]
pub struct PriceChangeEvent {
pub current_price: Option<CommodityPrice>,
}
pub fn decode_price_change_event(inp: &tlv::TlvItemValue) -> anyhow::Result<PriceChangeEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(PriceChangeEvent {
current_price: {
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(CommodityPrice {
period_start: nested_item.get_int(&[0]),
period_end: nested_item.get_int(&[1]),
price: nested_item.get_int(&[2]).map(|v| v as u8),
price_level: nested_item.get_int(&[3]).map(|v| v as i16),
description: nested_item.get_string_owned(&[4]),
components: {
if let Some(tlv::TlvItemValue::List(l)) = nested_item.get(&[5]) {
let mut items = Vec::new();
for list_item in l {
items.push(CommodityPriceComponent {
price: list_item.get_int(&[0]).map(|v| v as u8),
source: list_item.get_int(&[1]).map(|v| v as u8),
description: list_item.get_string_owned(&[2]),
tariff_component_id: list_item.get_int(&[3]).map(|v| v as u32),
});
}
Some(items)
} else {
None
}
},
})
} else {
None
}
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}