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 ALL: [Self; 8] = [
Self::B300,
Self::B600,
Self::B1200,
Self::B2400,
Self::B4800,
Self::B9600,
Self::B19200,
Self::B38400,
];
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,
}
}
}
impl TryFrom<u32> for Baud {
type Error = Error;
fn try_from(bits_per_second: u32) -> Result<Self> {
Self::ALL
.into_iter()
.find(|b| b.bits_per_second() == bits_per_second)
.ok_or(Error::InvalidBaud(bits_per_second))
}
}
#[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),
Unreadable(SecondaryAddress),
WrongMeter(Option<Address>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
Complete,
LimitReached,
Invalid(Error),
WrongMeter(Option<Address>),
NoReply {
heard: Heard,
},
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Complete => f.write_str("complete"),
Self::LimitReached => f.write_str("telegram limit reached, the meter has more records"),
Self::Invalid(e @ Error::InvalidAddress(_)) => write!(f, "{e}"),
Self::Invalid(e) => write!(f, "invalid telegram: {e}"),
Self::WrongMeter(Some(a)) => write!(f, "another meter answered: {a}"),
Self::WrongMeter(None) => f.write_str("another meter answered (without an identity)"),
Self::NoReply { heard } => write!(f, "no reply, heard {heard}"),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Heard {
#[default]
Nothing,
Garbled,
Unexpected,
OtherAddress(u8),
}
impl fmt::Display for Heard {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Nothing => f.write_str("nothing"),
Self::Garbled => f.write_str("garbled bytes"),
Self::Unexpected => f.write_str("a frame that does not answer the request"),
Self::OtherAddress(a) => write!(f, "a response from primary address {a}"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReadState {
Reset,
Select,
Read,
Deselect,
Done,
}
#[derive(Clone, Debug)]
pub struct Readout {
target: Target,
state: ReadState,
fcb: bool,
tries: u8,
retries: u8,
telegrams: u8,
max_telegrams: u8,
expect: Option<SecondaryAddress>,
first: Option<Address>,
heard: Heard,
outcome: Option<Outcome>,
}
impl Readout {
pub const fn new(target: Target) -> Self {
let (state, outcome) = match target {
Target::Primary(a @ (251..=253 | BROADCAST)) => {
(ReadState::Done, Some(Outcome::Invalid(Error::InvalidAddress(a))))
}
_ => (ReadState::Reset, None),
};
Self {
target,
state,
fcb: true,
tries: 0,
retries: RETRIES,
telegrams: 0,
max_telegrams: 16,
expect: None,
first: None,
heard: Heard::Nothing,
outcome,
}
}
#[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
}
#[must_use]
pub const fn expect_meter(mut self, meter: SecondaryAddress) -> Self {
self.expect = Some(meter);
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 outcome(&self) -> Option<Outcome> {
match self.state {
ReadState::Done => self.outcome,
_ => None,
}
}
pub const fn is_complete(&self) -> bool {
matches!(self.outcome(), Some(Outcome::Complete))
}
pub const fn telegrams(&self) -> u8 {
self.telegrams
}
const fn advance(&mut self, next: ReadState) {
self.state = next;
self.tries = 0;
self.heard = Heard::Nothing;
}
const fn finish(&mut self, outcome: Outcome) {
self.outcome = Some(outcome);
let next = match (self.target, self.state) {
(Target::Secondary(_), ReadState::Select | ReadState::Read) => ReadState::Deselect,
_ => ReadState::Done,
};
self.advance(next);
}
pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
let heard = match wired::scan_ended(received) {
_ if received.is_empty() => Heard::Nothing,
wired::Scan::Frame { frame, skip, len } if skip + len == received.len() => self.judge(&frame),
_ => Heard::Garbled,
};
self.fail(heard)
}
const fn judge(&self, frame: &Frame<'_>) -> Heard {
match (self.state, self.target, frame) {
(ReadState::Read, Target::Primary(p), Frame::Long { c, a, .. })
if p <= 250 && *a != p && control::is_response(*c) =>
{
Heard::OtherAddress(*a)
}
_ => Heard::Unexpected,
}
}
fn fail(&mut self, heard: Heard) -> Event<'static> {
match (self.state, self.target) {
(ReadState::Reset, Target::Secondary(_)) => {
self.advance(ReadState::Select);
return Event::NoReply;
}
(ReadState::Deselect, _) => {
self.advance(ReadState::Done);
return Event::NoReply;
}
(ReadState::Done, _) => return Event::NoReply,
_ => {}
}
self.heard = self.heard.max(heard);
if self.tries < self.retries {
self.tries += 1;
Event::Retrying
} else {
self.finish(Outcome::NoReply { heard: self.heard });
Event::NoReply
}
}
pub fn reply<'a>(&mut self, frame: &'a [u8]) -> Event<'a> {
let (parsed, used) = match Frame::parse(frame) {
Ok(None) => return Event::NeedMore,
Ok(Some(parsed)) => parsed,
Err(_) => return self.fail(Heard::Garbled),
};
if self.state == ReadState::Deselect {
self.advance(ReadState::Done);
return Event::Acknowledged;
}
if used != frame.len() {
return self.fail(Heard::Garbled);
}
match (self.state, parsed) {
(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::Read, Frame::Ack) if self.telegrams > 0 => {
self.finish(Outcome::Complete);
Event::Acknowledged
}
(ReadState::Read, Frame::Long { c, a, ci, data }) if self.answers(c, a) => {
self.telegram(ci, data)
}
(_, parsed) => {
let heard = self.judge(&parsed);
self.fail(heard)
}
}
}
const fn answers(&self, c: u8, a: u8) -> bool {
control::is_response(c)
&& match self.target {
Target::Primary(p) if p <= 250 => a == p,
_ => true,
}
}
fn telegram<'a>(&mut self, ci: u8, data: &'a [u8]) -> Event<'a> {
let app = match Application::parse(ci, data) {
Ok(app) => app,
Err(e) => {
self.finish(Outcome::Invalid(e));
return Event::Invalid(e);
}
};
let meter = app.meter();
let selection = match self.target {
Target::Secondary(s) => Some(s),
Target::Primary(_) => None,
};
let fits = |p: &SecondaryAddress| *p == SecondaryAddress::ANY || meter.is_some_and(|m| p.matches(&m));
let same = self.telegrams == 0 || self.first == meter;
if !(selection.iter().chain(&self.expect).all(fits) && same) {
self.finish(Outcome::WrongMeter(meter));
return Event::WrongMeter(meter);
}
self.first = meter;
self.telegrams = self.telegrams.saturating_add(1);
self.fcb = !self.fcb;
match app.records().map(more_follows) {
Some(Err(e)) => self.finish(Outcome::Invalid(e)),
None | Some(Ok(false)) => self.finish(Outcome::Complete),
Some(Ok(true)) if self.telegrams >= self.max_telegrams.max(1) => {
self.finish(Outcome::LimitReached);
}
Some(Ok(true)) => self.advance(ReadState::Read),
}
Event::Telegram(app)
}
}
#[allow(clippy::needless_pass_by_value)] fn more_follows(mut records: crate::Records<'_>) -> Result<bool> {
for r in records.by_ref() {
r?;
}
Ok(records.more_follows())
}
#[allow(clippy::struct_excessive_bools)] #[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,
deselected: 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: 25_000,
exhausted: false,
deselected: 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 && !self.reading && self.tries == 0 && self.selections >= self.max_selections {
self.done = true;
self.exhausted = true;
}
if self.done {
if self.deselected {
return None;
}
self.deselected = true;
return Some(deselect());
}
if self.reading {
return Request::from_frame(&wired::req_ud2(NETWORK_LAYER, true), timeout_for(0)).ok();
}
if self.tries == 0 {
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 self.done {
return Event::NoReply;
}
if !received.is_empty() {
return self.collision();
}
if self.tries < self.retries {
self.tries += 1;
return Event::Retrying;
}
if self.reading {
return self.unreadable();
}
self.next_sibling();
Event::NoReply
}
fn unreadable(&mut self) -> Event<'static> {
let probe = self.probe();
self.next_sibling();
Event::Unreadable(probe)
}
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> {
if self.done {
return self.timeout(bytes);
}
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::Ack, _))) => self.timeout(&[]),
Ok(Some((Frame::Long { c, ci, data, .. }, _))) if self.reading && control::is_response(c) => {
let probe = self.probe();
match Application::parse(ci, data).ok().and_then(|a| a.meter()) {
Some(meter) if probe.matches(&meter) => {
self.next_sibling();
Event::Found(meter)
}
_ => self.unreadable(),
}
}
_ => self.collision(),
}
}
}