use crate::dm::conformance::{Conform, Conformance, Supports};
use crate::dm::meta::{
AttributeDescriptor, ClusterDescriptor, CommandDescriptor, EventDescriptor, EventPriority,
Reporting,
};
use crate::dm::{Access, AttributeQualities};
use crate::im::{AttributeId, ClusterId, CommandId, EventId};
#[derive(Debug, Clone, Copy)]
pub struct Feature {
pub bit: u8,
pub code: &'static str,
pub name: &'static str,
pub conform: Conform,
}
#[derive(Debug, Clone, Copy)]
pub struct Attribute {
pub id: AttributeId,
pub name: &'static str,
pub kind: &'static str,
pub access: Access,
pub qualities: AttributeQualities,
pub reporting: Reporting,
pub conform: Conform,
}
#[derive(Debug, Clone, Copy)]
pub struct Command {
pub id: CommandId,
pub name: &'static str,
pub to_server: bool,
pub response: Option<CommandId>,
pub access: Access,
pub conform: Conform,
}
#[derive(Debug, Clone, Copy)]
pub struct Event {
pub id: EventId,
pub name: &'static str,
pub priority: EventPriority,
pub access: Access,
pub conform: Conform,
}
#[derive(Debug, Clone, Copy)]
pub struct Cluster {
pub id: ClusterId,
pub name: &'static str,
pub revision: u16,
pub pics: &'static str,
pub derived_from: Option<&'static str>,
pub features: &'static [Feature],
pub attributes: &'static [Attribute],
pub commands: &'static [Command],
pub events: &'static [Event],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Defect {
Missing(Element),
Disallowed(Element),
UnknownFeature(u8),
WrongRevision {
found: u16,
expected: u16,
},
ResponseAccepted(CommandId),
Provisional(Element),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Element {
Attribute(AttributeId),
Command(CommandId),
Event(EventId),
}
struct Instance<'a> {
descriptor: &'a ClusterDescriptor<'a>,
}
impl Supports for Instance<'_> {
fn feature_map(&self) -> u32 {
self.descriptor.feature_map
}
fn has_attribute(&self, id: AttributeId) -> bool {
self.descriptor.attributes.iter().any(|a| a.id == id)
}
fn has_command(&self, id: CommandId) -> bool {
self.descriptor.accepted_commands.iter().any(|c| c.id == id) || self.generates(id)
}
fn has_event(&self, id: EventId) -> bool {
self.descriptor.events.iter().any(|e| e.id == id)
}
fn has_cluster(&self, _id: ClusterId) -> bool {
false
}
}
impl Instance<'_> {
fn generates(&self, id: CommandId) -> bool {
self.descriptor.generated_command_ids().any(|c| c == id)
}
}
impl Cluster {
#[must_use]
pub fn feature_mask(&self) -> u32 {
let mut mask = 0u32;
for feature in self.features {
if feature.bit < 32 {
mask |= 1u32 << feature.bit;
}
}
mask
}
#[must_use]
pub fn feature(&self, code: &str) -> Option<&Feature> {
self.features.iter().find(|f| f.code == code)
}
pub fn validate(&self, descriptor: &ClusterDescriptor<'_>, mut found: impl FnMut(Defect)) {
#[cfg(not(feature = "provisional"))]
if PROVISIONAL_CLUSTERS.iter().any(|(id, _)| *id == self.id) {
for attribute in descriptor.attributes {
found(Defect::Provisional(Element::Attribute(attribute.id)));
}
}
if descriptor.revision != self.revision {
found(Defect::WrongRevision {
found: descriptor.revision,
expected: self.revision,
});
}
let undefined = descriptor.feature_map & !self.feature_mask();
for bit in 0..32u8 {
if undefined & (1u32 << bit) != 0 {
found(Defect::UnknownFeature(bit));
}
}
let instance = Instance { descriptor };
for attribute in self.attributes {
let verdict = attribute.conform.verdict(&instance);
let present = instance.has_attribute(attribute.id);
check(
verdict,
present,
Element::Attribute(attribute.id),
&mut found,
);
}
for command in self.commands {
let verdict = command.conform.verdict(&instance);
if command.to_server {
let present = descriptor
.accepted_commands
.iter()
.any(|c| c.id == command.id);
check(verdict, present, Element::Command(command.id), &mut found);
} else {
let shared = self
.commands
.iter()
.any(|other| other.to_server && other.id == command.id);
if !shared
&& descriptor
.accepted_commands
.iter()
.any(|c| c.id == command.id)
{
found(Defect::ResponseAccepted(command.id));
}
let present = instance.generates(command.id);
check(verdict, present, Element::Command(command.id), &mut found);
}
}
for event in self.events {
let verdict = event.conform.verdict(&instance);
let present = instance.has_event(event.id);
check(verdict, present, Element::Event(event.id), &mut found);
}
}
#[must_use]
pub fn is_valid(&self, descriptor: &ClusterDescriptor<'_>) -> bool {
let mut ok = true;
self.validate(descriptor, |_| ok = false);
ok
}
}
pub const PROVISIONAL_CLUSTERS: &[(ClusterId, &str)] = &[
(0x050F, "App §1.1 — Content Control"),
(0x0064, "App §1.1 — Temperature Alarm"),
(0x0431, "App §1.1 — Ambient Context Sensing"),
];
pub const PROVISIONAL_NOT_EXPRESSIBLE: &str =
"App §1.1: Dishwasher Alarm's five alarm bits; DL §1.1: two device types";
fn check(verdict: Conformance, present: bool, element: Element, found: &mut impl FnMut(Defect)) {
match verdict {
Conformance::Mandatory if !present => found(Defect::Missing(element)),
Conformance::Disallowed if present => found(Defect::Disallowed(element)),
#[cfg(not(feature = "provisional"))]
Conformance::Provisional if present => found(Defect::Provisional(element)),
_ => {}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Optional<'a> {
pub attributes: &'a [AttributeId],
pub commands: &'a [CommandId],
pub events: &'a [EventId],
}
impl Optional<'_> {
pub const NONE: Self = Self {
attributes: &[],
commands: &[],
events: &[],
};
}
#[derive(Debug)]
pub struct Conforming<const A: usize, const C: usize, const G: usize, const E: usize> {
id: ClusterId,
revision: u16,
feature_map: u32,
attributes: heapless::Vec<AttributeDescriptor, A>,
accepted: heapless::Vec<CommandDescriptor, C>,
generated: heapless::Vec<CommandId, G>,
events: heapless::Vec<EventDescriptor, E>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Chosen<const N: usize> {
bits: [bool; N],
}
impl<const N: usize> Chosen<N> {
const fn new() -> Self {
Self { bits: [false; N] }
}
fn set(&mut self, index: usize) -> crate::error::Result<()> {
match self.bits.get_mut(index) {
Some(slot) => {
*slot = true;
Ok(())
}
None => Err(crate::Error::new(crate::ErrorCode::NoSpace)),
}
}
fn has(&self, index: usize) -> bool {
self.bits.get(index).copied().unwrap_or(false)
}
}
struct Candidate<'a> {
feature_map: u32,
spec: &'a Cluster,
attributes: &'a Chosen<MAX_ELEMENTS>,
commands: &'a Chosen<MAX_ELEMENTS>,
events: &'a Chosen<MAX_ELEMENTS>,
}
impl Supports for Candidate<'_> {
fn feature_map(&self) -> u32 {
self.feature_map
}
fn has_attribute(&self, id: AttributeId) -> bool {
self.spec
.attributes
.iter()
.enumerate()
.any(|(index, a)| a.id == id && self.attributes.has(index))
}
fn has_command(&self, id: CommandId) -> bool {
self.spec
.commands
.iter()
.enumerate()
.any(|(index, c)| c.id == id && self.commands.has(index))
}
fn has_event(&self, id: EventId) -> bool {
self.spec
.events
.iter()
.enumerate()
.any(|(index, e)| e.id == id && self.events.has(index))
}
fn has_cluster(&self, _id: ClusterId) -> bool {
false
}
}
const ROUNDS: usize = 8;
const MAX_ELEMENTS: usize = 128;
impl<const A: usize, const C: usize, const G: usize, const E: usize> Conforming<A, C, G, E> {
pub fn new(
spec: &'static Cluster,
feature_map: u32,
optional: &Optional<'_>,
) -> crate::error::Result<Self> {
if feature_map & !spec.feature_mask() != 0 {
crate::error::bail!(InvalidArgument)
}
let mut attributes = Chosen::<MAX_ELEMENTS>::new();
let mut commands = Chosen::<MAX_ELEMENTS>::new();
let mut events = Chosen::<MAX_ELEMENTS>::new();
for round in 0..ROUNDS {
let candidate = Candidate {
feature_map,
spec,
attributes: &attributes,
commands: &commands,
events: &events,
};
let mut next_attributes = Chosen::<MAX_ELEMENTS>::new();
let mut next_commands = Chosen::<MAX_ELEMENTS>::new();
let mut next_events = Chosen::<MAX_ELEMENTS>::new();
for (index, attribute) in spec.attributes.iter().enumerate() {
if selected(
attribute.conform.verdict(&candidate),
optional.attributes.contains(&attribute.id),
) {
next_attributes.set(index)?;
}
}
for (index, command) in spec.commands.iter().enumerate() {
if selected(
command.conform.verdict(&candidate),
optional.commands.contains(&command.id),
) {
next_commands.set(index)?;
}
}
for (index, event) in spec.events.iter().enumerate() {
if selected(
event.conform.verdict(&candidate),
optional.events.contains(&event.id),
) {
next_events.set(index)?;
}
}
let settled =
next_attributes == attributes && next_commands == commands && next_events == events;
attributes = next_attributes;
commands = next_commands;
events = next_events;
if settled {
break;
}
if round == ROUNDS - 1 {
crate::error::bail!(InvalidState)
}
}
let mut this = Self {
id: spec.id,
revision: spec.revision,
feature_map,
attributes: heapless::Vec::new(),
accepted: heapless::Vec::new(),
generated: heapless::Vec::new(),
events: heapless::Vec::new(),
};
for (_, attribute) in spec
.attributes
.iter()
.enumerate()
.filter(|(index, _)| attributes.has(*index))
{
this.attributes
.push(AttributeDescriptor {
id: attribute.id,
access: attribute.access,
reporting: attribute.reporting,
qualities: attribute.qualities,
})
.map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
}
for (_, command) in spec
.commands
.iter()
.enumerate()
.filter(|(index, _)| commands.has(*index))
{
if command.to_server {
this.accepted
.push(CommandDescriptor {
id: command.id,
access: command.access,
response: None,
})
.map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
} else {
this.generated
.push(command.id)
.map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
}
}
for (_, event) in spec
.events
.iter()
.enumerate()
.filter(|(index, _)| events.has(*index))
{
this.events
.push(EventDescriptor {
id: event.id,
access: event.access,
priority: event.priority,
})
.map_err(|_| crate::Error::new(crate::ErrorCode::NoSpace))?;
}
Ok(this)
}
#[must_use]
pub fn descriptor(&self) -> ClusterDescriptor<'_> {
ClusterDescriptor {
id: self.id,
revision: self.revision,
feature_map: self.feature_map,
attributes: &self.attributes,
accepted_commands: &self.accepted,
generated_commands: &self.generated,
events: &self.events,
}
}
}
const fn selected(verdict: Conformance, chosen: bool) -> bool {
match verdict {
Conformance::Mandatory => true,
Conformance::Optional
| Conformance::Provisional
| Conformance::Deprecated
| Conformance::Described => chosen,
Conformance::Disallowed => false,
}
}