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.
//
// Electrical Grid Conditions โ€” cluster 0x00A0.
//
// 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.

//! Electrical Grid Conditions (cluster `0x00A0`, revision 1).
//!
//! 4 identifiers, 1 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 = 0x00A0;

/// 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 = "EGC";

/// 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 {
    /// Forecasts upcoming
    ///
    /// Code `FORE`, bit 0.
    pub const FORECASTING: u32 = 1 << 0;
}

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

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

    /// `LocalGenerationAvailable`.
    pub const LOCAL_GENERATION_AVAILABLE: AttributeId = 0x00;
    /// `CurrentConditions`.
    pub const CURRENT_CONDITIONS: AttributeId = 0x01;
    /// `ForecastConditions`.
    pub const FORECAST_CONDITIONS: AttributeId = 0x02;
}

/// The event ids.
pub mod event {
    use crate::im::EventId;

    /// `CurrentConditionsChanged`.
    pub const CURRENT_CONDITIONS_CHANGED: EventId = 0x00;
}

/// `ThreeLevelEnum`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum ThreeLevelEnum {
    /// Low
    Low = 0,
    /// Medium
    Medium = 1,
    /// High
    High = 2,
}

impl ThreeLevelEnum {
    /// 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::Low),
            1 => Some(Self::Medium),
            2 => Some(Self::High),
            _ => None,
        }
    }

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

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

impl<'a> FromTlv<'a> for ThreeLevelEnum {
    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))
    }
}

/// `ElectricalGridConditionsStruct`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ElectricalGridConditionsStruct {
    /// `PeriodStart`, field 0.
    pub period_start: u32,
    /// `PeriodEnd`, field 1.
    pub period_end: Nullable<u32>,
    /// `GridCarbonIntensity`, field 2.
    pub grid_carbon_intensity: i16,
    /// `GridCarbonLevel`, field 3.
    pub grid_carbon_level: ThreeLevelEnum,
    /// `LocalCarbonIntensity`, field 4.
    pub local_carbon_intensity: i16,
    /// `LocalCarbonLevel`, field 5.
    pub local_carbon_level: ThreeLevelEnum,
}

impl ToTlv for ElectricalGridConditionsStruct {
    fn to_tlv(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
        w.start_structure(tag)?;
        self.period_start.to_tlv(w, Tag::Context(0))?;
        self.period_end.to_tlv(w, Tag::Context(1))?;
        self.grid_carbon_intensity.to_tlv(w, Tag::Context(2))?;
        self.grid_carbon_level.to_tlv(w, Tag::Context(3))?;
        self.local_carbon_intensity.to_tlv(w, Tag::Context(4))?;
        self.local_carbon_level.to_tlv(w, Tag::Context(5))?;
        w.end_container()
    }
}

impl<'a> FromTlv<'a> for ElectricalGridConditionsStruct {
    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 period_start = None;
        let mut period_end = None;
        let mut grid_carbon_intensity = None;
        let mut grid_carbon_level = None;
        let mut local_carbon_intensity = None;
        let mut local_carbon_level = 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) => period_start = Some(<u32>::from_tlv(reader, &field)?),
                Some(1) => period_end = Some(<Nullable<u32>>::from_tlv(reader, &field)?),
                Some(2) => grid_carbon_intensity = Some(<i16>::from_tlv(reader, &field)?),
                Some(3) => grid_carbon_level = Some(<ThreeLevelEnum>::from_tlv(reader, &field)?),
                Some(4) => local_carbon_intensity = Some(<i16>::from_tlv(reader, &field)?),
                Some(5) => local_carbon_level = Some(<ThreeLevelEnum>::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 {
            period_start: period_start.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            period_end: period_end.ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            grid_carbon_intensity: grid_carbon_intensity
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            grid_carbon_level: grid_carbon_level
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            local_carbon_intensity: local_carbon_intensity
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
            local_carbon_level: local_carbon_level
                .ok_or(crate::Error::new(crate::ErrorCode::TlvNotFound))?,
        })
    }
}

/// Every attribute the specification defines, with its conformance.
pub const ATTRIBUTES: &[Attribute] = &[
    Attribute {
        id: 0x0000,
        name: "LocalGenerationAvailable",
        kind: "bool",
        access: Access::read_write_with(Privilege::View, Privilege::Operate),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0001,
        name: "CurrentConditions",
        kind: "ElectricalGridConditionsStruct",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::NULLABLE,
        reporting: Reporting::OnChange,
        conform: Conform::MANDATORY,
    },
    Attribute {
        id: 0x0002,
        name: "ForecastConditions",
        kind: "list[ElectricalGridConditionsStruct]",
        access: Access::read_only(Privilege::View),
        qualities: AttributeQualities::empty(),
        reporting: Reporting::OnChange,
        conform: Conform {
            clauses: &[Clause {
                verdict: Conformance::Mandatory,
                when: Condition::Feature(0),
            }],
        },
    },
];

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

/// Every event, with its conformance.
pub const EVENTS: &[Event] = &[Event {
    id: 0x00,
    name: "CurrentConditionsChanged",
    priority: EventPriority::Info,
    access: Access::read_only(Privilege::View),
    conform: Conform::OPTIONAL,
}];

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