use heapless::Vec;
use crate::im::Status;
pub use crate::clusters::generated::thermostat::ThermostatSuggestionNotFollowingReasonBitmap;
pub const PRESET_HANDLE_MAX: usize = 16;
pub const EXPIRATION_MINUTES_MIN: u16 = 30;
pub const EXPIRATION_MINUTES_MAX: u16 = 1440;
pub const EFFECTIVE_TIME_HORIZON_S: u32 = 24 * 60 * 60;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Suggestion {
pub unique_id: u8,
pub preset_handle: Vec<u8, PRESET_HANDLE_MAX>,
pub effective_time: u32,
pub expiration_time: u32,
}
impl Suggestion {
#[must_use]
pub const fn is_effective(&self, now: u32) -> bool {
self.effective_time <= now && now < self.expiration_time
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Evaluation {
pub current: Option<u8>,
pub wake_at: Option<u32>,
pub not_following: ThermostatSuggestionNotFollowingReasonBitmap,
}
#[derive(Debug)]
pub struct Suggestions<const N: usize> {
entries: Vec<Suggestion, N>,
next_id: u8,
}
impl<const N: usize> Default for Suggestions<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> Suggestions<N> {
#[must_use]
pub const fn new() -> Self {
Self {
entries: Vec::new(),
next_id: 0,
}
}
#[must_use]
pub const fn max(&self) -> usize {
N
}
#[must_use]
pub fn entries(&self) -> &[Suggestion] {
&self.entries
}
#[must_use]
pub fn get(&self, unique_id: u8) -> Option<&Suggestion> {
self.entries.iter().find(|e| e.unique_id == unique_id)
}
pub fn add(
&mut self,
preset_handle: &[u8],
effective_time: Option<u32>,
expiration_in_minutes: u16,
now: Option<u32>,
preset_exists: impl Fn(&[u8]) -> bool,
) -> Result<u8, Status> {
let Some(now) = now else {
return Err(Status::InvalidInState);
};
if preset_handle.len() > PRESET_HANDLE_MAX
|| !(EXPIRATION_MINUTES_MIN..=EXPIRATION_MINUTES_MAX).contains(&expiration_in_minutes)
{
return Err(Status::ConstraintError);
}
if !preset_exists(preset_handle) {
return Err(Status::NotFound);
}
if self.entries.len() >= N {
return Err(Status::ResourceExhausted);
}
let effective_time = effective_time.unwrap_or(now);
if effective_time > now.saturating_add(EFFECTIVE_TIME_HORIZON_S) {
return Err(Status::InvalidCommand);
}
let unique_id = self.allocate().ok_or(Status::ResourceExhausted)?;
let mut handle = Vec::new();
handle
.extend_from_slice(preset_handle)
.map_err(|_| Status::ConstraintError)?;
self.entries
.push(Suggestion {
unique_id,
preset_handle: handle,
effective_time,
expiration_time: effective_time
.saturating_add(u32::from(expiration_in_minutes).saturating_mul(60)),
})
.map_err(|_| Status::ResourceExhausted)?;
Ok(unique_id)
}
pub fn remove(&mut self, unique_id: u8) -> Result<(), Status> {
let before = self.entries.len();
self.entries.retain(|e| e.unique_id != unique_id);
if self.entries.len() == before {
return Err(Status::NotFound);
}
Ok(())
}
pub fn evaluate(&mut self, now: Option<u32>) -> Evaluation {
let Some(now) = now else {
return Evaluation {
current: None,
wake_at: None,
not_following: ThermostatSuggestionNotFollowingReasonBitmap::empty(),
};
};
self.entries.retain(|e| e.expiration_time > now);
let wake_at = self
.entries
.iter()
.flat_map(|e| [e.effective_time, e.expiration_time])
.filter(|at| *at > now)
.min();
let current = self.choose(now);
let not_following = if current.is_none() && self.entries.iter().any(|e| e.is_effective(now))
{
ThermostatSuggestionNotFollowingReasonBitmap::CONFLICTING_SUGGESTIONS
} else {
ThermostatSuggestionNotFollowingReasonBitmap::empty()
};
Evaluation {
current,
wake_at,
not_following,
}
}
fn choose(&self, now: u32) -> Option<u8> {
let mut best: Option<(usize, u32, u8)> = None;
for entry in self.entries.iter().filter(|e| e.is_effective(now)) {
let count = self
.entries
.iter()
.filter(|other| {
other.is_effective(now) && other.preset_handle == entry.preset_handle
})
.count();
let candidate = (count, entry.effective_time, entry.unique_id);
if best.is_none_or(|current| candidate > current) {
best = Some(candidate);
}
}
best.map(|(_, _, unique_id)| unique_id)
}
fn allocate(&mut self) -> Option<u8> {
for _ in 0..=usize::from(u8::MAX) {
let candidate = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
if !self.entries.iter().any(|e| e.unique_id == candidate) {
return Some(candidate);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
const HOME: &[u8] = b"home";
const AWAY: &[u8] = b"away";
fn any(_: &[u8]) -> bool {
true
}
#[test]
fn a_suggestion_runs_from_its_effective_time_for_its_duration() {
let mut table = Suggestions::<4>::new();
let id = table
.add(HOME, Some(2_000), 60, Some(1_000), any)
.expect("added");
let entry = table.get(id).expect("stored");
assert_eq!(entry.effective_time, 2_000);
assert_eq!(entry.expiration_time, 2_000 + 3_600);
}
#[test]
fn a_null_effective_time_means_now() {
let mut table = Suggestions::<4>::new();
let id = table.add(HOME, None, 30, Some(500), any).expect("added");
assert_eq!(table.get(id).expect("stored").effective_time, 500);
}
#[test]
fn identifiers_are_distinct_and_reused_only_when_free() {
let mut table = Suggestions::<4>::new();
let first = table.add(HOME, None, 30, Some(0), any).unwrap();
let second = table.add(AWAY, None, 30, Some(0), any).unwrap();
assert_ne!(first, second);
table.remove(first).expect("removed");
let third = table.add(HOME, None, 30, Some(0), any).unwrap();
assert_ne!(third, second);
}
#[test]
fn expired_entries_are_dropped_by_the_evaluation() {
let mut table = Suggestions::<4>::new();
table.add(HOME, Some(0), 30, Some(0), any).unwrap();
assert_eq!(table.entries().len(), 1);
let evaluation = table.evaluate(Some(1_800));
assert!(table.entries().is_empty(), "the window closed at 1800");
assert_eq!(evaluation.current, None);
}
#[test]
fn the_timer_is_the_next_boundary_of_any_entry() {
let mut table = Suggestions::<4>::new();
table.add(HOME, Some(0), 30, Some(0), any).unwrap(); table.add(AWAY, Some(600), 60, Some(0), any).unwrap(); let evaluation = table.evaluate(Some(0));
assert_eq!(evaluation.wake_at, Some(600), "the nearer of the two");
let evaluation = table.evaluate(Some(700));
assert_eq!(evaluation.wake_at, Some(1_800));
}
#[test]
fn the_most_suggested_preset_wins() {
let mut table = Suggestions::<8>::new();
table.add(AWAY, Some(0), 60, Some(0), any).unwrap();
table.add(HOME, Some(10), 60, Some(0), any).unwrap();
let newest_home = table.add(HOME, Some(20), 60, Some(0), any).unwrap();
let evaluation = table.evaluate(Some(30));
assert_eq!(
evaluation.current,
Some(newest_home),
"two votes for home beat one for away, and the newer of the two wins"
);
assert!(evaluation.not_following.is_empty());
}
}