use crate::tlv;
use anyhow;
use serde_json;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Granularity {
Notimegranularity = 0,
Minutesgranularity = 1,
Secondsgranularity = 2,
Millisecondsgranularity = 3,
Microsecondsgranularity = 4,
}
impl Granularity {
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,
}
}
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 {
Timenotaccepted = 2,
}
impl StatusCode {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
2 => Some(StatusCode::Timenotaccepted),
_ => None,
}
}
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 {
None = 0,
Unknown = 1,
Admin = 2,
Nodetimecluster = 3,
Nonmattersntp = 4,
Nonmatterntp = 5,
Mattersntp = 6,
Matterntp = 7,
Mixedntp = 8,
Nonmattersntpnts = 9,
Nonmatterntpnts = 10,
Mattersntpnts = 11,
Matterntpnts = 12,
Mixedntpnts = 13,
Cloudsource = 14,
Ptp = 15,
Gnss = 16,
}
impl TimeSource {
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,
}
}
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 {
Full = 0,
Partial = 1,
None = 2,
}
impl TimeZoneDatabase {
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(TimeZoneDatabase::Full),
1 => Some(TimeZoneDatabase::Partial),
2 => Some(TimeZoneDatabase::None),
_ => None,
}
}
pub fn to_u8(self) -> u8 {
self as u8
}
}
impl From<TimeZoneDatabase> for u8 {
fn from(val: TimeZoneDatabase) -> Self {
val as u8
}
}
#[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>,
}
pub fn encode_set_utc_time(utc_time: u64, granularity: Granularity, time_source: TimeSource) -> anyhow::Result<Vec<u8>> {
let tlv = tlv::TlvItemEnc {
tag: 0,
value: tlv::TlvItemValueEnc::StructInvisible(vec![
(0, tlv::TlvItemValueEnc::UInt64(utc_time)).into(),
(1, tlv::TlvItemValueEnc::UInt8(granularity.to_u8())).into(),
(2, tlv::TlvItemValueEnc::UInt8(time_source.to_u8())).into(),
]),
};
Ok(tlv.encode()?)
}
pub fn encode_set_trusted_time_source(trusted_time_source: Option<FabricScopedTrustedTimeSource>) -> anyhow::Result<Vec<u8>> {
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()?)
}
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()?)
}
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()?)
}
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()?)
}
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)
}
}
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"))
}
}
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"))
}
}
pub fn decode_trusted_time_source(inp: &tlv::TlvItemValue) -> anyhow::Result<Option<TrustedTimeSource>> {
if let tlv::TlvItemValue::List(_fields) = inp {
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 {
Ok(None)
}
}
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)
}
}
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)
}
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)
}
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)
}
}
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"))
}
}
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"))
}
}
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"))
}
}
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"))
}
}
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"))
}
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
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),
}
}
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"),
]
}
#[derive(Debug, serde::Serialize)]
pub struct SetTimeZoneResponse {
pub dst_offset_required: Option<bool>,
}
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"))
}
}
#[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>,
}
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"))
}
}
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"))
}
}