use core::str::FromStr;
use crate::dm::{AttrId, ClusterId};
use crate::error::Error;
use crate::im::SubscribeReq;
use crate::persist::{KvBlobStore, KvBlobStoreAccess, Persist, BASIC_INFO_KEY};
use crate::session::CASE_SESSIONS_PER_FABRIC;
use crate::tlv::{FromTLV, Nullable, TLVElement, ToTLV};
use crate::utils::bitflags::bitflags;
use crate::utils::init::{init, Init};
use crate::utils::storage::String;
pub const BASIC_INFO_CLUSTER_ID: ClusterId = 0x0028;
pub const CONFIGURATION_VERSION_ATTR_ID: AttrId = 0x0018;
pub const DEFAULT_MATTER_SPEC_VERSION: u32 = 0x01060000;
pub const DEFAULT_DATA_MODEL_REVISION: u16 = 21;
pub const DEFAULT_MAX_PATHS_PER_INVOKE: u16 = 1;
pub const DEFAULT_MIN_SUBSCRIPTION_MAX_INTERVAL_SECS: u16 = 40;
pub const DEFAULT_MAX_SUBSCRIPTION_MAX_INTERVAL_SECS: u16 = 120;
bitflags! {
#[repr(transparent)]
#[derive(Default)]
#[cfg_attr(not(feature = "defmt"), derive(Debug, Copy, Clone, Eq, PartialEq, Hash))]
pub struct PairingHintFlags: u32 {
const POWER_CYCLE = 0x0000_0001;
const DEV_MANUFACTURER_URL = 0x0000_0002;
const ADMINISTRATOR = 0x0000_0004;
const SETTINGS_MENU = 0x0000_0008;
const CUSTOM_INSTRUCTION = 0x0000_0010;
const DEVICE_MANUAL = 0x0000_0020;
const PRESS_RESET_BUTTON = 0x0000_0040;
const PRESS_RESET_BUTTON_WITH_POWER = 0x0000_0080;
const PRESS_RESET_BUTTON_FOR_N_SECONDS = 0x0000_0100;
const PRESS_RESET_BUTTON_UNTIL_LIGHT_BLINKS = 0x0000_0200;
const PRESS_RESET_BUTTON_FOR_N_SECONDS_WITH_POWER = 0x0000_0400;
const PRESS_RESET_BUTTON_UNTIL_LIGHT_BLINKS_WITH_POWER = 0x0000_0800;
const PRESS_RESET_BUTTON_N_TIMES = 0x0000_1000;
const PRESS_SETUP_BUTTON = 0x0000_2000;
const PRESS_SETUP_BUTTON_WITH_POWER = 0x0000_4000;
const PRESS_SETUP_BUTTON_FOR_N_SECONDS = 0x0000_8000;
const PRESS_SETUP_BUTTON_UNTIL_LIGHT_BLINKS = 0x0001_0000;
const PRESS_SETUP_BUTTON_FOR_N_SECONDS_WITH_POWER = 0x0002_0000;
const PRESS_SETUP_BUTTON_UNTIL_LIGHT_BLINKS_WITH_POWER = 0x0004_0000;
const PRESS_SETUP_BUTTON_N_TIMES = 0x0008_0000;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DeviceLocationConfig<'a> {
pub location_name: &'a str,
pub floor_number: Option<i16>,
pub area_type: Option<u8>,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct BasicInfoConfig<'a> {
pub vendor_name: &'a str,
pub vid: u16,
pub product_name: &'a str,
pub pid: u16,
pub hw_ver: u16,
pub hw_ver_str: &'a str,
pub sw_ver: u32,
pub sw_ver_str: &'a str,
pub manufacturing_date: &'a str,
pub part_number: &'a str,
pub product_url: &'a str,
pub product_label: &'a str,
pub serial_no: &'a str,
pub unique_id: &'a str,
pub location: Option<&'a str>,
pub device_location: Option<DeviceLocationConfig<'a>>,
pub capability_minima: CapabilityMinima,
pub product_appearance: ProductAppearance,
pub specification_version: u32,
pub data_model_revision: u16,
pub max_paths_per_invoke: u16,
pub device_name: &'a str,
pub device_type: Option<u16>,
pub pairing_hint: PairingHintFlags,
pub pairing_instruction: &'a str,
pub sai: Option<u32>,
pub sii: Option<u32>,
pub min_subscription_max_interval_secs: u16,
pub max_subscription_max_interval_secs: u16,
}
impl BasicInfoConfig<'_> {
pub const fn new() -> Self {
Self {
vid: 0,
pid: 0,
hw_ver: 0,
hw_ver_str: "",
sw_ver: 0,
sw_ver_str: "",
serial_no: "",
product_name: "",
vendor_name: "",
manufacturing_date: "",
part_number: "",
product_url: "",
product_label: "",
unique_id: "",
location: None,
device_location: None,
capability_minima: CapabilityMinima::new(),
product_appearance: ProductAppearance::new(),
specification_version: DEFAULT_MATTER_SPEC_VERSION,
data_model_revision: DEFAULT_DATA_MODEL_REVISION,
max_paths_per_invoke: DEFAULT_MAX_PATHS_PER_INVOKE,
device_name: "",
device_type: None,
pairing_hint: PairingHintFlags::empty(),
pairing_instruction: "",
sai: None,
sii: None,
min_subscription_max_interval_secs: DEFAULT_MIN_SUBSCRIPTION_MAX_INTERVAL_SECS,
max_subscription_max_interval_secs: DEFAULT_MAX_SUBSCRIPTION_MAX_INTERVAL_SECS,
}
}
}
impl Default for BasicInfoConfig<'_> {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct CapabilityMinima {
pub case_sessions_per_fabric: u16,
pub subscriptions_per_fabric: u16,
pub simultaneous_invocations_supported: u16,
pub simultaneous_writes_supported: u16,
pub read_paths_supported: u16,
pub subscribe_paths_supported: u16,
}
const SUBSCRIPTIONS_PER_FABRIC: u16 = 3;
const SIMULTANEOUS_INVOCATIONS_SUPPORTED: u16 = 1;
const SIMULTANEOUS_WRITES_SUPPORTED: u16 = 1;
const READ_PATHS_SUPPORTED: u16 = 9;
pub const SUBSCRIPTION_BUFFER_SIZE: usize = 256;
pub const SUBSCRIBE_PATHS_SUPPORTED: u16 =
((SUBSCRIPTION_BUFFER_SIZE - SubscribeReq::MAX_FIXED_LEN) / SubscribeReq::MAX_PATH_LEN) as u16;
const _: () = ::core::assert!(SUBSCRIBE_PATHS_SUPPORTED >= 3);
impl CapabilityMinima {
pub const fn new() -> Self {
Self {
case_sessions_per_fabric: CASE_SESSIONS_PER_FABRIC as _,
subscriptions_per_fabric: SUBSCRIPTIONS_PER_FABRIC,
simultaneous_invocations_supported: SIMULTANEOUS_INVOCATIONS_SUPPORTED,
simultaneous_writes_supported: SIMULTANEOUS_WRITES_SUPPORTED,
read_paths_supported: READ_PATHS_SUPPORTED,
subscribe_paths_supported: SUBSCRIBE_PATHS_SUPPORTED,
}
}
}
impl Default for CapabilityMinima {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ProductAppearance {
pub finish: ProductFinish,
pub color: Option<ProductColor>,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ProductFinish {
Other,
Matte,
Satin,
Polished,
Rugged,
Fabric,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ProductColor {
Black,
Navy,
Green,
Teal,
Maroon,
Purple,
Olive,
Gray,
Blue,
Lime,
Aqua,
Red,
Fuchsia,
Yellow,
White,
Nickel,
Chrome,
Brass,
Copper,
Silver,
Gold,
}
impl ProductAppearance {
pub const fn new() -> Self {
Self {
finish: ProductFinish::Other,
color: None,
}
}
}
impl Default for ProductAppearance {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, ToTLV, FromTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DeviceLocation {
pub location_name: String<128>,
pub floor_number: Option<i16>,
pub area_type: Option<u8>,
}
impl DeviceLocation {
pub const fn new() -> Self {
Self {
location_name: String::new(),
floor_number: None,
area_type: None,
}
}
}
impl Default for DeviceLocation {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, ToTLV, FromTLV)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct BasicInfoSettings {
pub node_label: String<32>, pub location: Option<String<2>>, pub location_type: Option<RegulatoryLocationType>,
pub local_config_disabled: bool,
pub configuration_version: u32,
pub device_location: Option<Nullable<DeviceLocation>>,
pub recovery_identifier: Option<u64>,
pub unique_id: Option<u64>,
}
impl BasicInfoSettings {
pub const fn new() -> Self {
Self {
node_label: String::new(),
location: None,
location_type: None,
local_config_disabled: false,
configuration_version: 1,
device_location: None,
recovery_identifier: None,
unique_id: None,
}
}
pub fn init() -> impl Init<Self> {
init!(Self {
node_label: String::new(),
location: None,
location_type: None,
local_config_disabled: false,
configuration_version: 1,
device_location: None,
recovery_identifier: None,
unique_id: None,
})
}
pub fn reset(&mut self) {
self.node_label.clear();
self.location = None;
self.location_type = None;
self.local_config_disabled = false;
self.configuration_version = 1;
self.device_location = None;
self.recovery_identifier = None;
self.unique_id = None;
}
pub fn bump_configuration_version(&mut self) -> u32 {
self.configuration_version = self.configuration_version.saturating_add(1);
self.configuration_version
}
pub fn set_location(&mut self, location: &str) {
self.location = Some(unwrap!(String::<2>::from_str(location)));
}
pub fn reset_persist<S: KvBlobStore>(
&mut self,
mut store: S,
buf: &mut [u8],
) -> Result<(), Error> {
self.reset();
store.remove(BASIC_INFO_KEY, buf)?;
info!("Removed basic info settings from storage");
Ok(())
}
pub fn load(&mut self, data: &[u8]) -> Result<(), Error> {
let info = Self::from_tlv(&TLVElement::new(data))?;
self.node_label = info.node_label;
self.location = info.location;
self.location_type = info.location_type;
self.local_config_disabled = info.local_config_disabled;
self.configuration_version = info.configuration_version;
self.device_location = info.device_location;
self.recovery_identifier = info.recovery_identifier;
self.unique_id = info.unique_id;
Ok(())
}
#[inline(never)]
pub fn store_persist<S: KvBlobStoreAccess>(
&self,
persist: &mut Persist<S>,
) -> Result<(), Error> {
persist.store_tlv(BASIC_INFO_KEY, self)
}
pub fn load_persist<S: KvBlobStoreAccess>(&mut self, kv: S) -> Result<(), Error> {
self.reset();
if Persist::new(kv)
.load(BASIC_INFO_KEY, |data| self.load(data))?
.is_some()
{
info!("Loaded basic info settings from storage");
}
Ok(())
}
}
impl Default for BasicInfoSettings {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, FromTLV, ToTLV)]
#[tlvargs(datatype = "u8")]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum RegulatoryLocationType {
#[enumval(0)]
Indoor = 0,
#[enumval(1)]
Outdoor = 1,
#[enumval(2)]
IndoorOutdoor = 2,
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use super::{BasicInfoSettings, DeviceLocation};
use crate::tlv::{Nullable, TLVElement, TLVTag, ToTLV};
use crate::utils::storage::WriteBuf;
fn round_trip(settings: &BasicInfoSettings) -> BasicInfoSettings {
let mut buf = [0; 512];
let mut wb = WriteBuf::new(&mut buf);
settings.to_tlv(&TLVTag::Anonymous, &mut wb).unwrap();
let mut loaded = BasicInfoSettings::new();
loaded.load(wb.as_slice()).unwrap();
loaded
}
#[test]
fn explicit_xx_location_is_kept() {
let mut settings = BasicInfoSettings::new();
assert!(settings.location.is_none());
settings.set_location("XX");
assert_eq!(settings.location.as_deref(), Some("XX"));
assert_eq!(round_trip(&settings).location.as_deref(), Some("XX"));
}
#[test]
fn device_location_states_survive_persistence() {
let mut settings = BasicInfoSettings::new();
assert!(round_trip(&settings).device_location.is_none());
settings.device_location = Some(Nullable::none());
let loaded = round_trip(&settings);
assert!(matches!(&loaded.device_location, Some(l) if l.is_none()));
settings.device_location = Some(Nullable::some(DeviceLocation {
location_name: "Basement".try_into().unwrap(),
floor_number: Some(-1),
area_type: None,
}));
let loaded = round_trip(&settings);
let location = loaded.device_location.unwrap().into_option().unwrap();
assert_eq!(location.location_name, "Basement");
assert_eq!(location.floor_number, Some(-1));
assert_eq!(location.area_type, None);
}
#[test]
fn missing_device_location_field_loads_as_unset() {
let settings = BasicInfoSettings::new();
let loaded = round_trip(&settings);
assert!(loaded.device_location.is_none());
let mut settings = BasicInfoSettings::new();
settings.set_location("US");
settings.location_type = Some(super::RegulatoryLocationType::Indoor);
settings.device_location = Some(Nullable::none());
settings.reset();
assert!(settings.location.is_none());
assert!(settings.location_type.is_none());
assert!(settings.device_location.is_none());
}
#[test]
fn recovery_identifier_survives_persistence_and_resets() {
let mut settings = BasicInfoSettings::new();
assert!(settings.recovery_identifier.is_none());
assert!(round_trip(&settings).recovery_identifier.is_none());
settings.recovery_identifier = Some(0x1122_3344_5566_7788);
assert_eq!(
round_trip(&settings).recovery_identifier,
Some(0x1122_3344_5566_7788)
);
settings.reset();
assert!(settings.recovery_identifier.is_none());
}
#[test]
fn unique_id_survives_persistence_and_resets() {
let mut settings = BasicInfoSettings::new();
assert!(settings.unique_id.is_none());
assert!(round_trip(&settings).unique_id.is_none());
settings.recovery_identifier = Some(1);
settings.unique_id = Some(0x0123_4567_89AB_CDEF);
let loaded = round_trip(&settings);
assert_eq!(loaded.unique_id, Some(0x0123_4567_89AB_CDEF));
assert_eq!(loaded.recovery_identifier, Some(1));
settings.reset();
assert!(settings.unique_id.is_none());
}
#[allow(unused)]
fn _t(_: TLVElement) {}
}