use core::cell::{Cell, RefCell};
use crate::clusters::generated::water_heater_management as spec_water;
use crate::dm::spec::{Conforming, Optional};
use crate::dm::{Resolved, ResolvedCommand};
use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
use crate::platform::{Duration, Instant};
use crate::tlv::{Tag, TlvWriter};
use super::Cluster;
pub use spec_water::attribute::{
BOOST_STATE, ESTIMATED_HEAT_REQUIRED, HEAT_DEMAND, HEATER_TYPES, TANK_PERCENTAGE, TANK_VOLUME,
};
pub use spec_water::command::{BOOST, CANCEL_BOOST};
pub use spec_water::event::{BOOST_ENDED, BOOST_STARTED};
pub use spec_water::{
BoostStateEnum, ID, PICS, REVISION, WaterHeaterBoostInfoStruct, WaterHeaterHeatSourceBitmap,
feature,
};
pub const SECOND: Duration = Duration::from_secs(1);
pub trait WaterHeaterHooks {
fn heat_demand(&self) -> WaterHeaterHeatSourceBitmap;
fn tank_volume(&self) -> u16 {
0
}
fn estimated_heat_required(&self) -> u64 {
0
}
fn tank_percentage(&self) -> u8 {
0
}
fn boost(&self, info: &WaterHeaterBoostInfoStruct) -> Result<(), Status>;
fn cancel_boost(&self) {}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Event {
BoostStarted(WaterHeaterBoostInfoStruct),
BoostEnded,
}
#[derive(Debug)]
pub struct WaterHeaterManagement<'a, H: WaterHeaterHooks> {
hooks: &'a H,
heater_types: WaterHeaterHeatSourceBitmap,
boost: Cell<Option<WaterHeaterBoostInfoStruct>>,
expires: Cell<Option<Instant>>,
events: RefCell<heapless::Vec<Event, 4>>,
}
impl<'a, H: WaterHeaterHooks> WaterHeaterManagement<'a, H> {
#[must_use]
pub fn new(hooks: &'a H, heater_types: WaterHeaterHeatSourceBitmap) -> Self {
Self {
hooks,
heater_types,
boost: Cell::new(None),
expires: Cell::new(None),
events: RefCell::new(heapless::Vec::new()),
}
}
pub fn conforming(
feature_map: u32,
optional: &Optional<'_>,
) -> crate::error::Result<Conforming<6, 2, 0, 2>> {
Conforming::new(&spec_water::CLUSTER, feature_map, optional)
}
#[must_use]
pub const fn heater_types(&self) -> WaterHeaterHeatSourceBitmap {
self.heater_types
}
#[must_use]
pub fn boost_state(&self) -> BoostStateEnum {
if self.boost.get().is_some() {
BoostStateEnum::Active
} else {
BoostStateEnum::Inactive
}
}
#[must_use]
pub fn boost_info(&self) -> Option<WaterHeaterBoostInfoStruct> {
self.boost.get()
}
#[must_use]
pub fn wake_at(&self) -> Option<Instant> {
self.expires.get()
}
pub fn poll(&self, now: Instant) {
if let Some(expires) = self.expires.get()
&& now >= expires
{
self.end();
}
}
pub fn target_reached(&self) {
if self
.boost
.get()
.is_some_and(|info| info.one_shot == Some(true))
{
self.end();
}
}
pub fn take_events(&self) -> heapless::Vec<Event, 4> {
core::mem::take(&mut self.events.borrow_mut())
}
fn push(&self, event: Event) {
let mut events = self.events.borrow_mut();
if events.is_full() {
events.remove(0);
}
let _ = events.push(event);
}
fn end(&self) {
if self.boost.take().is_some() {
self.expires.set(None);
self.hooks.cancel_boost();
self.push(Event::BoostEnded);
}
}
}
impl<H: WaterHeaterHooks> ClusterHandler for WaterHeaterManagement<'_, H> {
fn read(
&self,
resolved: &Resolved<'_>,
_ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
match resolved.attribute {
HEATER_TYPES => full(w.unsigned(tag, u64::from(self.heater_types.bits()))),
HEAT_DEMAND => full(w.unsigned(tag, u64::from(self.hooks.heat_demand().bits()))),
TANK_VOLUME => full(w.unsigned(tag, u64::from(self.hooks.tank_volume()))),
ESTIMATED_HEAT_REQUIRED => full(w.unsigned(tag, self.hooks.estimated_heat_required())),
TANK_PERCENTAGE => full(w.unsigned(tag, u64::from(self.hooks.tank_percentage()))),
BOOST_STATE => full(w.unsigned(tag, u64::from(self.boost_state().value()))),
_ => Err(Status::UnsupportedAttribute),
}
}
fn invoke(
&self,
resolved: &ResolvedCommand<'_>,
fields: Option<&[u8]>,
ctx: &InteractionContext<'_>,
_w: &mut TlvWriter<'_>,
_tag: Tag,
) -> Result<Option<CommandId>, StatusIb> {
match resolved.command.id {
BOOST => {
let decoded: spec_water::BoostFields =
super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
let info = decoded.boost_info;
if info.duration == 0 {
return Err(Status::ConstraintError.into());
}
if let (Some(target), Some(reheat)) = (info.target_percentage, info.target_reheat)
&& reheat > target
{
return Err(Status::ConstraintError.into());
}
if info.target_percentage.is_some_and(|p| p > 100)
|| info.target_reheat.is_some_and(|p| p > 100)
{
return Err(Status::ConstraintError.into());
}
self.hooks.boost(&info).map_err(StatusIb::from)?;
self.boost.set(Some(info));
self.expires
.set(Some(ctx.now.saturating_add(
SECOND.saturating_mul(u64::from(info.duration)),
)));
self.push(Event::BoostStarted(info));
Ok(None)
}
CANCEL_BOOST => {
self.end();
Ok(None)
}
_ => Err(Status::UnsupportedCommand.into()),
}
}
}
impl<H: WaterHeaterHooks> Cluster for WaterHeaterManagement<'_, H> {
const ID: ClusterId = ID;
}