use core::fmt;
use crate::app::{Address, Application, Manufacturer, Medium};
use crate::time::DateTime;
use crate::wired::{self, BROADCAST, Frame, NETWORK_LAYER, control};
use crate::{Error, Result};
pub mod ci {
pub const APPLICATION_RESET: u8 = 0x50;
pub const DATA_SEND: u8 = 0x51;
pub const SELECT: u8 = 0x52;
pub const BAUD_300: u8 = 0xB8;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SecondaryAddress {
pub digits: [Option<u8>; 8],
pub manufacturer: Option<Manufacturer>,
pub version: Option<u8>,
pub medium: Option<Medium>,
}
impl SecondaryAddress {
pub const ANY: Self = Self { digits: [None; 8], manufacturer: None, version: None, medium: None };
pub fn id(number: u32) -> Option<Self> {
if number > 99_999_999 {
return None;
}
#[allow(clippy::cast_possible_truncation)] let d = |k: u32| Some((number / k % 10) as u8);
let digits = [d(10_000_000), d(1_000_000), d(100_000), d(10_000), d(1_000), d(100), d(10), d(1)];
Some(Self { digits, ..Self::ANY })
}
pub fn exact(address: &Address) -> Self {
let mut digits = [None; 8];
let [a, b, c, d] = address.id;
for (slot, byte) in digits.chunks_exact_mut(2).zip([d, c, b, a]) {
if let [high, low] = slot {
*high = Some(byte >> 4).filter(|&x| x <= 9);
*low = Some(byte & 0x0F).filter(|&x| x <= 9);
}
}
Self {
digits,
manufacturer: Some(address.manufacturer),
version: Some(address.version),
medium: Some(address.medium),
}
}
pub fn pattern(text: &str) -> Option<Self> {
let mut out = Self::ANY;
for (n, c) in text.bytes().enumerate() {
let slot = out.digits.get_mut(n)?;
*slot = match c {
b'0'..=b'9' => Some(c - b'0'),
b'F' | b'f' | b'*' | b'?' => None,
_ => return None,
};
}
Some(out)
}
pub fn id_bytes(&self) -> [u8; 4] {
let nibble = |d: Option<u8>| d.unwrap_or(0x0F);
let mut out = [0u8; 4];
for (i, pair) in self.digits.chunks_exact(2).enumerate() {
if let ([high, low], Some(slot)) = (pair, out.get_mut(3 - i)) {
*slot = (nibble(*high) << 4) | nibble(*low);
}
}
out
}
pub fn matches(&self, address: &Address) -> bool {
let exact = Self::exact(address);
self.digits.iter().zip(exact.digits).all(|(want, got)| want.is_none() || *want == got)
&& self.manufacturer.is_none_or(|m| m == address.manufacturer)
&& self.version.is_none_or(|v| v == address.version)
&& self.medium.is_none_or(|m| m == address.medium)
}
pub fn to_bytes(&self) -> [u8; 8] {
let [i0, i1, i2, i3] = self.id_bytes();
let [m0, m1] = self.manufacturer.map_or(0xFFFF, |m| m.0).to_le_bytes();
[i0, i1, i2, i3, m0, m1, self.version.unwrap_or(0xFF), self.medium.map_or(0xFF, |m| m.0)]
}
}
impl fmt::Display for SecondaryAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for d in self.digits {
match d {
Some(d) => write!(f, "{d}")?,
None => f.write_str("F")?,
}
}
if let Some(m) = self.manufacturer {
write!(f, " {m}")?;
}
if let Some(v) = self.version {
write!(f, " v{v}")?;
}
if let Some(m) = self.medium {
write!(f, " {m}")?;
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Baud {
B300,
B600,
B1200,
B2400,
B4800,
B9600,
B19200,
B38400,
}
impl Baud {
pub const fn bits_per_second(self) -> u32 {
match self {
Self::B300 => 300,
Self::B600 => 600,
Self::B1200 => 1200,
Self::B2400 => 2400,
Self::B4800 => 4800,
Self::B9600 => 9600,
Self::B19200 => 19200,
Self::B38400 => 38400,
}
}
const fn ci(self) -> u8 {
ci::BAUD_300
+ match self {
Self::B300 => 0,
Self::B600 => 1,
Self::B1200 => 2,
Self::B2400 => 3,
Self::B4800 => 4,
Self::B9600 => 5,
Self::B19200 => 6,
Self::B38400 => 7,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Request {
bytes: [u8; 32],
len: u8,
reply: bool,
}
pub const fn response_timeout_ms(baud: Baud) -> u32 {
(330 * 1000u32).div_ceil(baud.bits_per_second()) + 50
}
pub const RETRIES: u8 = 2;
impl Request {
const EMPTY: Self = Self { bytes: [0; 32], len: 0, reply: false };
fn from_frame(frame: &Frame<'_>, reply: bool) -> Result<Self> {
let mut bytes = [0u8; 32];
let n = frame.encode(&mut bytes)?;
Ok(Self { bytes, len: u8::try_from(n).map_err(|_| Error::OutputTooSmall)?, reply })
}
pub fn bytes(&self) -> &[u8] {
self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
}
pub const fn timeout_ms(&self, baud: Baud) -> u32 {
if self.reply { response_timeout_ms(baud) } else { 0 }
}
#[must_use]
pub fn with_fcb(mut self, fcb: bool) -> Self {
let len = usize::from(self.len);
let (c_at, sum) = match self.bytes() {
[0x10, ..] => (1, 1..3),
[0x68, ..] if len >= 6 => (4, 4..len - 2),
_ => return self,
};
if let Some(c) = self.bytes.get_mut(c_at) {
*c = (*c & !control::FCB) | if fcb { control::FCB } else { 0 };
}
let cs = self.bytes.get(sum).map_or(0, |b| b.iter().fold(0u8, |s, &x| s.wrapping_add(x)));
if let Some(slot) = self.bytes.get_mut(len - 2) {
*slot = cs;
}
self
}
pub const fn expects_reply(&self) -> bool {
self.reply
}
}
const fn timeout_for(address: u8) -> bool {
address != BROADCAST
}
pub fn link_reset(address: u8) -> Request {
Request::from_frame(&wired::snd_nke(address), timeout_for(address)).unwrap_or(Request::EMPTY)
}
fn snd_ud(address: u8, fcb: bool, ci: u8, data: &[u8]) -> Result<Request> {
let c = control::SND_UD | if fcb { control::FCB } else { 0 };
Request::from_frame(&Frame::Long { c, a: address, ci, data }, timeout_for(address))
}
pub fn select(address: &SecondaryAddress) -> Request {
snd_ud(NETWORK_LAYER, true, ci::SELECT, &address.to_bytes()).unwrap_or(Request::EMPTY)
}
pub fn select_enhanced(address: &SecondaryAddress, fabrication: Option<u32>) -> Request {
let fab = fabrication.and_then(SecondaryAddress::id).map_or([0xFF; 4], |f| f.id_bytes());
let [a, b, c, d, e, f, g, h] = address.to_bytes();
let [f0, f1, f2, f3] = fab;
snd_ud(NETWORK_LAYER, true, ci::SELECT, &[a, b, c, d, e, f, g, h, 0x0C, 0x78, f0, f1, f2, f3])
.unwrap_or(Request::EMPTY)
}
pub fn deselect() -> Request {
link_reset(NETWORK_LAYER)
}
pub fn set_primary_address(address: u8, new: u8) -> Option<Request> {
(new <= 250).then(|| snd_ud(address, false, ci::DATA_SEND, &[0x01, 0x7A, new]).unwrap_or(Request::EMPTY))
}
pub fn application_reset(address: u8, subcode: Option<u8>) -> Request {
let data = subcode.map(|s| [s]);
snd_ud(address, false, ci::APPLICATION_RESET, data.as_ref().map_or(&[][..], |d| &d[..]))
.unwrap_or(Request::EMPTY)
}
pub fn request_all_data(address: u8) -> Request {
snd_ud(address, false, ci::DATA_SEND, &[0x7F]).unwrap_or(Request::EMPTY)
}
pub fn set_baud(address: u8, baud: Baud) -> Request {
snd_ud(address, false, baud.ci(), &[]).unwrap_or(Request::EMPTY)
}
pub fn set_time(address: u8, time: &DateTime) -> Request {
let [a, b, c, d] = time.to_type_f();
snd_ud(address, false, ci::DATA_SEND, &[0x04, 0x6D, a, b, c, d]).unwrap_or(Request::EMPTY)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Target {
Primary(u8),
Secondary(SecondaryAddress),
}
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)] pub enum Event<'a> {
NeedMore,
Telegram(Application<'a>),
Found(Address),
Ambiguous(SecondaryAddress),
Acknowledged,
Retrying,
NoReply,
Invalid(Error),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReadState {
Reset,
Select,
Read,
Deselect,
Done,
Failed,
}
#[derive(Clone, Debug)]
pub struct Readout {
target: Target,
state: ReadState,
fcb: bool,
tries: u8,
retries: u8,
telegrams: u8,
max_telegrams: u8,
}
impl Readout {
pub const fn new(target: Target) -> Self {
let state = ReadState::Reset;
let _ = target;
Self { target, state, fcb: true, tries: 0, retries: RETRIES, telegrams: 0, max_telegrams: 16 }
}
#[must_use]
pub const fn retries(mut self, retries: u8) -> Self {
self.retries = retries;
self
}
#[must_use]
pub const fn max_telegrams(mut self, max: u8) -> Self {
self.max_telegrams = max;
self
}
const fn address(&self) -> u8 {
match self.target {
Target::Primary(a) => a,
Target::Secondary(_) => NETWORK_LAYER,
}
}
pub fn next_request(&mut self) -> Option<Request> {
Some(match (self.state, self.target) {
(ReadState::Reset, _) => link_reset(self.address()),
(ReadState::Select, Target::Secondary(s)) => select(&s),
(ReadState::Read, _) => {
Request::from_frame(&wired::req_ud2(self.address(), self.fcb), timeout_for(0)).ok()?
}
(ReadState::Deselect, _) => deselect(),
_ => return None,
})
}
pub const fn is_complete(&self) -> bool {
matches!(self.state, ReadState::Done)
}
pub const fn telegrams(&self) -> u8 {
self.telegrams
}
fn advance(&mut self, next: ReadState) {
self.state = next;
self.tries = 0;
}
fn after_read(&self) -> ReadState {
match self.target {
Target::Primary(_) => ReadState::Done,
Target::Secondary(_) => ReadState::Deselect,
}
}
pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
let _ = received;
if let (ReadState::Reset, Target::Secondary(_)) = (self.state, self.target) {
self.advance(ReadState::Select);
return Event::NoReply;
}
if self.state == ReadState::Deselect {
self.advance(ReadState::Done);
return Event::NoReply;
}
if self.tries < self.retries {
self.tries += 1;
Event::Retrying
} else {
self.state = ReadState::Failed;
Event::NoReply
}
}
pub fn reply<'a>(&mut self, bytes: &'a [u8]) -> Event<'a> {
let frame = match Frame::parse(bytes) {
Ok(None) => return Event::NeedMore,
Ok(Some((frame, _))) => frame,
Err(_) => return self.timeout(bytes),
};
match (self.state, frame) {
(ReadState::Reset, Frame::Ack) => {
self.fcb = true;
let next = match self.target {
Target::Primary(_) => ReadState::Read,
Target::Secondary(_) => ReadState::Select,
};
self.advance(next);
Event::Acknowledged
}
(ReadState::Select, Frame::Ack) => {
self.fcb = true;
self.advance(ReadState::Read);
Event::Acknowledged
}
(ReadState::Deselect, _) => {
self.advance(ReadState::Done);
Event::Acknowledged
}
(ReadState::Read, Frame::Ack) => {
self.advance(self.after_read());
Event::Acknowledged
}
(ReadState::Read, Frame::Long { ci, data, .. }) => match Application::parse(ci, data) {
Ok(app) => {
self.telegrams = self.telegrams.saturating_add(1);
let more =
app.records().is_some_and(|r| more_follows(r)) && self.telegrams < self.max_telegrams;
self.fcb = !self.fcb;
let next = if more { ReadState::Read } else { self.after_read() };
self.advance(next);
Event::Telegram(app)
}
Err(e) => {
self.advance(self.after_read());
Event::Invalid(e)
}
},
_ => self.timeout(bytes),
}
}
}
fn more_follows(mut records: crate::Records<'_>) -> bool {
for _ in records.by_ref() {}
records.more_follows()
}
#[derive(Clone, Debug)]
pub struct Search {
prefix: [u8; 8],
depth: u8,
reading: bool,
done: bool,
tries: u8,
retries: u8,
selections: u32,
max_selections: u32,
exhausted: bool,
}
impl Default for Search {
fn default() -> Self {
Self::new()
}
}
impl Search {
pub const fn new() -> Self {
Self {
prefix: [0; 8],
depth: 1,
reading: false,
done: false,
tries: 0,
retries: RETRIES,
selections: 0,
max_selections: 20_000,
exhausted: false,
}
}
#[must_use]
pub const fn max_selections(mut self, max: u32) -> Self {
self.max_selections = max;
self
}
pub const fn is_complete(&self) -> bool {
self.done && !self.exhausted
}
pub fn probe(&self) -> SecondaryAddress {
let mut s = SecondaryAddress::ANY;
for (slot, digit) in s.digits.iter_mut().zip(self.prefix).take(usize::from(self.depth)) {
*slot = Some(digit);
}
s
}
pub const fn selections(&self) -> u32 {
self.selections
}
pub fn next_request(&mut self) -> Option<Request> {
if self.done {
return None;
}
if self.reading {
return Request::from_frame(&wired::req_ud2(NETWORK_LAYER, true), timeout_for(0)).ok();
}
if self.tries == 0 {
if self.selections >= self.max_selections {
self.done = true;
self.exhausted = true;
return None;
}
self.selections = self.selections.saturating_add(1);
}
Some(select(&self.probe()))
}
fn next_sibling(&mut self) {
self.tries = 0;
self.reading = false;
loop {
let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) else {
self.done = true;
return;
};
if *d < 9 {
*d += 1;
return;
}
*d = 0;
if self.depth == 1 {
self.done = true;
return;
}
self.depth -= 1;
}
}
pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
if !received.is_empty() {
return self.collision();
}
if self.tries < self.retries {
self.tries += 1;
return Event::Retrying;
}
self.next_sibling();
Event::NoReply
}
fn collision(&mut self) -> Event<'static> {
self.reading = false;
self.tries = 0;
if self.depth >= 8 {
let probe = self.probe();
self.next_sibling();
return Event::Ambiguous(probe);
}
self.depth += 1;
if let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) {
*d = 0;
}
Event::Retrying
}
pub fn reply(&mut self, bytes: &[u8]) -> Event<'static> {
match Frame::parse(bytes) {
Ok(None) => Event::NeedMore,
Ok(Some((_, used))) if used < bytes.len() => self.collision(),
Ok(Some((Frame::Ack, _))) if !self.reading => {
self.reading = true;
self.tries = 0;
Event::Acknowledged
}
Ok(Some((Frame::Long { ci, data, .. }, _))) if self.reading => {
let found = Application::parse(ci, data).ok().and_then(|a| a.meter());
self.next_sibling();
found.map_or(Event::NoReply, Event::Found)
}
_ => self.collision(),
}
}
}