use crate::error::{Error, ErrorCode, Result, bail};
use crate::im::ib::AttributeReport;
use crate::im::message::ReportData;
use crate::tlv::{ContainerKind, TlvReader, Value};
const ANONYMOUS_ARRAY: u8 = 0x16;
const END_OF_CONTAINER: u8 = 0x18;
#[derive(Debug)]
pub struct ReportAssembler<const N: usize> {
buf: [u8; N],
len: usize,
subscription_id: Option<u32>,
chunks: usize,
complete: bool,
}
impl<const N: usize> Default for ReportAssembler<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> ReportAssembler<N> {
#[must_use]
pub const fn new() -> Self {
let mut buf = [0u8; N];
buf[0] = ANONYMOUS_ARRAY;
Self {
buf,
len: 1,
subscription_id: None,
chunks: 0,
complete: false,
}
}
pub const fn reset(&mut self) {
self.buf[0] = ANONYMOUS_ARRAY;
self.len = 1;
self.subscription_id = None;
self.chunks = 0;
self.complete = false;
}
#[must_use]
pub const fn is_complete(&self) -> bool {
self.complete
}
#[must_use]
pub const fn chunks(&self) -> usize {
self.chunks
}
#[must_use]
pub const fn subscription_id(&self) -> Option<u32> {
self.subscription_id
}
pub fn push(&mut self, report: &ReportData<'_>) -> Result<bool> {
if self.complete {
bail!(InvalidState)
}
match (self.subscription_id, report.subscription_id) {
(None, id) if self.chunks == 0 => self.subscription_id = id,
(held, id) if held == id => {}
_ => bail!(InvalidState),
}
if let Some(bytes) = report.attribute_reports_bytes() {
self.append_members(bytes)?;
}
self.chunks = self.chunks.saturating_add(1);
if !report.more_chunked_messages {
self.push_byte(END_OF_CONTAINER)?;
self.complete = true;
}
Ok(self.complete)
}
fn append_members(&mut self, array: &[u8]) -> Result<()> {
let mut reader = TlvReader::new_in(array, ContainerKind::Structure);
let Some(head) = reader.next_element()? else {
bail!(TlvTruncated)
};
if head.value.container() != Some(ContainerKind::Array) {
bail!(TlvWrongType)
}
loop {
let start = reader.position();
let Some(element) = reader.next_element()? else {
return Ok(());
};
if element.value == Value::EndOfContainer {
return Ok(());
}
reader.skip_value(&element)?;
let member = reader.slice_from(start)?;
let end = self
.len
.checked_add(member.len())
.and_then(|end| (end < N).then_some(end))
.ok_or(Error::new(ErrorCode::NoSpace))?;
let Some(slot) = self.buf.get_mut(self.len..end) else {
bail!(NoSpace)
};
slot.copy_from_slice(member);
self.len = end;
}
}
fn push_byte(&mut self, byte: u8) -> Result<()> {
let Some(slot) = self.buf.get_mut(self.len) else {
bail!(NoSpace)
};
*slot = byte;
self.len = self.len.saturating_add(1);
Ok(())
}
pub fn reports(&self) -> Reports<'_> {
let mut reader = TlvReader::new(self.assembled());
let opened = matches!(
reader.next_element(),
Ok(Some(element)) if element.value.container() == Some(ContainerKind::Array)
);
Reports {
reader,
done: !opened,
}
}
#[must_use]
pub fn assembled(&self) -> &[u8] {
self.buf.get(..self.len).unwrap_or(&[])
}
}
#[derive(Debug)]
pub struct Reports<'a> {
reader: TlvReader<'a>,
done: bool,
}
impl<'a> Iterator for Reports<'a> {
type Item = Result<AttributeReport<'a>>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
let element = match self.reader.next_element() {
Ok(Some(element)) => element,
Ok(None) => {
self.done = true;
return None;
}
Err(e) => {
self.done = true;
return Some(Err(e));
}
};
if element.value == Value::EndOfContainer {
self.done = true;
return None;
}
if element.value.container() != Some(ContainerKind::Structure) {
self.done = true;
return Some(Err(Error::new(ErrorCode::TlvWrongType)));
}
match AttributeReport::decode(&mut self.reader) {
Ok(report) => Some(Ok(report)),
Err(e) => {
self.done = true;
Some(Err(e))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::im::ib::AttributeData;
use crate::im::{AttributePath, encode_report_data};
use crate::tlv::{Tag, TlvWriter};
fn chunk(buf: &mut [u8], first: u32, values: &[u64], more: bool) -> usize {
let mut value_bufs: heapless::Vec<heapless::Vec<u8, 16>, 8> = heapless::Vec::new();
for value in values {
let mut scratch = [0u8; 16];
let mut w = TlvWriter::new_in(&mut scratch, ContainerKind::Structure);
w.unsigned(Tag::Context(2), *value).expect("value");
let encoded = w.finish().expect("finish");
value_bufs
.push(heapless::Vec::from_slice(encoded).expect("fits"))
.expect("fits");
}
let reports: heapless::Vec<AttributeReport<'_>, 8> = values
.iter()
.enumerate()
.map(|(index, _)| {
AttributeReport::Data(AttributeData {
data_version: Some(1),
path: AttributePath::attribute(1, 0x0006, first + index as u32),
data: &value_bufs[index],
})
})
.collect();
let bytes = encode_report_data(buf, None, reports, more, false).expect("encode");
bytes.len()
}
#[test]
fn a_report_split_across_messages_comes_back_whole_and_in_order() {
let mut assembler = ReportAssembler::<512>::new();
let mut first = [0u8; 256];
let n = chunk(&mut first, 0, &[10, 11], true);
let report = ReportData::decode(&first[..n]).expect("decode");
assert!(
!assembler.push(&report).expect("push"),
"more is coming, and the server is waiting for a StatusResponse"
);
let mut second = [0u8; 256];
let n = chunk(&mut second, 2, &[12], false);
let report = ReportData::decode(&second[..n]).expect("decode");
assert!(assembler.push(&report).expect("push"), "the last chunk");
assert!(assembler.is_complete());
assert_eq!(assembler.chunks(), 2);
let paths: heapless::Vec<u32, 8> = assembler
.reports()
.map(|r| r.expect("decode").path().attribute.expect("concrete"))
.collect();
assert_eq!(
paths.as_slice(),
&[0, 1, 2],
"every block, in the order it arrived — order is part of the answer"
);
}
#[test]
fn a_single_message_answer_is_complete_at_once() {
let mut assembler = ReportAssembler::<256>::new();
let mut buf = [0u8; 256];
let n = chunk(&mut buf, 0, &[42], false);
let report = ReportData::decode(&buf[..n]).expect("decode");
assert!(assembler.push(&report).expect("push"));
assert_eq!(assembler.chunks(), 1);
assert_eq!(assembler.reports().count(), 1);
}
#[test]
fn an_answer_larger_than_the_buffer_is_refused_rather_than_truncated() {
let mut assembler = ReportAssembler::<24>::new();
let mut buf = [0u8; 256];
let n = chunk(&mut buf, 0, &[1, 2, 3, 4], false);
let report = ReportData::decode(&buf[..n]).expect("decode");
assert_eq!(
assembler.push(&report).map_err(|e| e.code()),
Err(ErrorCode::NoSpace)
);
}
#[test]
fn a_chunk_after_the_last_one_is_refused() {
let mut assembler = ReportAssembler::<256>::new();
let mut buf = [0u8; 256];
let n = chunk(&mut buf, 0, &[1], false);
let report = ReportData::decode(&buf[..n]).expect("decode");
assert!(assembler.push(&report).expect("push"));
assert_eq!(
assembler.push(&report).map_err(|e| e.code()),
Err(ErrorCode::InvalidState)
);
}
#[test]
fn chunks_of_two_different_subscriptions_are_not_spliced_together() {
let mut assembler = ReportAssembler::<512>::new();
let mut first = [0u8; 256];
let mut scratch = [0u8; 16];
let mut w = TlvWriter::new_in(&mut scratch, ContainerKind::Structure);
w.unsigned(Tag::Context(2), 1).expect("value");
let value = w.finish().expect("finish").to_vec();
let report = AttributeReport::Data(AttributeData {
data_version: Some(1),
path: AttributePath::attribute(1, 0x0006, 0),
data: &value,
});
let bytes = encode_report_data(&mut first, Some(7), [report], true, false).expect("encode");
let len = bytes.len();
let decoded = ReportData::decode(&first[..len]).expect("decode");
assert!(!assembler.push(&decoded).expect("push"));
assert_eq!(assembler.subscription_id(), Some(7));
let mut second = [0u8; 256];
let report = AttributeReport::Data(AttributeData {
data_version: Some(1),
path: AttributePath::attribute(1, 0x0006, 1),
data: &value,
});
let bytes =
encode_report_data(&mut second, Some(9), [report], false, false).expect("encode");
let len = bytes.len();
let decoded = ReportData::decode(&second[..len]).expect("decode");
assert_eq!(
assembler.push(&decoded).map_err(|e| e.code()),
Err(ErrorCode::InvalidState),
"a different subscription id is a different answer"
);
}
#[test]
fn reset_makes_it_usable_for_the_next_read() {
let mut assembler = ReportAssembler::<256>::new();
let mut buf = [0u8; 256];
let n = chunk(&mut buf, 0, &[1], false);
let report = ReportData::decode(&buf[..n]).expect("decode");
assembler.push(&report).expect("push");
assembler.reset();
assert!(!assembler.is_complete());
assert_eq!(assembler.chunks(), 0);
assert_eq!(assembler.reports().count(), 0);
assembler.push(&report).expect("usable again");
assert!(assembler.is_complete());
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Subscription {
id: u32,
max_interval_s: u16,
last_heard: crate::platform::Instant,
}
impl Subscription {
#[must_use]
pub const fn new(
response: &crate::im::message::SubscribeResponse,
now: crate::platform::Instant,
) -> Self {
Self {
id: response.subscription_id,
max_interval_s: response.max_interval_s,
last_heard: now,
}
}
#[must_use]
pub const fn id(&self) -> u32 {
self.id
}
#[must_use]
pub const fn max_interval_s(&self) -> u16 {
self.max_interval_s
}
pub fn heard(&mut self, report: &ReportData<'_>, now: crate::platform::Instant) -> bool {
if report.subscription_id != Some(self.id) {
return false;
}
self.last_heard = now;
true
}
#[must_use]
pub fn expires_at(&self) -> crate::platform::Instant {
self.last_heard.saturating_add(
crate::platform::Duration::from_secs(u64::from(self.max_interval_s))
.saturating_add(LIVENESS_MARGIN),
)
}
#[must_use]
pub fn is_expired(&self, now: crate::platform::Instant) -> bool {
now >= self.expires_at()
}
}
pub const LIVENESS_MARGIN: crate::platform::Duration = crate::platform::Duration::from_secs(10);