use core::cell::{Cell, RefCell};
use crate::clusters::generated::bridged_device_basic_information as spec_bridged;
use crate::dm::spec::{Conforming, Optional};
use crate::dm::{Resolved, ResolvedCommand};
use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
use crate::msg::VendorId;
use crate::platform::{Duration, Instant};
use crate::tlv::{Tag, TlvWriter};
use super::Cluster;
pub use spec_bridged::attribute::{
CONFIGURATION_VERSION, HARDWARE_VERSION, HARDWARE_VERSION_STRING, MANUFACTURING_DATE,
NODE_LABEL, PART_NUMBER, PRODUCT_LABEL, PRODUCT_NAME, PRODUCT_URL, REACHABLE, SERIAL_NUMBER,
SOFTWARE_VERSION, SOFTWARE_VERSION_STRING, UNIQUE_ID, VENDOR_ID, VENDOR_NAME,
};
pub use spec_bridged::command::KEEP_ACTIVE;
pub use spec_bridged::event::{ACTIVE_CHANGED, REACHABLE_CHANGED};
pub use spec_bridged::{ID, PICS, REVISION, feature};
#[derive(Debug, Clone, Copy, Default)]
pub struct BridgedDevice<'a> {
pub vendor_name: Option<&'a str>,
pub vendor_id: Option<VendorId>,
pub product_name: Option<&'a str>,
pub product_id: Option<u16>,
pub hardware_version: Option<u16>,
pub hardware_version_string: Option<&'a str>,
pub software_version: Option<u32>,
pub software_version_string: Option<&'a str>,
pub manufacturing_date: Option<&'a str>,
pub part_number: Option<&'a str>,
pub product_url: Option<&'a str>,
pub product_label: Option<&'a str>,
pub serial_number: Option<&'a str>,
pub unique_id: Option<&'a str>,
pub configuration_version: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PendingActive {
pub stay_active_ms: u32,
pub expires: Instant,
}
pub const NODE_LABEL_MAX: usize = 32;
#[derive(Debug)]
pub struct BridgedDeviceBasicInformation<'a> {
device: BridgedDevice<'a>,
reachable: Cell<bool>,
node_label: RefCell<heapless::String<NODE_LABEL_MAX>>,
pending: Cell<Option<PendingActive>>,
events: RefCell<heapless::Vec<Event, 8>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event {
ReachableChanged(bool),
ActiveChanged(u32),
}
impl<'a> BridgedDeviceBasicInformation<'a> {
#[must_use]
pub fn new(device: BridgedDevice<'a>, reachable: bool) -> Self {
Self {
device,
reachable: Cell::new(reachable),
node_label: RefCell::new(heapless::String::new()),
pending: Cell::new(None),
events: RefCell::new(heapless::Vec::new()),
}
}
pub fn conforming(
feature_map: u32,
optional: &Optional<'_>,
) -> crate::error::Result<Conforming<16, 1, 0, 2>> {
Conforming::new(&spec_bridged::CLUSTER, feature_map, optional)
}
#[must_use]
pub fn optional_for(device: &BridgedDevice<'_>, buf: &'a mut [u32; 16]) -> Optional<'a> {
let mut n = 0usize;
let mut add = |id: u32, present: bool| {
if present && n < buf.len() {
if let Some(slot) = buf.get_mut(n) {
*slot = id;
}
n = n.saturating_add(1);
}
};
add(VENDOR_NAME, device.vendor_name.is_some());
add(VENDOR_ID, device.vendor_id.is_some());
add(PRODUCT_NAME, device.product_name.is_some());
add(NODE_LABEL, true);
add(HARDWARE_VERSION, device.hardware_version.is_some());
add(
HARDWARE_VERSION_STRING,
device.hardware_version_string.is_some(),
);
add(SOFTWARE_VERSION, device.software_version.is_some());
add(
SOFTWARE_VERSION_STRING,
device.software_version_string.is_some(),
);
add(MANUFACTURING_DATE, device.manufacturing_date.is_some());
add(PART_NUMBER, device.part_number.is_some());
add(PRODUCT_URL, device.product_url.is_some());
add(PRODUCT_LABEL, device.product_label.is_some());
add(SERIAL_NUMBER, device.serial_number.is_some());
add(UNIQUE_ID, device.unique_id.is_some());
add(
CONFIGURATION_VERSION,
device.configuration_version.is_some(),
);
Optional {
attributes: buf.get(..n).unwrap_or(&[]),
commands: &[],
events: &[],
}
}
pub const WITH_KEEP_ACTIVE: Optional<'static> = Optional {
attributes: &[],
commands: &[KEEP_ACTIVE],
events: &[],
};
#[must_use]
pub const fn device(&self) -> &BridgedDevice<'a> {
&self.device
}
#[must_use]
pub fn reachable(&self) -> bool {
self.reachable.get()
}
pub fn set_reachable(&self, reachable: bool) {
if self.reachable.replace(reachable) != reachable {
self.push(Event::ReachableChanged(reachable));
}
}
#[must_use]
pub fn node_label(&self) -> core::cell::Ref<'_, heapless::String<NODE_LABEL_MAX>> {
self.node_label.borrow()
}
#[must_use]
pub fn pending_active(&self) -> Option<PendingActive> {
self.pending.get()
}
pub fn poll(&self, now: Instant) {
if let Some(pending) = self.pending.get()
&& now >= pending.expires
{
self.pending.set(None);
}
}
pub fn became_active(&self) {
if let Some(pending) = self.pending.take() {
self.push(Event::ActiveChanged(pending.stay_active_ms));
}
}
pub fn take_events(&self) -> heapless::Vec<Event, 8> {
core::mem::take(&mut self.events.borrow_mut())
}
fn push(&self, event: Event) {
let mut events = self.events.borrow_mut();
if events.is_full() {
events.remove(0);
}
let _ = events.push(event);
}
fn keep_active(&self, stay_active_ms: u32, timeout_ms: u32, now: Instant) {
let expires = now.saturating_add(Duration::from_millis(u64::from(timeout_ms)));
let merged = match self.pending.get() {
Some(prior) => PendingActive {
stay_active_ms: prior.stay_active_ms.max(stay_active_ms),
expires: if prior.expires > expires {
prior.expires
} else {
expires
},
},
None => PendingActive {
stay_active_ms,
expires,
},
};
self.pending.set(Some(merged));
}
}
impl ClusterHandler for BridgedDeviceBasicInformation<'_> {
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);
let device = &self.device;
fn text(value: Option<&str>) -> Result<&str, Status> {
value.ok_or(Status::UnsupportedAttribute)
}
match resolved.attribute {
REACHABLE => full(w.bool(tag, self.reachable.get())),
NODE_LABEL => full(w.utf8(tag, self.node_label.borrow().as_str())),
VENDOR_NAME => full(w.utf8(tag, text(device.vendor_name)?)),
VENDOR_ID => full(w.unsigned(
tag,
u64::from(device.vendor_id.ok_or(Status::UnsupportedAttribute)?.0),
)),
PRODUCT_NAME => full(w.utf8(tag, text(device.product_name)?)),
spec_bridged::attribute::PRODUCT_ID => full(w.unsigned(
tag,
u64::from(device.product_id.ok_or(Status::UnsupportedAttribute)?),
)),
HARDWARE_VERSION => full(
w.unsigned(
tag,
u64::from(
device
.hardware_version
.ok_or(Status::UnsupportedAttribute)?,
),
),
),
HARDWARE_VERSION_STRING => full(w.utf8(tag, text(device.hardware_version_string)?)),
SOFTWARE_VERSION => full(
w.unsigned(
tag,
u64::from(
device
.software_version
.ok_or(Status::UnsupportedAttribute)?,
),
),
),
SOFTWARE_VERSION_STRING => full(w.utf8(tag, text(device.software_version_string)?)),
MANUFACTURING_DATE => full(w.utf8(tag, text(device.manufacturing_date)?)),
PART_NUMBER => full(w.utf8(tag, text(device.part_number)?)),
PRODUCT_URL => full(w.utf8(tag, text(device.product_url)?)),
PRODUCT_LABEL => full(w.utf8(tag, text(device.product_label)?)),
SERIAL_NUMBER => full(w.utf8(tag, text(device.serial_number)?)),
UNIQUE_ID => full(w.utf8(tag, text(device.unique_id)?)),
CONFIGURATION_VERSION => full(
w.unsigned(
tag,
u64::from(
device
.configuration_version
.ok_or(Status::UnsupportedAttribute)?,
),
),
),
_ => Err(Status::UnsupportedAttribute),
}
}
fn write(
&self,
resolved: &Resolved<'_>,
data: &[u8],
_op: crate::im::WriteOp,
_ctx: &InteractionContext<'_>,
) -> Result<(), Status> {
if resolved.attribute != NODE_LABEL {
return Err(Status::UnsupportedWrite);
}
let mut reader = crate::tlv::TlvReader::new_in(data, crate::tlv::ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidAction)?
.ok_or(Status::InvalidAction)?;
let crate::tlv::Value::Utf8(text) = element.value else {
return Err(Status::InvalidDataType);
};
let mut label = heapless::String::new();
label.push_str(text).map_err(|_| Status::ConstraintError)?;
*self.node_label.borrow_mut() = label;
Ok(())
}
fn invoke(
&self,
resolved: &ResolvedCommand<'_>,
fields: Option<&[u8]>,
ctx: &InteractionContext<'_>,
_w: &mut TlvWriter<'_>,
_tag: Tag,
) -> Result<Option<CommandId>, StatusIb> {
if resolved.command.id != KEEP_ACTIVE {
return Err(Status::UnsupportedCommand.into());
}
let decoded: spec_bridged::KeepActiveFields =
super::decode_fields(fields.ok_or(StatusIb::from(Status::InvalidCommand))?)?;
self.keep_active(decoded.stay_active_duration, decoded.timeout_ms, ctx.now);
Ok(None)
}
}
impl Cluster for BridgedDeviceBasicInformation<'_> {
const ID: ClusterId = ID;
}