#![allow(clippy::too_many_arguments)]
use crate::tlv;
use anyhow;
use serde_json;
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum EnergyTransferStoppedReason {
Evstopped = 0,
Evsestopped = 1,
Other = 2,
}
impl EnergyTransferStoppedReason {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(EnergyTransferStoppedReason::Evstopped),
1 => Some(EnergyTransferStoppedReason::Evsestopped),
2 => Some(EnergyTransferStoppedReason::Other),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<EnergyTransferStoppedReason> for u8 {
fn from(val: EnergyTransferStoppedReason) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum FaultState {
Noerror = 0,
Meterfailure = 1,
Overvoltage = 2,
Undervoltage = 3,
Overcurrent = 4,
Contactwetfailure = 5,
Contactdryfailure = 6,
Groundfault = 7,
Powerloss = 8,
Powerquality = 9,
Pilotshortcircuit = 10,
Emergencystop = 11,
Evdisconnected = 12,
Wrongpowersupply = 13,
Liveneutralswap = 14,
Overtemperature = 15,
Other = 255,
}
impl FaultState {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(FaultState::Noerror),
1 => Some(FaultState::Meterfailure),
2 => Some(FaultState::Overvoltage),
3 => Some(FaultState::Undervoltage),
4 => Some(FaultState::Overcurrent),
5 => Some(FaultState::Contactwetfailure),
6 => Some(FaultState::Contactdryfailure),
7 => Some(FaultState::Groundfault),
8 => Some(FaultState::Powerloss),
9 => Some(FaultState::Powerquality),
10 => Some(FaultState::Pilotshortcircuit),
11 => Some(FaultState::Emergencystop),
12 => Some(FaultState::Evdisconnected),
13 => Some(FaultState::Wrongpowersupply),
14 => Some(FaultState::Liveneutralswap),
15 => Some(FaultState::Overtemperature),
255 => Some(FaultState::Other),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<FaultState> for u8 {
fn from(val: FaultState) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum State {
Notpluggedin = 0,
Pluggedinnodemand = 1,
Pluggedindemand = 2,
Pluggedincharging = 3,
Pluggedindischarging = 4,
Sessionending = 5,
Fault = 6,
}
impl State {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(State::Notpluggedin),
1 => Some(State::Pluggedinnodemand),
2 => Some(State::Pluggedindemand),
3 => Some(State::Pluggedincharging),
4 => Some(State::Pluggedindischarging),
5 => Some(State::Sessionending),
6 => Some(State::Fault),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<State> for u8 {
fn from(val: State) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum SupplyState {
Disabled = 0,
Chargingenabled = 1,
Dischargingenabled = 2,
Disablederror = 3,
Disableddiagnostics = 4,
Enabled = 5,
}
impl SupplyState {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(SupplyState::Disabled),
1 => Some(SupplyState::Chargingenabled),
2 => Some(SupplyState::Dischargingenabled),
3 => Some(SupplyState::Disablederror),
4 => Some(SupplyState::Disableddiagnostics),
5 => Some(SupplyState::Enabled),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<SupplyState> for u8 {
fn from(val: SupplyState) -> Self {
val as u8
}
}
pub type TargetDayOfWeek = u8;
pub mod targetdayofweek {
pub const SUNDAY: u8 = 0x01;
pub const MONDAY: u8 = 0x02;
pub const TUESDAY: u8 = 0x04;
pub const WEDNESDAY: u8 = 0x08;
pub const THURSDAY: u8 = 0x10;
pub const FRIDAY: u8 = 0x20;
pub const SATURDAY: u8 = 0x40;
}
#[derive(Debug, serde::Serialize)]
pub struct ChargingTargetSchedule {
pub day_of_week_for_sequence: Option<TargetDayOfWeek>,
pub charging_targets: Option<Vec<ChargingTarget>>,
}
#[derive(Debug, serde::Serialize)]
pub struct ChargingTarget {
pub target_time_minutes_past_midnight: Option<u16>,
pub target_so_c: Option<u8>,
pub added_energy: Option<u64>,
}
pub fn encode_enable_charging(charging_enabled_until: Option<u64>, minimum_charge_current: u8, maximum_charge_current: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt64(charging_enabled_until.unwrap_or(0))).into(),
(1, tlv::TlvItemValueEnc::UInt8(minimum_charge_current)).into(),
(2, tlv::TlvItemValueEnc::UInt8(maximum_charge_current)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_enable_discharging(discharging_enabled_until: Option<u64>, maximum_discharge_current: u8) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt64(discharging_enabled_until.unwrap_or(0))).into(),
(1, tlv::TlvItemValueEnc::UInt8(maximum_discharge_current)).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_set_targets(charging_target_schedules: Vec<ChargingTargetSchedule>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::Array(charging_target_schedules.into_iter().map(|v| {
let mut fields = Vec::new();
if let Some(x) = v.day_of_week_for_sequence { fields.push((0, tlv::TlvItemValueEnc::UInt8(x)).into()); }
if let Some(listv) = v.charging_targets {
let inner_vec: Vec<_> = listv.into_iter().map(|inner| {
let mut nested_fields = Vec::new();
if let Some(x) = inner.target_time_minutes_past_midnight { nested_fields.push((0, tlv::TlvItemValueEnc::UInt16(x)).into()); }
if let Some(x) = inner.target_so_c { nested_fields.push((1, tlv::TlvItemValueEnc::UInt8(x)).into()); }
if let Some(x) = inner.added_energy { nested_fields.push((2, tlv::TlvItemValueEnc::UInt64(x)).into()); }
(0, tlv::TlvItemValueEnc::StructAnon(nested_fields)).into()
}).collect();
fields.push((1, tlv::TlvItemValueEnc::Array(inner_vec)).into());
}
(0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
}).collect())).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn decode_state(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<State>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(State::from_u8(*v as u8))
} else {
Ok(None)
}
}
pub fn decode_supply_state(inp: &tlv::TlvItemValue) -> anyhow::Result<SupplyState> {
if let tlv::TlvItemValue::Int(v) = inp {
SupplyState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_fault_state(inp: &tlv::TlvItemValue) -> anyhow::Result<FaultState> {
if let tlv::TlvItemValue::Int(v) = inp {
FaultState::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
pub fn decode_charging_enabled_until(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_discharging_enabled_until(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_circuit_capacity(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_minimum_charge_current(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_maximum_charge_current(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_maximum_discharge_current(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_user_maximum_charge_current(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_randomization_delay_window(inp: &tlv::TlvItemValue) -> anyhow::Result<u32> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u32)
} else {
Err(anyhow::anyhow!("Expected UInt32"))
}
}
pub fn decode_next_charge_start_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_next_charge_target_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_next_charge_required_energy(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_next_charge_target_so_c(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_approximate_ev_efficiency(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u16>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v as u16))
} else {
Ok(None)
}
}
pub fn decode_state_of_charge(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_battery_capacity(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_vehicle_id(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<String>> {
if let tlv::TlvItemValue::String(v) = inp {
Ok(Some(v.clone()))
} else {
Ok(None)
}
}
pub fn decode_session_id(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v as u32))
} else {
Ok(None)
}
}
pub fn decode_session_duration(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u32>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v as u32))
} else {
Ok(None)
}
}
pub fn decode_session_energy_charged(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_session_energy_discharged(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
if cluster_id != 0x0099 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0099, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_state(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_supply_state(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_fault_state(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0003 => {
match decode_charging_enabled_until(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0004 => {
match decode_discharging_enabled_until(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0005 => {
match decode_circuit_capacity(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0006 => {
match decode_minimum_charge_current(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0007 => {
match decode_maximum_charge_current(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0008 => {
match decode_maximum_discharge_current(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0009 => {
match decode_user_maximum_charge_current(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x000A => {
match decode_randomization_delay_window(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0023 => {
match decode_next_charge_start_time(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0024 => {
match decode_next_charge_target_time(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0025 => {
match decode_next_charge_required_energy(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0026 => {
match decode_next_charge_target_so_c(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0027 => {
match decode_approximate_ev_efficiency(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0030 => {
match decode_state_of_charge(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0031 => {
match decode_battery_capacity(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0032 => {
match decode_vehicle_id(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0040 => {
match decode_session_id(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0041 => {
match decode_session_duration(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0042 => {
match decode_session_energy_charged(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0043 => {
match decode_session_energy_discharged(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, "State"),
(0x0001, "SupplyState"),
(0x0002, "FaultState"),
(0x0003, "ChargingEnabledUntil"),
(0x0004, "DischargingEnabledUntil"),
(0x0005, "CircuitCapacity"),
(0x0006, "MinimumChargeCurrent"),
(0x0007, "MaximumChargeCurrent"),
(0x0008, "MaximumDischargeCurrent"),
(0x0009, "UserMaximumChargeCurrent"),
(0x000A, "RandomizationDelayWindow"),
(0x0023, "NextChargeStartTime"),
(0x0024, "NextChargeTargetTime"),
(0x0025, "NextChargeRequiredEnergy"),
(0x0026, "NextChargeTargetSoC"),
(0x0027, "ApproximateEVEfficiency"),
(0x0030, "StateOfCharge"),
(0x0031, "BatteryCapacity"),
(0x0032, "VehicleID"),
(0x0040, "SessionID"),
(0x0041, "SessionDuration"),
(0x0042, "SessionEnergyCharged"),
(0x0043, "SessionEnergyDischarged"),
]
}
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x01, "Disable"),
(0x02, "EnableCharging"),
(0x03, "EnableDischarging"),
(0x04, "StartDiagnostics"),
(0x05, "SetTargets"),
(0x06, "GetTargets"),
(0x07, "ClearTargets"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x01 => Some("Disable"),
0x02 => Some("EnableCharging"),
0x03 => Some("EnableDischarging"),
0x04 => Some("StartDiagnostics"),
0x05 => Some("SetTargets"),
0x06 => Some("GetTargets"),
0x07 => Some("ClearTargets"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x01 => Some(vec![]),
0x02 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "charging_enabled_until", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: true },
crate::clusters::codec::CommandField { tag: 1, name: "minimum_charge_current", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 2, name: "maximum_charge_current", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
]),
0x03 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "discharging_enabled_until", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: true },
crate::clusters::codec::CommandField { tag: 1, name: "maximum_discharge_current", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
]),
0x04 => Some(vec![]),
0x05 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "charging_target_schedules", kind: crate::clusters::codec::FieldKind::List { entry_type: "ChargingTargetScheduleStruct" }, optional: false, nullable: false },
]),
0x06 => Some(vec![]),
0x07 => Some(vec![]),
_ => None,
}
}
pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
match cmd_id {
0x01 => Ok(vec![]),
0x02 => {
let charging_enabled_until = crate::clusters::codec::json_util::get_opt_u64(args, "charging_enabled_until")?;
let minimum_charge_current = crate::clusters::codec::json_util::get_u8(args, "minimum_charge_current")?;
let maximum_charge_current = crate::clusters::codec::json_util::get_u8(args, "maximum_charge_current")?;
encode_enable_charging(charging_enabled_until, minimum_charge_current, maximum_charge_current)
}
0x03 => {
let discharging_enabled_until = crate::clusters::codec::json_util::get_opt_u64(args, "discharging_enabled_until")?;
let maximum_discharge_current = crate::clusters::codec::json_util::get_u8(args, "maximum_discharge_current")?;
encode_enable_discharging(discharging_enabled_until, maximum_discharge_current)
}
0x04 => Ok(vec![]),
0x05 => Err(anyhow::anyhow!("command \"SetTargets\" has complex args: use raw mode")),
0x06 => Ok(vec![]),
0x07 => Ok(vec![]),
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
#[derive(Debug, serde::Serialize)]
pub struct GetTargetsResponse {
pub charging_target_schedules: Option<Vec<ChargingTargetSchedule>>,
}
pub fn decode_get_targets_response(inp: &tlv::TlvItemValue) -> anyhow::Result<GetTargetsResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(GetTargetsResponse {
charging_target_schedules: {
if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
let mut items = Vec::new();
for list_item in l {
items.push(ChargingTargetSchedule {
day_of_week_for_sequence: list_item.get_int(&[0]).map(|v| v as u8),
charging_targets: {
if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[1]) {
let mut items = Vec::new();
for list_item in l {
items.push(ChargingTarget {
target_time_minutes_past_midnight: list_item.get_int(&[0]).map(|v| v as u16),
target_so_c: list_item.get_int(&[1]).map(|v| v as u8),
added_energy: list_item.get_int(&[2]),
});
}
Some(items)
} else {
None
}
},
});
}
Some(items)
} else {
None
}
},
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub async fn disable(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_CMD_ID_DISABLE, &[]).await?;
Ok(())
}
pub async fn enable_charging(conn: &crate::controller::Connection, endpoint: u16, charging_enabled_until: Option<u64>, minimum_charge_current: u8, maximum_charge_current: u8) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_CMD_ID_ENABLECHARGING, &encode_enable_charging(charging_enabled_until, minimum_charge_current, maximum_charge_current)?).await?;
Ok(())
}
pub async fn enable_discharging(conn: &crate::controller::Connection, endpoint: u16, discharging_enabled_until: Option<u64>, maximum_discharge_current: u8) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_CMD_ID_ENABLEDISCHARGING, &encode_enable_discharging(discharging_enabled_until, maximum_discharge_current)?).await?;
Ok(())
}
pub async fn start_diagnostics(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_CMD_ID_STARTDIAGNOSTICS, &[]).await?;
Ok(())
}
pub async fn set_targets(conn: &crate::controller::Connection, endpoint: u16, charging_target_schedules: Vec<ChargingTargetSchedule>) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_CMD_ID_SETTARGETS, &encode_set_targets(charging_target_schedules)?).await?;
Ok(())
}
pub async fn get_targets(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<GetTargetsResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_CMD_ID_GETTARGETS, &[]).await?;
decode_get_targets_response(&tlv)
}
pub async fn clear_targets(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_CMD_ID_CLEARTARGETS, &[]).await?;
Ok(())
}
pub async fn read_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<State>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_STATE).await?;
decode_state(&tlv)
}
pub async fn read_supply_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<SupplyState> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_SUPPLYSTATE).await?;
decode_supply_state(&tlv)
}
pub async fn read_fault_state(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<FaultState> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_FAULTSTATE).await?;
decode_fault_state(&tlv)
}
pub async fn read_charging_enabled_until(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_CHARGINGENABLEDUNTIL).await?;
decode_charging_enabled_until(&tlv)
}
pub async fn read_discharging_enabled_until(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_DISCHARGINGENABLEDUNTIL).await?;
decode_discharging_enabled_until(&tlv)
}
pub async fn read_circuit_capacity(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_CIRCUITCAPACITY).await?;
decode_circuit_capacity(&tlv)
}
pub async fn read_minimum_charge_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_MINIMUMCHARGECURRENT).await?;
decode_minimum_charge_current(&tlv)
}
pub async fn read_maximum_charge_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_MAXIMUMCHARGECURRENT).await?;
decode_maximum_charge_current(&tlv)
}
pub async fn read_maximum_discharge_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_MAXIMUMDISCHARGECURRENT).await?;
decode_maximum_discharge_current(&tlv)
}
pub async fn read_user_maximum_charge_current(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_USERMAXIMUMCHARGECURRENT).await?;
decode_user_maximum_charge_current(&tlv)
}
pub async fn read_randomization_delay_window(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u32> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_RANDOMIZATIONDELAYWINDOW).await?;
decode_randomization_delay_window(&tlv)
}
pub async fn read_next_charge_start_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_NEXTCHARGESTARTTIME).await?;
decode_next_charge_start_time(&tlv)
}
pub async fn read_next_charge_target_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_NEXTCHARGETARGETTIME).await?;
decode_next_charge_target_time(&tlv)
}
pub async fn read_next_charge_required_energy(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_NEXTCHARGEREQUIREDENERGY).await?;
decode_next_charge_required_energy(&tlv)
}
pub async fn read_next_charge_target_so_c(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_NEXTCHARGETARGETSOC).await?;
decode_next_charge_target_so_c(&tlv)
}
pub async fn read_approximate_ev_efficiency(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u16>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_APPROXIMATEEVEFFICIENCY).await?;
decode_approximate_ev_efficiency(&tlv)
}
pub async fn read_state_of_charge(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u8>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_STATEOFCHARGE).await?;
decode_state_of_charge(&tlv)
}
pub async fn read_battery_capacity(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_BATTERYCAPACITY).await?;
decode_battery_capacity(&tlv)
}
pub async fn read_vehicle_id(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<String>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_VEHICLEID).await?;
decode_vehicle_id(&tlv)
}
pub async fn read_session_id(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_SESSIONID).await?;
decode_session_id(&tlv)
}
pub async fn read_session_duration(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u32>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_SESSIONDURATION).await?;
decode_session_duration(&tlv)
}
pub async fn read_session_energy_charged(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_SESSIONENERGYCHARGED).await?;
decode_session_energy_charged(&tlv)
}
pub async fn read_session_energy_discharged(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_ENERGY_EVSE, crate::clusters::defs::CLUSTER_ENERGY_EVSE_ATTR_ID_SESSIONENERGYDISCHARGED).await?;
decode_session_energy_discharged(&tlv)
}
#[derive(Debug, serde::Serialize)]
pub struct EVConnectedEvent {
pub session_id: Option<u32>,
}
#[derive(Debug, serde::Serialize)]
pub struct EVNotDetectedEvent {
pub session_id: Option<u32>,
pub state: Option<State>,
pub session_duration: Option<u32>,
pub session_energy_charged: Option<u64>,
pub session_energy_discharged: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct EnergyTransferStartedEvent {
pub session_id: Option<u32>,
pub state: Option<State>,
pub maximum_current: Option<u8>,
pub maximum_discharge_current: Option<u8>,
}
#[derive(Debug, serde::Serialize)]
pub struct EnergyTransferStoppedEvent {
pub session_id: Option<u32>,
pub state: Option<State>,
pub reason: Option<EnergyTransferStoppedReason>,
pub energy_transferred: Option<u64>,
pub energy_discharged: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct FaultEvent {
pub session_id: Option<u32>,
pub state: Option<State>,
pub fault_state_previous_state: Option<FaultState>,
pub fault_state_current_state: Option<FaultState>,
}
#[derive(Debug, serde::Serialize)]
pub struct RFIDEvent {
#[serde(serialize_with = "serialize_opt_bytes_as_hex")]
pub uid: Option<Vec<u8>>,
}
pub fn decode_ev_connected_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EVConnectedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(EVConnectedEvent {
session_id: item.get_int(&[0]).map(|v| v as u32),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_ev_not_detected_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EVNotDetectedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(EVNotDetectedEvent {
session_id: item.get_int(&[0]).map(|v| v as u32),
state: item.get_int(&[1]).and_then(|v| State::from_u8(v as u8)),
session_duration: item.get_int(&[2]).map(|v| v as u32),
session_energy_charged: item.get_int(&[3]),
session_energy_discharged: item.get_int(&[4]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_energy_transfer_started_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EnergyTransferStartedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(EnergyTransferStartedEvent {
session_id: item.get_int(&[0]).map(|v| v as u32),
state: item.get_int(&[1]).and_then(|v| State::from_u8(v as u8)),
maximum_current: item.get_int(&[2]).map(|v| v as u8),
maximum_discharge_current: item.get_int(&[3]).map(|v| v as u8),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_energy_transfer_stopped_event(inp: &tlv::TlvItemValue) -> anyhow::Result<EnergyTransferStoppedEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(EnergyTransferStoppedEvent {
session_id: item.get_int(&[0]).map(|v| v as u32),
state: item.get_int(&[1]).and_then(|v| State::from_u8(v as u8)),
reason: item.get_int(&[2]).and_then(|v| EnergyTransferStoppedReason::from_u8(v as u8)),
energy_transferred: item.get_int(&[4]),
energy_discharged: item.get_int(&[5]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_fault_event(inp: &tlv::TlvItemValue) -> anyhow::Result<FaultEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(FaultEvent {
session_id: item.get_int(&[0]).map(|v| v as u32),
state: item.get_int(&[1]).and_then(|v| State::from_u8(v as u8)),
fault_state_previous_state: item.get_int(&[2]).and_then(|v| FaultState::from_u8(v as u8)),
fault_state_current_state: item.get_int(&[4]).and_then(|v| FaultState::from_u8(v as u8)),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
pub fn decode_rfid_event(inp: &tlv::TlvItemValue) -> anyhow::Result<RFIDEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(RFIDEvent {
uid: item.get_octet_string_owned(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}