matter-kit 0.3.0

Matter (CSA smart-home standard) protocol implementation in Rust: no_std, no-alloc, executor-agnostic
Documentation
// Generated by `cargo xtask` from the CSA data model 1.6. Do not edit.
//
// Energy Preference โ€” cluster 0x009B.
//
// Regenerate with `cargo xtask clusters --dm <checkout>/data_model/1.6`; `cargo xtask check`
// is the CI gate that keeps this file honest. The XML itself is not vendored here โ€” it
// carries the CSA's own copyright notice and is not redistributable.

//! Energy Preference (cluster `0x009B`, revision 1).
//!
//! 5 identifiers, 2 feature bits, and the specification's own conformance for
//! every element. `CLUSTER` is the whole table.

#![allow(unused_imports)]

use crate::dm::conformance::{Clause, Condition, Conform, Conformance};
use crate::dm::meta::{EventPriority, Reporting};
use crate::dm::spec::{Attribute, Cluster, Command, Event, Feature};
use crate::dm::{Access, AccessQualities, AttributeQualities, Privilege};
use crate::error::Result;
use crate::im::{AttributeId, ClusterId, CommandId, EventId};
use crate::tlv::{
    ContainerKind, Element, FromTlv, Nullable, Tag, TlvList, TlvReader, TlvWriter, ToTlv, Value,
};

/// The cluster id.
pub const ID: ClusterId = 0x009B;

/// The highest revision the specification's history defines โ€” what `ClusterRevision`
/// must report (Core ยง7.13.1).
pub const REVISION: u16 = 1;

/// The PICS code, which a certification declaration names the cluster by.
pub const PICS: &str = "EPREF";

/// The `FeatureMap` bits (Core ยง7.13.2).
///
/// A feature has conformance of its own: a device may not claim one the
/// specification forbids it alongside another.
pub mod feature {
    /// Device can balance energy consumption vs. another priority
    ///
    /// Code `BALA`, bit 0.
    pub const ENERGY_BALANCE: u32 = 1 << 0;
    /// Device can adjust the conditions for entering a low power mode
    ///
    /// Code `LPMS`, bit 1.
    pub const LOW_POWER_MODE_SENSITIVITY: u32 = 1 << 1;
}

/// Every feature bit, with its conformance.
pub const FEATURES: &[Feature] = &[
    Feature {
        bit: 0,
        code: "BALA",
        name: "EnergyBalance",
        conform: Conform::OPTIONAL,
    },
    Feature {
        bit: 1,
        code: "LPMS",
        name: "LowPowerModeSensitivity",
        conform: Conform::OPTIONAL,
    },
];

/// The attribute ids.
pub mod attribute {
    use crate::im::AttributeId;

    /// `EnergyBalances`.
    pub const ENERGY_BALANCES: AttributeId = 0x00;
    /// `CurrentEnergyBalance`.
    pub const CURRENT_ENERGY_BALANCE: AttributeId = 0x01;
    /// `EnergyPriorities`.
    pub const ENERGY_PRIORITIES: AttributeId = 0x02;
    /// `LowPowerModeSensitivities`.
    pub const LOW_POWER_MODE_SENSITIVITIES: AttributeId = 0x03;
    /// `CurrentLowPowerModeSensitivity`.
    pub const CURRENT_LOW_POWER_MODE_SENSITIVITY: AttributeId = 0x04;
}

/// `EnergyPriorityEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum EnergyPriorityEnum {
    /// User comfort
    Comfort = 0,
    /// Speed of operation
    Speed = 1,
    /// Amount of Energy consumed by the device
    Efficiency = 2,
    /// Amount of water consumed by the device
    WaterConsumption = 3,
}

impl EnergyPriorityEnum {
    /// Reads a wire value, or `None` for one this revision does not define.
    #[must_use]
    pub const fn from_value(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::Comfort),
            1 => Some(Self::Speed),
            2 => Some(Self::Efficiency),
            3 => Some(Self::WaterConsumption),
            _ => None,
        }
    }

    /// Its wire value.
    #[must_use]
    pub const fn value(self) -> u8 {
        self as u8
    }
}

impl ToTlv for EnergyPriorityEnum {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        self.value().to_tlv(w, tag)
    }
}

impl<'a> FromTlv<'a> for EnergyPriorityEnum {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        let value = <u8 as FromTlv<'a>>::from_tlv(reader, element)?;
        Self::from_value(value).ok_or(crate::Error::new(crate::ErrorCode::TlvOutOfRange))
    }
}

/// `BalanceStruct`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BalanceStruct<'a> {
    /// `Step`, field 0.
    pub step: u8,
    /// `Label`, field 1.
    pub label: Option<&'a str>,
}

impl<'a> ToTlv for BalanceStruct<'a> {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.step.to_tlv(w, Tag::Context(0))?;
        if let Some(value) = &self.label {
            value.to_tlv(w, Tag::Context(1))?;
        }
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for BalanceStruct<'a> {
    fn from_tlv(reader: &mut TlvReader<'a>, element: &Element<'a>) -> Result<Self> {
        if element.value.container() != Some(ContainerKind::Structure) {
            return Err(crate::Error::new(crate::ErrorCode::TlvWrongType));
        }
        let mut step = None;
        let mut label = None;
        loop {
            let Some(field) = reader.next_element()? else {
                return Err(crate::Error::new(crate::ErrorCode::TlvTruncated));
            };
            if field.value == Value::EndOfContainer {
                break;
            }
            match field.tag.context() {
                Some(0) => step = Some(<u8>::from_tlv(reader, &field)?),
                Some(1) => label = Some(<&'a str>::from_tlv(reader, &field)?),
                // A field this revision does not define. ยง7.19.2: a receiver
                // ignores what it does not know rather than refusing the whole
                // structure, which is what lets a newer peer talk to an older one.
                _ => reader.skip_value(&field)?,
            }
        }
        Ok(Self {
            step: step.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            label,
        })
    }
}

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[
    Attribute {
        id: 0x0000,
        name: "EnergyBalances",
        kind: "list[BalanceStruct]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0001,
        name: "CurrentEnergyBalance",
        kind: "uint8",
        access: Access::read_write_with(Privilege::View, Privilege::Operate),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0002,
        name: "EnergyPriorities",
        kind: "list[EnergyPriorityEnum]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
    Attribute {
        id: 0x0003,
        name: "LowPowerModeSensitivities",
        kind: "list[BalanceStruct]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::FIXED,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(1),
            }],
        },
    },
    Attribute {
        id: 0x0004,
        name: "CurrentLowPowerModeSensitivity",
        kind: "uint8",
        access: Access::read_write_with(Privilege::View, Privilege::Operate),
        qualities: AttributeQualities::NON_VOLATILE,
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(1),
            }],
        },
    },
];

/// Every command, with its conformance.
pub const COMMANDS: &[Command] = &[];

/// Every event, with its conformance.
pub const EVENTS: &[Event] = &[];

/// The whole cluster, as the specification defines it.
pub const CLUSTER: Cluster = Cluster {
    id: ID,
    name: "Energy Preference",
    revision: REVISION,
    pics: "EPREF",
    derived_from: None,
    features: FEATURES,
    attributes: ATTRIBUTES,
    commands: COMMANDS,
    events: EVENTS,
};