//! Matter TLV encoders and decoders for Time Synchronization Cluster
//! Cluster ID: 0x0038
//!
//! This file is automatically generated from TimeSync.xml
#![allow(clippy::too_many_arguments)]
use crate::tlv;
use anyhow;
use serde_json;
// Enum definitions
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Granularity {
/// This indicates that the node is not currently synchronized with a UTC Time source and its clock is based on the Last Known Good UTC Time only.
Notimegranularity = 0,
/// This indicates the node was synchronized to an upstream source in the past, but sufficient clock drift has occurred such that the clock error is now > 5 seconds.
Minutesgranularity = 1,
/// This indicates the node is synchronized to an upstream source using a low resolution protocol. UTC Time is accurate to ± 5 seconds.
Secondsgranularity = 2,
/// This indicates the node is synchronized to an upstream source using high resolution time-synchronization protocol such as NTP, or has built-in GNSS with some amount of jitter applying its GNSS timestamp. UTC Time is accurate to ± 50 ms.
Millisecondsgranularity = 3,
/// This indicates the node is synchronized to an upstream source using a highly precise time-synchronization protocol such as PTP, or has built-in GNSS. UTC time is accurate to ± 10 μs.
Microsecondsgranularity = 4,
}
impl Granularity {
/// Convert from u8 value
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(Granularity::Notimegranularity),
1 => Some(Granularity::Minutesgranularity),
2 => Some(Granularity::Secondsgranularity),
3 => Some(Granularity::Millisecondsgranularity),
4 => Some(Granularity::Microsecondsgranularity),
_ => None,
}
}
/// Convert to u8 value
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<Granularity> for u8 {
fn from(val: Granularity) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum StatusCode {
/// Node rejected the attempt to set the UTC time
Timenotaccepted = 2,
}
impl StatusCode {
/// Convert from u8 value
pub fn from_u8(value: u8) -> Option<Self> {
match value {
2 => Some(StatusCode::Timenotaccepted),
_ => None,
}
}
/// Convert to u8 value
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<StatusCode> for u8 {
fn from(val: StatusCode) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TimeSource {
/// Node is not currently synchronized with a UTC Time source.
None = 0,
/// Node uses an unlisted time source.
Unknown = 1,
/// Node received time from a client using the SetUTCTime Command.
Admin = 2,
/// Synchronized time by querying the Time Synchronization cluster of another Node.
Nodetimecluster = 3,
/// SNTP from a server not in the Matter network. NTS is not used.
Nonmattersntp = 4,
/// NTP from servers not in the Matter network. None of the servers used NTS.
Nonmatterntp = 5,
/// SNTP from a server within the Matter network. NTS is not used.
Mattersntp = 6,
/// NTP from servers within the Matter network. None of the servers used NTS.
Matterntp = 7,
/// NTP from multiple servers in the Matter network and external. None of the servers used NTS.
Mixedntp = 8,
/// SNTP from a server not in the Matter network. NTS is used.
Nonmattersntpnts = 9,
/// NTP from servers not in the Matter network. NTS is used on at least one server.
Nonmatterntpnts = 10,
/// SNTP from a server within the Matter network. NTS is used.
Mattersntpnts = 11,
/// NTP from a server within the Matter network. NTS is used on at least one server.
Matterntpnts = 12,
/// NTP from multiple servers in the Matter network and external. NTS is used on at least one server.
Mixedntpnts = 13,
/// Time synchronization comes from a vendor cloud-based source (e.g. "Date" header in authenticated HTTPS connection).
Cloudsource = 14,
/// Time synchronization comes from PTP.
Ptp = 15,
/// Time synchronization comes from a GNSS source.
Gnss = 16,
}
impl TimeSource {
/// Convert from u8 value
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(TimeSource::None),
1 => Some(TimeSource::Unknown),
2 => Some(TimeSource::Admin),
3 => Some(TimeSource::Nodetimecluster),
4 => Some(TimeSource::Nonmattersntp),
5 => Some(TimeSource::Nonmatterntp),
6 => Some(TimeSource::Mattersntp),
7 => Some(TimeSource::Matterntp),
8 => Some(TimeSource::Mixedntp),
9 => Some(TimeSource::Nonmattersntpnts),
10 => Some(TimeSource::Nonmatterntpnts),
11 => Some(TimeSource::Mattersntpnts),
12 => Some(TimeSource::Matterntpnts),
13 => Some(TimeSource::Mixedntpnts),
14 => Some(TimeSource::Cloudsource),
15 => Some(TimeSource::Ptp),
16 => Some(TimeSource::Gnss),
_ => None,
}
}
/// Convert to u8 value
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<TimeSource> for u8 {
fn from(val: TimeSource) -> Self {
val as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum TimeZoneDatabase {
/// Node has a full list of the available time zones
Full = 0,
/// Node has a partial list of the available time zones
Partial = 1,
/// Node does not have a time zone database
None = 2,
}
impl TimeZoneDatabase {
/// Convert from u8 value
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(TimeZoneDatabase::Full),
1 => Some(TimeZoneDatabase::Partial),
2 => Some(TimeZoneDatabase::None),
_ => None,
}
}
/// Convert to u8 value
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<TimeZoneDatabase> for u8 {
fn from(val: TimeZoneDatabase) -> Self {
val as u8
}
}
// Struct definitions
#[derive(Debug, serde::Serialize)]
pub struct DSTOffset {
pub offset: Option<i32>,
pub valid_starting: Option<u64>,
pub valid_until: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct FabricScopedTrustedTimeSource {
pub node_id: Option<u64>,
pub endpoint: Option<u16>,
}
#[derive(Debug, serde::Serialize)]
pub struct TimeZone {
pub offset: Option<i32>,
pub valid_at: Option<u64>,
pub name: Option<String>,
}
#[derive(Debug, serde::Serialize)]
pub struct TrustedTimeSource {
pub fabric_index: Option<u8>,
pub node_id: Option<u64>,
pub endpoint: Option<u16>,
}
// Command encoders
/// Encode SetUTCTime command (0x00)
pub fn encode_set_utc_time(utc_time: u64, granularity: Granularity, time_source: Option<TimeSource>) -> anyhow::Result<Vec<u8>> {
let mut tlv_fields: Vec<tlv::TlvItemEnc> = Vec::new();
tlv_fields.push((0, tlv::TlvItemValueEnc::UInt64(utc_time)).into());
tlv_fields.push((1, tlv::TlvItemValueEnc::UInt8(granularity.to_u8())).into());
if let Some(x) = time_source { tlv_fields.push((2, tlv::TlvItemValueEnc::UInt8(x.to_u8())).into()); }
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(tlv_fields),
};
Ok(tlv.encode()?)
}
/// Encode SetTrustedTimeSource command (0x01)
pub fn encode_set_trusted_time_source(trusted_time_source: Option<FabricScopedTrustedTimeSource>) -> anyhow::Result<Vec<u8>> {
// Encode optional struct FabricScopedTrustedTimeSourceStruct
let trusted_time_source_enc = if let Some(s) = trusted_time_source {
let mut fields = Vec::new();
if let Some(x) = s.node_id { fields.push((0, tlv::TlvItemValueEnc::UInt64(x)).into()); }
if let Some(x) = s.endpoint { fields.push((1, tlv::TlvItemValueEnc::UInt16(x)).into()); }
tlv::TlvItemValueEnc::StructInvisible(fields)
} else {
tlv::TlvItemValueEnc::StructInvisible(Vec::new())
};
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, trusted_time_source_enc).into(),
]),
};
Ok(tlv.encode()?)
}
/// Encode SetTimeZone command (0x02)
pub fn encode_set_time_zone(time_zone: Vec<TimeZone>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::Array(time_zone.into_iter().map(|v| {
let mut fields = Vec::new();
if let Some(x) = v.offset { fields.push((0, tlv::TlvItemValueEnc::Int32(x)).into()); }
if let Some(x) = v.valid_at { fields.push((1, tlv::TlvItemValueEnc::UInt64(x)).into()); }
if let Some(x) = v.name { fields.push((2, tlv::TlvItemValueEnc::String(x.clone())).into()); }
(0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
}).collect())).into(),
]),
};
Ok(tlv.encode()?)
}
/// Encode SetDSTOffset command (0x04)
pub fn encode_set_dst_offset(dst_offset: Vec<DSTOffset>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::Array(dst_offset.into_iter().map(|v| {
let mut fields = Vec::new();
if let Some(x) = v.offset { fields.push((0, tlv::TlvItemValueEnc::Int32(x)).into()); }
if let Some(x) = v.valid_starting { fields.push((1, tlv::TlvItemValueEnc::UInt64(x)).into()); }
if let Some(x) = v.valid_until { fields.push((2, tlv::TlvItemValueEnc::UInt64(x)).into()); }
(0, tlv::TlvItemValueEnc::StructAnon(fields)).into()
}).collect())).into(),
]),
};
Ok(tlv.encode()?)
}
/// Encode SetDefaultNTP command (0x05)
pub fn encode_set_default_ntp(default_ntp: Option<String>) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::String(default_ntp.unwrap_or("".to_string()))).into(),
]),
};
Ok(tlv.encode()?)
}
// Attribute decoders
/// Decode UTCTime attribute (0x0000)
pub fn decode_utc_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
/// Decode Granularity attribute (0x0001)
pub fn decode_granularity(inp: &tlv::TlvItemValue) -> anyhow::Result<Granularity> {
if let tlv::TlvItemValue::Int(v) = inp {
Granularity::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
/// Decode TimeSource attribute (0x0002)
pub fn decode_time_source(inp: &tlv::TlvItemValue) -> anyhow::Result<TimeSource> {
if let tlv::TlvItemValue::Int(v) = inp {
TimeSource::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
/// Decode TrustedTimeSource attribute (0x0003)
pub fn decode_trusted_time_source(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<TrustedTimeSource>> {
if let tlv::TlvItemValue::List(_fields) = inp {
// Struct with fields
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(Some(TrustedTimeSource {
fabric_index: item.get_int(&[0]).map(|v| v as u8),
node_id: item.get_int(&[1]),
endpoint: item.get_int(&[2]).map(|v| v as u16),
}))
//} else if let tlv::TlvItemValue::Null = inp {
// // Null value for nullable struct
// Ok(None)
} else {
Ok(None)
// Err(anyhow::anyhow!("Expected struct fields or null"))
}
}
/// Decode DefaultNTP attribute (0x0004)
pub fn decode_default_ntp(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<String>> {
if let tlv::TlvItemValue::String(v) = inp {
Ok(Some(v.clone()))
} else {
Ok(None)
}
}
/// Decode TimeZone attribute (0x0005)
pub fn decode_time_zone(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TimeZone>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(TimeZone {
offset: item.get_int(&[0]).map(|v| v as i32),
valid_at: item.get_int(&[1]),
name: item.get_string_owned(&[2]),
});
}
}
Ok(res)
}
/// Decode DSTOffset attribute (0x0006)
pub fn decode_dst_offset(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<DSTOffset>> {
let mut res = Vec::new();
if let tlv::TlvItemValue::List(v) = inp {
for item in v {
res.push(DSTOffset {
offset: item.get_int(&[0]).map(|v| v as i32),
valid_starting: item.get_int(&[1]),
valid_until: item.get_int(&[2]),
});
}
}
Ok(res)
}
/// Decode LocalTime attribute (0x0007)
pub fn decode_local_time(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<u64>> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(Some(*v))
} else {
Ok(None)
}
}
/// Decode TimeZoneDatabase attribute (0x0008)
pub fn decode_time_zone_database(inp: &tlv::TlvItemValue) -> anyhow::Result<TimeZoneDatabase> {
if let tlv::TlvItemValue::Int(v) = inp {
TimeZoneDatabase::from_u8(*v as u8).ok_or_else(|| anyhow::anyhow!("Invalid enum value"))
} else {
Err(anyhow::anyhow!("Expected Integer"))
}
}
/// Decode NTPServerAvailable attribute (0x0009)
pub fn decode_ntp_server_available(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
if let tlv::TlvItemValue::Bool(v) = inp {
Ok(*v)
} else {
Err(anyhow::anyhow!("Expected Bool"))
}
}
/// Decode TimeZoneListMaxSize attribute (0x000A)
pub fn decode_time_zone_list_max_size(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
/// Decode DSTOffsetListMaxSize attribute (0x000B)
pub fn decode_dst_offset_list_max_size(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
if let tlv::TlvItemValue::Int(v) = inp {
Ok(*v as u8)
} else {
Err(anyhow::anyhow!("Expected UInt8"))
}
}
/// Decode SupportsDNSResolve attribute (0x000C)
pub fn decode_supports_dns_resolve(inp: &tlv::TlvItemValue) -> anyhow::Result<bool> {
if let tlv::TlvItemValue::Bool(v) = inp {
Ok(*v)
} else {
Err(anyhow::anyhow!("Expected Bool"))
}
}
// JSON dispatcher function
/// Decode attribute value and return as JSON string
///
/// # Parameters
/// * `cluster_id` - The cluster identifier
/// * `attribute_id` - The attribute identifier
/// * `tlv_value` - The TLV value to decode
///
/// # Returns
/// JSON string representation of the decoded value or error
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
// Verify this is the correct cluster
if cluster_id != 0x0038 {
return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0038, got {}\"}}", cluster_id);
}
match attribute_id {
0x0000 => {
match decode_utc_time(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0001 => {
match decode_granularity(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0002 => {
match decode_time_source(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0003 => {
match decode_trusted_time_source(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0004 => {
match decode_default_ntp(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0005 => {
match decode_time_zone(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0006 => {
match decode_dst_offset(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0007 => {
match decode_local_time(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0008 => {
match decode_time_zone_database(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x0009 => {
match decode_ntp_server_available(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x000A => {
match decode_time_zone_list_max_size(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x000B => {
match decode_dst_offset_list_max_size(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
0x000C => {
match decode_supports_dns_resolve(tlv_value) {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
Err(e) => format!("{{\"error\": \"{}\"}}", e),
}
}
_ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
}
}
/// Get list of all attributes supported by this cluster
///
/// # Returns
/// Vector of tuples containing (attribute_id, attribute_name)
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
vec![
(0x0000, "UTCTime"),
(0x0001, "Granularity"),
(0x0002, "TimeSource"),
(0x0003, "TrustedTimeSource"),
(0x0004, "DefaultNTP"),
(0x0005, "TimeZone"),
(0x0006, "DSTOffset"),
(0x0007, "LocalTime"),
(0x0008, "TimeZoneDatabase"),
(0x0009, "NTPServerAvailable"),
(0x000A, "TimeZoneListMaxSize"),
(0x000B, "DSTOffsetListMaxSize"),
(0x000C, "SupportsDNSResolve"),
]
}
// Command listing
pub fn get_command_list() -> Vec<(u32, &'static str)> {
vec![
(0x00, "SetUTCTime"),
(0x01, "SetTrustedTimeSource"),
(0x02, "SetTimeZone"),
(0x04, "SetDSTOffset"),
(0x05, "SetDefaultNTP"),
]
}
pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
match cmd_id {
0x00 => Some("SetUTCTime"),
0x01 => Some("SetTrustedTimeSource"),
0x02 => Some("SetTimeZone"),
0x04 => Some("SetDSTOffset"),
0x05 => Some("SetDefaultNTP"),
_ => None,
}
}
pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
match cmd_id {
0x00 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "utc_time", kind: crate::clusters::codec::FieldKind::U64, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 1, name: "granularity", kind: crate::clusters::codec::FieldKind::Enum { name: "Granularity", variants: &[(0, "Notimegranularity"), (1, "Minutesgranularity"), (2, "Secondsgranularity"), (3, "Millisecondsgranularity"), (4, "Microsecondsgranularity")] }, optional: false, nullable: false },
crate::clusters::codec::CommandField { tag: 2, name: "time_source", kind: crate::clusters::codec::FieldKind::Enum { name: "TimeSource", variants: &[(0, "None"), (1, "Unknown"), (2, "Admin"), (3, "Nodetimecluster"), (4, "Nonmattersntp"), (5, "Nonmatterntp"), (6, "Mattersntp"), (7, "Matterntp"), (8, "Mixedntp"), (9, "Nonmattersntpnts"), (10, "Nonmatterntpnts"), (11, "Mattersntpnts"), (12, "Matterntpnts"), (13, "Mixedntpnts"), (14, "Cloudsource"), (15, "Ptp"), (16, "Gnss")] }, optional: true, nullable: false },
]),
0x01 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "trusted_time_source", kind: crate::clusters::codec::FieldKind::Struct { name: "FabricScopedTrustedTimeSourceStruct" }, optional: false, nullable: true },
]),
0x02 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "time_zone", kind: crate::clusters::codec::FieldKind::List { entry_type: "TimeZoneStruct" }, optional: false, nullable: false },
]),
0x04 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "dst_offset", kind: crate::clusters::codec::FieldKind::List { entry_type: "DSTOffsetStruct" }, optional: false, nullable: false },
]),
0x05 => Some(vec![
crate::clusters::codec::CommandField { tag: 0, name: "default_ntp", kind: crate::clusters::codec::FieldKind::String, optional: false, nullable: true },
]),
_ => None,
}
}
pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
match cmd_id {
0x00 => {
let utc_time = crate::clusters::codec::json_util::get_u64(args, "utc_time")?;
let granularity = {
let n = crate::clusters::codec::json_util::get_u64(args, "granularity")?;
Granularity::from_u8(n as u8).ok_or_else(|| anyhow::anyhow!("invalid Granularity: {}", n))?
};
let time_source = crate::clusters::codec::json_util::get_opt_u64(args, "time_source")?
.and_then(|n| TimeSource::from_u8(n as u8));
encode_set_utc_time(utc_time, granularity, time_source)
}
0x01 => Err(anyhow::anyhow!("command \"SetTrustedTimeSource\" has complex args: use raw mode")),
0x02 => Err(anyhow::anyhow!("command \"SetTimeZone\" has complex args: use raw mode")),
0x04 => Err(anyhow::anyhow!("command \"SetDSTOffset\" has complex args: use raw mode")),
0x05 => {
let default_ntp = crate::clusters::codec::json_util::get_opt_string(args, "default_ntp")?;
encode_set_default_ntp(default_ntp)
}
_ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
}
}
#[derive(Debug, serde::Serialize)]
pub struct SetTimeZoneResponse {
pub dst_offset_required: Option<bool>,
}
// Command response decoders
/// Decode SetTimeZoneResponse command response (03)
pub fn decode_set_time_zone_response(inp: &tlv::TlvItemValue) -> anyhow::Result<SetTimeZoneResponse> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(SetTimeZoneResponse {
dst_offset_required: item.get_bool(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
// Typed facade (invokes + reads)
/// Invoke `SetUTCTime` command on cluster `Time Synchronization`.
pub async fn set_utc_time(conn: &crate::controller::Connection, endpoint: u16, utc_time: u64, granularity: Granularity, time_source: Option<TimeSource>) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETUTCTIME, &encode_set_utc_time(utc_time, granularity, time_source)?).await?;
Ok(())
}
/// Invoke `SetTrustedTimeSource` command on cluster `Time Synchronization`.
pub async fn set_trusted_time_source(conn: &crate::controller::Connection, endpoint: u16, trusted_time_source: Option<FabricScopedTrustedTimeSource>) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETTRUSTEDTIMESOURCE, &encode_set_trusted_time_source(trusted_time_source)?).await?;
Ok(())
}
/// Invoke `SetTimeZone` command on cluster `Time Synchronization`.
pub async fn set_time_zone(conn: &crate::controller::Connection, endpoint: u16, time_zone: Vec<TimeZone>) -> anyhow::Result<SetTimeZoneResponse> {
let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETTIMEZONE, &encode_set_time_zone(time_zone)?).await?;
decode_set_time_zone_response(&tlv)
}
/// Invoke `SetDSTOffset` command on cluster `Time Synchronization`.
pub async fn set_dst_offset(conn: &crate::controller::Connection, endpoint: u16, dst_offset: Vec<DSTOffset>) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETDSTOFFSET, &encode_set_dst_offset(dst_offset)?).await?;
Ok(())
}
/// Invoke `SetDefaultNTP` command on cluster `Time Synchronization`.
pub async fn set_default_ntp(conn: &crate::controller::Connection, endpoint: u16, default_ntp: Option<String>) -> anyhow::Result<()> {
conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_CMD_ID_SETDEFAULTNTP, &encode_set_default_ntp(default_ntp)?).await?;
Ok(())
}
/// Read `UTCTime` attribute from cluster `Time Synchronization`.
pub async fn read_utc_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_UTCTIME).await?;
decode_utc_time(&tlv)
}
/// Read `Granularity` attribute from cluster `Time Synchronization`.
pub async fn read_granularity(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Granularity> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_GRANULARITY).await?;
decode_granularity(&tlv)
}
/// Read `TimeSource` attribute from cluster `Time Synchronization`.
pub async fn read_time_source(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TimeSource> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMESOURCE).await?;
decode_time_source(&tlv)
}
/// Read `TrustedTimeSource` attribute from cluster `Time Synchronization`.
pub async fn read_trusted_time_source(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<TrustedTimeSource>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TRUSTEDTIMESOURCE).await?;
decode_trusted_time_source(&tlv)
}
/// Read `DefaultNTP` attribute from cluster `Time Synchronization`.
pub async fn read_default_ntp(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<String>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_DEFAULTNTP).await?;
decode_default_ntp(&tlv)
}
/// Read `TimeZone` attribute from cluster `Time Synchronization`.
pub async fn read_time_zone(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<TimeZone>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMEZONE).await?;
decode_time_zone(&tlv)
}
/// Read `DSTOffset` attribute from cluster `Time Synchronization`.
pub async fn read_dst_offset(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Vec<DSTOffset>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_DSTOFFSET).await?;
decode_dst_offset(&tlv)
}
/// Read `LocalTime` attribute from cluster `Time Synchronization`.
pub async fn read_local_time(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<Option<u64>> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_LOCALTIME).await?;
decode_local_time(&tlv)
}
/// Read `TimeZoneDatabase` attribute from cluster `Time Synchronization`.
pub async fn read_time_zone_database(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<TimeZoneDatabase> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMEZONEDATABASE).await?;
decode_time_zone_database(&tlv)
}
/// Read `NTPServerAvailable` attribute from cluster `Time Synchronization`.
pub async fn read_ntp_server_available(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_NTPSERVERAVAILABLE).await?;
decode_ntp_server_available(&tlv)
}
/// Read `TimeZoneListMaxSize` attribute from cluster `Time Synchronization`.
pub async fn read_time_zone_list_max_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_TIMEZONELISTMAXSIZE).await?;
decode_time_zone_list_max_size(&tlv)
}
/// Read `DSTOffsetListMaxSize` attribute from cluster `Time Synchronization`.
pub async fn read_dst_offset_list_max_size(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<u8> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_DSTOFFSETLISTMAXSIZE).await?;
decode_dst_offset_list_max_size(&tlv)
}
/// Read `SupportsDNSResolve` attribute from cluster `Time Synchronization`.
pub async fn read_supports_dns_resolve(conn: &crate::controller::Connection, endpoint: u16) -> anyhow::Result<bool> {
let tlv = conn.read_request2(endpoint, crate::clusters::defs::CLUSTER_ID_TIME_SYNCHRONIZATION, crate::clusters::defs::CLUSTER_TIME_SYNCHRONIZATION_ATTR_ID_SUPPORTSDNSRESOLVE).await?;
decode_supports_dns_resolve(&tlv)
}
#[derive(Debug, serde::Serialize)]
pub struct DSTStatusEvent {
pub dst_offset_active: Option<bool>,
}
#[derive(Debug, serde::Serialize)]
pub struct TimeZoneStatusEvent {
pub offset: Option<i32>,
pub name: Option<String>,
}
// Event decoders
/// Decode DSTStatus event (0x01, priority: info)
pub fn decode_dst_status_event(inp: &tlv::TlvItemValue) -> anyhow::Result<DSTStatusEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(DSTStatusEvent {
dst_offset_active: item.get_bool(&[0]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}
/// Decode TimeZoneStatus event (0x02, priority: info)
pub fn decode_time_zone_status_event(inp: &tlv::TlvItemValue) -> anyhow::Result<TimeZoneStatusEvent> {
if let tlv::TlvItemValue::List(_fields) = inp {
let item = tlv::TlvItem { tag: 0, value: inp.clone() };
Ok(TimeZoneStatusEvent {
offset: item.get_int(&[0]).map(|v| v as i32),
name: item.get_string_owned(&[1]),
})
} else {
Err(anyhow::anyhow!("Expected struct fields"))
}
}