use crate::error::{Error, ErrorCode, Result, bail};
use crate::im::path::{AttributePath, ClusterPath, CommandPath, EventPath};
use crate::im::status::Status;
use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value, set_once};
pub type DataVersion = u32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct StatusIb {
pub status: Status,
pub cluster_status: Option<u8>,
}
impl From<Status> for StatusIb {
fn from(status: Status) -> Self {
Self::new(status)
}
}
impl StatusIb {
#[must_use]
pub const fn cluster_failure(cluster_status: u8) -> Self {
Self {
status: Status::Failure,
cluster_status: Some(cluster_status),
}
}
#[must_use]
pub const fn new(status: Status) -> Self {
Self {
status,
cluster_status: None,
}
}
pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
w.start_structure(tag)?;
w.unsigned(Tag::Context(0), u64::from(self.status.value()))?;
if let Some(cluster_status) = self.cluster_status {
w.unsigned(Tag::Context(1), u64::from(cluster_status))?;
}
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
let mut status = None;
let mut cluster_status = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => set_once(
&mut status,
Status::from_value(narrow8(element.unsigned()?)?),
)?,
Some(1) => set_once(&mut cluster_status, narrow8(element.unsigned()?)?)?,
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
cluster_status,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttributeData<'a> {
pub data_version: Option<DataVersion>,
pub path: AttributePath,
pub data: &'a [u8],
}
impl<'a> AttributeData<'a> {
pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
w.start_structure(tag)?;
if let Some(version) = self.data_version {
w.unsigned(Tag::Context(0), u64::from(version))?;
}
self.path.encode(w, Tag::Context(1))?;
w.raw_element(self.data)?;
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
let mut data_version = None;
let mut path = None;
let mut data = None;
loop {
let start = reader.position();
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => set_once(&mut data_version, narrow32(element.unsigned()?)?)?,
Some(1) => {
if element.value.container() != Some(ContainerKind::List) {
bail!(TlvWrongType)
}
set_once(&mut path, AttributePath::decode(reader)?)?;
}
Some(2) => {
reader.skip_value(&element)?;
set_once(&mut data, reader.slice_from(start)?)?;
}
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
data_version,
path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
data: data.ok_or(Error::new(ErrorCode::TlvNotFound))?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttributeStatus {
pub path: AttributePath,
pub status: StatusIb,
}
impl AttributeStatus {
pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
w.start_structure(tag)?;
self.path.encode(w, Tag::Context(0))?;
self.status.encode(w, Tag::Context(1))?;
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
let mut path = None;
let mut status = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
if element.value.container() != Some(ContainerKind::List) {
bail!(TlvWrongType)
}
set_once(&mut path, AttributePath::decode(reader)?)?;
}
Some(1) => {
if element.value.container() != Some(ContainerKind::Structure) {
bail!(TlvWrongType)
}
set_once(&mut status, StatusIb::decode(reader)?)?;
}
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttributeReport<'a> {
Status(AttributeStatus),
Data(AttributeData<'a>),
}
impl<'a> AttributeReport<'a> {
#[must_use]
pub const fn path(&self) -> AttributePath {
match self {
Self::Status(s) => s.path,
Self::Data(d) => d.path,
}
}
pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
w.start_structure(Tag::Anonymous)?;
match self {
Self::Status(status) => status.encode(w, Tag::Context(0))?,
Self::Data(data) => data.encode(w, Tag::Context(1))?,
}
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
let mut out = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
expect_structure(&element)?;
set_once(&mut out, Self::Status(AttributeStatus::decode(reader)?))?;
}
Some(1) => {
expect_structure(&element)?;
set_once(&mut out, Self::Data(AttributeData::decode(reader)?))?;
}
_ => reader.skip_value(&element)?,
}
}
out.ok_or(Error::new(ErrorCode::TlvNotFound))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DataVersionFilter {
pub path: ClusterPath,
pub data_version: DataVersion,
}
impl DataVersionFilter {
pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
w.start_structure(Tag::Anonymous)?;
self.path.encode(w, Tag::Context(0))?;
w.unsigned(Tag::Context(1), u64::from(self.data_version))?;
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
let mut path = None;
let mut data_version = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
if element.value.container() != Some(ContainerKind::List) {
bail!(TlvWrongType)
}
set_once(&mut path, ClusterPath::decode(reader)?)?;
}
Some(1) => set_once(&mut data_version, narrow32(element.unsigned()?)?)?,
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
data_version: data_version.ok_or(Error::new(ErrorCode::TlvNotFound))?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EventFilter {
pub node: Option<crate::msg::NodeId>,
pub event_min: u64,
}
impl EventFilter {
pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
w.start_structure(Tag::Anonymous)?;
if let Some(node) = self.node {
w.unsigned(Tag::Context(0), node.0)?;
}
w.unsigned(Tag::Context(1), self.event_min)?;
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
let mut node = None;
let mut event_min = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => set_once(&mut node, crate::msg::NodeId(element.unsigned()?))?,
Some(1) => set_once(&mut event_min, element.unsigned()?)?,
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
node,
event_min: event_min.ok_or(Error::new(ErrorCode::TlvNotFound))?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandData<'a> {
pub path: CommandPath,
pub fields: Option<&'a [u8]>,
pub command_ref: Option<u16>,
}
impl<'a> CommandData<'a> {
#[must_use]
pub const fn new(path: CommandPath) -> Self {
Self {
path,
fields: None,
command_ref: None,
}
}
pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
w.start_structure(Tag::Anonymous)?;
self.path.encode(w, Tag::Context(0))?;
if let Some(fields) = self.fields {
w.raw_element(fields)?;
}
if let Some(command_ref) = self.command_ref {
w.unsigned(Tag::Context(2), u64::from(command_ref))?;
}
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
let mut path = None;
let mut fields = None;
let mut command_ref = None;
loop {
let start = reader.position();
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
if element.value.container() != Some(ContainerKind::List) {
bail!(TlvWrongType)
}
set_once(&mut path, CommandPath::decode(reader)?)?;
}
Some(1) => {
reader.skip_value(&element)?;
set_once(&mut fields, reader.slice_from(start)?)?;
}
Some(2) => set_once(&mut command_ref, narrow16(element.unsigned()?)?)?,
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
fields,
command_ref,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandStatus {
pub path: CommandPath,
pub status: StatusIb,
pub command_ref: Option<u16>,
}
impl CommandStatus {
pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
w.start_structure(tag)?;
self.path.encode(w, Tag::Context(0))?;
self.status.encode(w, Tag::Context(1))?;
if let Some(command_ref) = self.command_ref {
w.unsigned(Tag::Context(2), u64::from(command_ref))?;
}
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
let mut path = None;
let mut status = None;
let mut command_ref = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
if element.value.container() != Some(ContainerKind::List) {
bail!(TlvWrongType)
}
set_once(&mut path, CommandPath::decode(reader)?)?;
}
Some(1) => {
expect_structure(&element)?;
set_once(&mut status, StatusIb::decode(reader)?)?;
}
Some(2) => set_once(&mut command_ref, narrow16(element.unsigned()?)?)?,
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
command_ref,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvokeResponse<'a> {
Command(CommandData<'a>),
Status(CommandStatus),
}
impl<'a> InvokeResponse<'a> {
pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
w.start_structure(Tag::Anonymous)?;
match self {
Self::Command(command) => {
w.start_structure(Tag::Context(0))?;
command.path.encode(w, Tag::Context(0))?;
if let Some(fields) = command.fields {
w.raw_element(fields)?;
}
if let Some(command_ref) = command.command_ref {
w.unsigned(Tag::Context(2), u64::from(command_ref))?;
}
w.end_container()?;
}
Self::Status(status) => status.encode(w, Tag::Context(1))?,
}
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
let mut out = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
expect_structure(&element)?;
set_once(&mut out, Self::Command(CommandData::decode(reader)?))?;
}
Some(1) => {
expect_structure(&element)?;
set_once(&mut out, Self::Status(CommandStatus::decode(reader)?))?;
}
_ => reader.skip_value(&element)?,
}
}
out.ok_or(Error::new(ErrorCode::TlvNotFound))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EventStatus {
pub path: EventPath,
pub status: StatusIb,
}
impl EventStatus {
pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
w.start_structure(tag)?;
self.path.encode(w, Tag::Context(0))?;
self.status.encode(w, Tag::Context(1))?;
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'_>) -> Result<Self> {
let mut path = None;
let mut status = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
if element.value.container() != Some(ContainerKind::List) {
bail!(TlvWrongType)
}
set_once(&mut path, EventPath::decode(reader)?)?;
}
Some(1) => {
expect_structure(&element)?;
set_once(&mut status, StatusIb::decode(reader)?)?;
}
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
status: status.ok_or(Error::new(ErrorCode::TlvNotFound))?,
})
}
}
fn expect_structure(element: &Element<'_>) -> Result<()> {
if element.value.container() == Some(ContainerKind::Structure) {
Ok(())
} else {
Err(Error::new(ErrorCode::TlvWrongType))
}
}
fn narrow8(value: u64) -> Result<u8> {
u8::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
}
fn narrow16(value: u64) -> Result<u16> {
u16::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
}
fn narrow32(value: u64) -> Result<u32> {
u32::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EventData<'a> {
pub path: EventPath,
pub number: u64,
pub priority: u8,
pub timestamp: EventTimestamp,
pub data: &'a [u8],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventTimestamp {
Epoch(u64),
System(u64),
DeltaEpoch(u64),
DeltaSystem(u64),
}
impl EventTimestamp {
#[must_use]
pub const fn tag(self) -> u8 {
match self {
Self::Epoch(_) => 3,
Self::System(_) => 4,
Self::DeltaEpoch(_) => 5,
Self::DeltaSystem(_) => 6,
}
}
#[must_use]
pub const fn value(self) -> u64 {
match self {
Self::Epoch(value)
| Self::System(value)
| Self::DeltaEpoch(value)
| Self::DeltaSystem(value) => value,
}
}
#[must_use]
pub const fn is_delta(self) -> bool {
matches!(self, Self::DeltaEpoch(_) | Self::DeltaSystem(_))
}
}
impl<'a> EventData<'a> {
pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
w.start_structure(tag)?;
self.path.encode(w, Tag::Context(0))?;
w.unsigned(Tag::Context(1), self.number)?;
w.unsigned(Tag::Context(2), u64::from(self.priority))?;
w.unsigned(Tag::Context(self.timestamp.tag()), self.timestamp.value())?;
w.raw_element(self.data)?;
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
let mut path = None;
let mut number = None;
let mut priority = None;
let mut timestamp: Option<EventTimestamp> = None;
let mut data = None;
loop {
let start = reader.position();
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => {
let decoded = EventPath::decode(reader)?;
set_once(&mut path, decoded)?;
}
Some(1) => set_once(&mut number, element.unsigned()?)?,
Some(2) => set_once(&mut priority, narrow8(element.unsigned()?)?)?,
Some(3) => set_once(&mut timestamp, EventTimestamp::Epoch(element.unsigned()?))?,
Some(4) => set_once(&mut timestamp, EventTimestamp::System(element.unsigned()?))?,
Some(5) => {
set_once(
&mut timestamp,
EventTimestamp::DeltaEpoch(element.unsigned()?),
)?;
}
Some(6) => {
set_once(
&mut timestamp,
EventTimestamp::DeltaSystem(element.unsigned()?),
)?;
}
Some(7) => {
reader.skip_value(&element)?;
set_once(&mut data, reader.slice_from(start)?)?;
}
_ => reader.skip_value(&element)?,
}
}
Ok(Self {
path: path.ok_or(Error::new(ErrorCode::TlvNotFound))?,
number: number.ok_or(Error::new(ErrorCode::TlvNotFound))?,
priority: priority.ok_or(Error::new(ErrorCode::TlvNotFound))?,
timestamp: timestamp.ok_or(Error::new(ErrorCode::TlvNotFound))?,
data: data.ok_or(Error::new(ErrorCode::TlvNotFound))?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventReport<'a> {
Status(EventStatus),
Data(EventData<'a>),
}
impl<'a> EventReport<'a> {
pub fn encode(&self, w: &mut TlvWriter<'_>) -> Result<()> {
w.start_structure(Tag::Anonymous)?;
match self {
Self::Status(status) => status.encode(w, Tag::Context(0))?,
Self::Data(data) => data.encode(w, Tag::Context(1))?,
}
w.end_container()
}
pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
let mut report = None;
loop {
let Some(element) = reader.next_element()? else {
bail!(TlvTruncated)
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(0) => set_once(&mut report, Self::Status(EventStatus::decode(reader)?))?,
Some(1) => set_once(&mut report, Self::Data(EventData::decode(reader)?))?,
_ => reader.skip_value(&element)?,
}
}
report.ok_or(Error::new(ErrorCode::TlvNotFound))
}
}