use core::cell::RefCell;
use crate::clusters::generated::on_off as spec_on_off;
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::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
use super::Cluster;
pub use spec_on_off::attribute::{
GLOBAL_SCENE_CONTROL, OFF_WAIT_TIME, ON_OFF, ON_TIME, START_UP_ON_OFF,
};
pub use spec_on_off::command::{
OFF, OFF_WITH_EFFECT, ON, ON_WITH_RECALL_GLOBAL_SCENE, ON_WITH_TIMED_OFF, TOGGLE,
};
pub use spec_on_off::feature;
pub use spec_on_off::{
DelayedAllOffEffectVariantEnum, DyingLightEffectVariantEnum, EffectIdentifierEnum, ID,
OnOffControlBitmap, PICS, REVISION, StartUpOnOffEnum,
};
pub const TICK: Duration = Duration::from_millis(100);
pub const INDEFINITE: u16 = 0xFFFF;
pub trait OnOffHooks {
fn set(&self, on: bool);
fn off_with_effect(&self, effect: EffectIdentifierEnum, variant: u8) {
let _ = (effect, variant);
self.set(false);
}
fn recall_global_scene(&self) -> bool {
true
}
fn store_global_scene(&self) {}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct State {
on: bool,
global_scene_control: bool,
on_time: u16,
off_wait_time: u16,
next_tick: Option<Instant>,
}
#[derive(Debug)]
pub struct OnOff<'a, H: OnOffHooks> {
hooks: &'a H,
feature_map: u32,
state: RefCell<State>,
start_up: Option<StartUpOnOffEnum>,
}
impl<'a, H: OnOffHooks> OnOff<'a, H> {
#[must_use]
pub fn new(hooks: &'a H, feature_map: u32, start_up: Option<StartUpOnOffEnum>) -> Self {
Self {
hooks,
feature_map,
state: RefCell::new(State {
on: false,
global_scene_control: true,
on_time: 0,
off_wait_time: 0,
next_tick: None,
}),
start_up,
}
}
const fn lighting(&self) -> bool {
self.feature_map & feature::LIGHTING != 0
}
const fn off_only(&self) -> bool {
self.feature_map & feature::OFF_ONLY != 0
}
pub fn conforming(
feature_map: u32,
optional: &Optional<'_>,
) -> crate::error::Result<Conforming<5, 6, 0, 0>> {
Conforming::new(&spec_on_off::CLUSTER, feature_map, optional)
}
pub fn start(&self, previous: bool) {
let on = match self.start_up {
None => previous,
Some(StartUpOnOffEnum::Off) => false,
Some(StartUpOnOffEnum::On) => true,
Some(StartUpOnOffEnum::Toggle) => !previous,
};
self.set(on);
}
#[must_use]
pub fn is_on(&self) -> bool {
self.state.borrow().on
}
#[must_use]
pub fn on_time(&self) -> u16 {
self.state.borrow().on_time
}
#[must_use]
pub fn off_wait_time(&self) -> u16 {
self.state.borrow().off_wait_time
}
#[must_use]
pub fn global_scene_control(&self) -> bool {
self.state.borrow().global_scene_control
}
fn set(&self, on: bool) {
let changed = {
let mut state = self.state.borrow_mut();
let changed = state.on != on;
state.on = on;
changed
};
if changed {
self.hooks.set(on);
}
}
#[must_use]
pub fn wake_at(&self) -> Option<Instant> {
self.state.borrow().next_tick
}
pub fn poll(&self, now: Instant) {
let mut turn_off = false;
{
let mut state = self.state.borrow_mut();
let Some(mut due) = state.next_tick else {
return;
};
if state.on_time == INDEFINITE || state.off_wait_time == INDEFINITE {
state.next_tick = None;
return;
}
let mut ticks = 0u32;
while now >= due && ticks < MAX_CATCH_UP {
ticks = ticks.saturating_add(1);
due = due.saturating_add(TICK);
if state.on && state.on_time > 0 {
state.on_time = state.on_time.saturating_sub(1);
if state.on_time == 0 {
state.off_wait_time = 0;
turn_off = true;
state.next_tick = None;
break;
}
} else if !state.on && state.off_wait_time > 0 {
state.off_wait_time = state.off_wait_time.saturating_sub(1);
if state.off_wait_time == 0 {
state.next_tick = None;
break;
}
} else {
state.next_tick = None;
break;
}
}
if state.next_tick.is_some() {
state.next_tick = Some(due);
}
}
if turn_off {
self.set(false);
}
}
fn arm(&self, now: Instant) {
let mut state = self.state.borrow_mut();
let counting = state.on_time != INDEFINITE
&& state.off_wait_time != INDEFINITE
&& (state.on_time > 0 || state.off_wait_time > 0);
state.next_tick = counting.then(|| now.saturating_add(TICK));
}
}
const MAX_CATCH_UP: u32 = 600;
impl<H: OnOffHooks> OnOff<'_, H> {
fn command_off(&self, now: Instant) {
self.set(false);
if self.lighting() {
self.state.borrow_mut().on_time = 0;
self.arm(now);
}
}
fn command_on(&self, now: Instant) {
self.set(true);
if self.lighting() {
let mut state = self.state.borrow_mut();
state.global_scene_control = true;
if state.on_time == 0 {
state.off_wait_time = 0;
}
drop(state);
self.arm(now);
}
}
fn command_toggle(&self, now: Instant) {
if self.is_on() {
self.command_off(now);
} else {
self.command_on(now);
}
}
fn command_on_with_timed_off(&self, control: u8, on_time: u16, off_wait: u16, now: Instant) {
let accept_only_when_on = control & OnOffControlBitmap::ACCEPT_ONLY_WHEN_ON.bits() != 0;
if accept_only_when_on && !self.is_on() {
return;
}
let turn_on = {
let mut state = self.state.borrow_mut();
if state.off_wait_time > 0 && !state.on {
state.off_wait_time = state.off_wait_time.min(off_wait);
false
} else {
state.on_time = state.on_time.max(on_time);
state.off_wait_time = off_wait;
true
}
};
if turn_on {
self.set(true);
}
self.arm(now);
}
fn command_off_with_effect(&self, effect: EffectIdentifierEnum, variant: u8, now: Instant) {
let store = {
let mut state = self.state.borrow_mut();
let store = state.global_scene_control;
if store {
state.global_scene_control = false;
}
store
};
if store {
self.hooks.store_global_scene();
}
self.hooks.off_with_effect(effect, variant);
self.set(false);
if self.lighting() {
self.state.borrow_mut().on_time = 0;
self.arm(now);
}
}
fn command_on_with_recall_global_scene(&self, now: Instant) {
if self.global_scene_control() {
return;
}
let on = self.hooks.recall_global_scene();
self.set(on);
let mut state = self.state.borrow_mut();
state.global_scene_control = true;
if state.on_time == 0 {
state.off_wait_time = 0;
}
drop(state);
self.arm(now);
}
}
fn decode_timed_off(fields: &[u8]) -> Result<(u8, u16, u16), Status> {
let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidAction)?
.ok_or(Status::InvalidAction)?;
if element.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidAction);
}
let (mut control, mut on_time, mut off_wait) = (None, None, None);
loop {
let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
return Err(Status::InvalidAction);
};
if field.value == Value::EndOfContainer {
break;
}
let value = field.unsigned().map_err(|_| Status::ConstraintError)?;
match field.tag.context() {
Some(0) => {
let bits = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
if OnOffControlBitmap::from_bits(bits).is_none() {
return Err(Status::ConstraintError);
}
control = Some(bits);
}
Some(1) | Some(2) => {
let ticks = u16::try_from(value).map_err(|_| Status::ConstraintError)?;
if ticks == INDEFINITE {
return Err(Status::ConstraintError);
}
if field.tag.context() == Some(1) {
on_time = Some(ticks);
} else {
off_wait = Some(ticks);
}
}
_ => {
reader
.skip_value(&field)
.map_err(|_| Status::InvalidAction)?;
}
}
}
match (control, on_time, off_wait) {
(Some(control), Some(on_time), Some(off_wait)) => Ok((control, on_time, off_wait)),
_ => Err(Status::InvalidCommand),
}
}
fn decode_effect(fields: &[u8]) -> Result<(EffectIdentifierEnum, u8), Status> {
let mut reader = TlvReader::new_in(fields, ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidAction)?
.ok_or(Status::InvalidAction)?;
if element.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidAction);
}
let (mut effect, mut variant) = (None, None);
loop {
let Some(field) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
return Err(Status::InvalidAction);
};
if field.value == Value::EndOfContainer {
break;
}
let value = u8::try_from(field.unsigned().map_err(|_| Status::ConstraintError)?)
.map_err(|_| Status::ConstraintError)?;
match field.tag.context() {
Some(0) => {
effect =
Some(EffectIdentifierEnum::from_value(value).ok_or(Status::ConstraintError)?);
}
Some(1) => variant = Some(value),
_ => {
reader
.skip_value(&field)
.map_err(|_| Status::InvalidAction)?;
}
}
}
match (effect, variant) {
(Some(effect), Some(variant)) => Ok((effect, variant)),
_ => Err(Status::InvalidCommand),
}
}
impl<H: OnOffHooks> ClusterHandler for OnOff<'_, 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 {
ON_OFF => full(w.bool(tag, self.is_on())),
GLOBAL_SCENE_CONTROL if self.lighting() => {
full(w.bool(tag, self.global_scene_control()))
}
ON_TIME if self.lighting() => full(w.unsigned(tag, u64::from(self.on_time()))),
OFF_WAIT_TIME if self.lighting() => {
full(w.unsigned(tag, u64::from(self.off_wait_time())))
}
START_UP_ON_OFF if self.lighting() => match self.start_up {
None => full(w.null(tag)),
Some(value) => full(w.unsigned(tag, u64::from(value.value()))),
},
_ => Err(Status::UnsupportedAttribute),
}
}
fn write(
&self,
resolved: &Resolved<'_>,
data: &[u8],
_op: crate::im::WriteOp,
_ctx: &InteractionContext<'_>,
) -> Result<(), Status> {
if !self.lighting() {
return Err(Status::UnsupportedWrite);
}
let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidAction)?
.ok_or(Status::InvalidAction)?;
match resolved.attribute {
ON_TIME | OFF_WAIT_TIME => {
let value = u16::try_from(element.unsigned().map_err(|_| Status::ConstraintError)?)
.map_err(|_| Status::ConstraintError)?;
let mut state = self.state.borrow_mut();
if resolved.attribute == ON_TIME {
state.on_time = value;
} else {
state.off_wait_time = value;
}
Ok(())
}
START_UP_ON_OFF => Err(Status::UnsupportedWrite),
_ => Err(Status::UnsupportedWrite),
}
}
fn invoke(
&self,
resolved: &ResolvedCommand<'_>,
fields: Option<&[u8]>,
ctx: &InteractionContext<'_>,
_w: &mut TlvWriter<'_>,
_tag: Tag,
) -> Result<Option<CommandId>, StatusIb> {
let now = ctx.now;
match resolved.command.id {
OFF => {
self.command_off(now);
Ok(None)
}
ON if !self.off_only() => {
self.command_on(now);
Ok(None)
}
TOGGLE if !self.off_only() => {
self.command_toggle(now);
Ok(None)
}
OFF_WITH_EFFECT if self.lighting() => {
let (effect, variant) =
decode_effect(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
self.command_off_with_effect(effect, variant, now);
Ok(None)
}
ON_WITH_RECALL_GLOBAL_SCENE if self.lighting() => {
self.command_on_with_recall_global_scene(now);
Ok(None)
}
ON_WITH_TIMED_OFF if self.lighting() => {
let (control, on_time, off_wait) =
decode_timed_off(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
self.command_on_with_timed_off(control, on_time, off_wait, now);
Ok(None)
}
_ => Err(Status::UnsupportedCommand.into()),
}
}
}
impl<H: OnOffHooks> Cluster for OnOff<'_, H> {
const ID: ClusterId = ID;
}