1use core::fmt;
37
38use crate::app::{Address, Application, Manufacturer, Medium};
39use crate::time::DateTime;
40use crate::wired::{self, BROADCAST, Frame, NETWORK_LAYER, control};
41use crate::{Error, Result};
42
43pub mod ci {
45 pub const APPLICATION_RESET: u8 = 0x50;
47 pub const DATA_SEND: u8 = 0x51;
49 pub const SELECT: u8 = 0x52;
51 pub const BAUD_300: u8 = 0xB8;
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
60pub struct SecondaryAddress {
61 pub digits: [Option<u8>; 8],
63 pub manufacturer: Option<Manufacturer>,
65 pub version: Option<u8>,
67 pub medium: Option<Medium>,
69}
70
71impl SecondaryAddress {
72 pub const ANY: Self = Self { digits: [None; 8], manufacturer: None, version: None, medium: None };
74
75 pub fn id(number: u32) -> Option<Self> {
78 if number > 99_999_999 {
79 return None;
80 }
81 #[allow(clippy::cast_possible_truncation)] let d = |k: u32| Some((number / k % 10) as u8);
84 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)];
85 Some(Self { digits, ..Self::ANY })
86 }
87
88 pub fn exact(address: &Address) -> Self {
90 let mut digits = [None; 8];
91 let [a, b, c, d] = address.id;
92 for (slot, byte) in digits.chunks_exact_mut(2).zip([d, c, b, a]) {
93 if let [high, low] = slot {
94 *high = Some(byte >> 4).filter(|&x| x <= 9);
95 *low = Some(byte & 0x0F).filter(|&x| x <= 9);
96 }
97 }
98 Self {
99 digits,
100 manufacturer: Some(address.manufacturer),
101 version: Some(address.version),
102 medium: Some(address.medium),
103 }
104 }
105
106 pub fn pattern(text: &str) -> Option<Self> {
109 let mut out = Self::ANY;
110 for (n, c) in text.bytes().enumerate() {
111 let slot = out.digits.get_mut(n)?;
112 *slot = match c {
113 b'0'..=b'9' => Some(c - b'0'),
114 b'F' | b'f' | b'*' | b'?' => None,
115 _ => return None,
116 };
117 }
118 Some(out)
119 }
120
121 pub fn id_bytes(&self) -> [u8; 4] {
123 let nibble = |d: Option<u8>| d.unwrap_or(0x0F);
124 let mut out = [0u8; 4];
125 for (i, pair) in self.digits.chunks_exact(2).enumerate() {
126 if let ([high, low], Some(slot)) = (pair, out.get_mut(3 - i)) {
127 *slot = (nibble(*high) << 4) | nibble(*low);
128 }
129 }
130 out
131 }
132
133 pub fn matches(&self, address: &Address) -> bool {
135 let exact = Self::exact(address);
136 self.digits.iter().zip(exact.digits).all(|(want, got)| want.is_none() || *want == got)
137 && self.manufacturer.is_none_or(|m| m == address.manufacturer)
138 && self.version.is_none_or(|v| v == address.version)
139 && self.medium.is_none_or(|m| m == address.medium)
140 }
141
142 pub fn to_bytes(&self) -> [u8; 8] {
145 let [i0, i1, i2, i3] = self.id_bytes();
146 let [m0, m1] = self.manufacturer.map_or(0xFFFF, |m| m.0).to_le_bytes();
147 [i0, i1, i2, i3, m0, m1, self.version.unwrap_or(0xFF), self.medium.map_or(0xFF, |m| m.0)]
148 }
149}
150
151impl fmt::Display for SecondaryAddress {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 for d in self.digits {
155 match d {
156 Some(d) => write!(f, "{d}")?,
157 None => f.write_str("F")?,
158 }
159 }
160 if let Some(m) = self.manufacturer {
161 write!(f, " {m}")?;
162 }
163 if let Some(v) = self.version {
164 write!(f, " v{v}")?;
165 }
166 if let Some(m) = self.medium {
167 write!(f, " {m}")?;
168 }
169 Ok(())
170 }
171}
172
173#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
175pub enum Baud {
176 B300,
178 B600,
180 B1200,
182 B2400,
184 B4800,
186 B9600,
188 B19200,
190 B38400,
192}
193
194impl Baud {
195 pub const fn bits_per_second(self) -> u32 {
197 match self {
198 Self::B300 => 300,
199 Self::B600 => 600,
200 Self::B1200 => 1200,
201 Self::B2400 => 2400,
202 Self::B4800 => 4800,
203 Self::B9600 => 9600,
204 Self::B19200 => 19200,
205 Self::B38400 => 38400,
206 }
207 }
208
209 const fn ci(self) -> u8 {
210 ci::BAUD_300
211 + match self {
212 Self::B300 => 0,
213 Self::B600 => 1,
214 Self::B1200 => 2,
215 Self::B2400 => 3,
216 Self::B4800 => 4,
217 Self::B9600 => 5,
218 Self::B19200 => 6,
219 Self::B38400 => 7,
220 }
221 }
222}
223
224#[derive(Clone, Copy, Debug, PartialEq, Eq)]
226pub struct Request {
227 bytes: [u8; 32],
228 len: u8,
229 reply: bool,
230}
231
232pub const fn response_timeout_ms(baud: Baud) -> u32 {
235 (330 * 1000u32).div_ceil(baud.bits_per_second()) + 50
236}
237
238pub const RETRIES: u8 = 2;
240
241impl Request {
242 const EMPTY: Self = Self { bytes: [0; 32], len: 0, reply: false };
243
244 fn from_frame(frame: &Frame<'_>, reply: bool) -> Result<Self> {
245 let mut bytes = [0u8; 32];
246 let n = frame.encode(&mut bytes)?;
247 Ok(Self { bytes, len: u8::try_from(n).map_err(|_| Error::OutputTooSmall)?, reply })
248 }
249
250 pub fn bytes(&self) -> &[u8] {
252 self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
253 }
254
255 pub const fn timeout_ms(&self, baud: Baud) -> u32 {
258 if self.reply { response_timeout_ms(baud) } else { 0 }
259 }
260
261 #[must_use]
265 pub fn with_fcb(mut self, fcb: bool) -> Self {
266 let len = usize::from(self.len);
267 let (c_at, sum) = match self.bytes() {
268 [0x10, ..] => (1, 1..3),
269 [0x68, ..] if len >= 6 => (4, 4..len - 2),
270 _ => return self,
271 };
272 if let Some(c) = self.bytes.get_mut(c_at) {
273 *c = (*c & !control::FCB) | if fcb { control::FCB } else { 0 };
274 }
275 let cs = self.bytes.get(sum).map_or(0, |b| b.iter().fold(0u8, |s, &x| s.wrapping_add(x)));
276 if let Some(slot) = self.bytes.get_mut(len - 2) {
277 *slot = cs;
278 }
279 self
280 }
281
282 pub const fn expects_reply(&self) -> bool {
284 self.reply
285 }
286}
287
288const fn timeout_for(address: u8) -> bool {
289 address != BROADCAST
290}
291
292pub fn link_reset(address: u8) -> Request {
294 Request::from_frame(&wired::snd_nke(address), timeout_for(address)).unwrap_or(Request::EMPTY)
296}
297
298fn snd_ud(address: u8, fcb: bool, ci: u8, data: &[u8]) -> Result<Request> {
299 let c = control::SND_UD | if fcb { control::FCB } else { 0 };
300 Request::from_frame(&Frame::Long { c, a: address, ci, data }, timeout_for(address))
301}
302
303pub fn select(address: &SecondaryAddress) -> Request {
307 snd_ud(NETWORK_LAYER, true, ci::SELECT, &address.to_bytes()).unwrap_or(Request::EMPTY)
308}
309
310pub fn select_enhanced(address: &SecondaryAddress, fabrication: Option<u32>) -> Request {
314 let fab = fabrication.and_then(SecondaryAddress::id).map_or([0xFF; 4], |f| f.id_bytes());
315 let [a, b, c, d, e, f, g, h] = address.to_bytes();
316 let [f0, f1, f2, f3] = fab;
317 snd_ud(NETWORK_LAYER, true, ci::SELECT, &[a, b, c, d, e, f, g, h, 0x0C, 0x78, f0, f1, f2, f3])
318 .unwrap_or(Request::EMPTY)
319}
320
321pub fn deselect() -> Request {
323 link_reset(NETWORK_LAYER)
324}
325
326pub fn set_primary_address(address: u8, new: u8) -> Option<Request> {
330 (new <= 250).then(|| snd_ud(address, false, ci::DATA_SEND, &[0x01, 0x7A, new]).unwrap_or(Request::EMPTY))
331}
332
333pub fn application_reset(address: u8, subcode: Option<u8>) -> Request {
337 let data = subcode.map(|s| [s]);
338 snd_ud(address, false, ci::APPLICATION_RESET, data.as_ref().map_or(&[][..], |d| &d[..]))
339 .unwrap_or(Request::EMPTY)
340}
341
342pub fn request_all_data(address: u8) -> Request {
344 snd_ud(address, false, ci::DATA_SEND, &[0x7F]).unwrap_or(Request::EMPTY)
345}
346
347pub fn set_baud(address: u8, baud: Baud) -> Request {
350 snd_ud(address, false, baud.ci(), &[]).unwrap_or(Request::EMPTY)
351}
352
353pub fn set_time(address: u8, time: &DateTime) -> Request {
355 let [a, b, c, d] = time.to_type_f();
356 snd_ud(address, false, ci::DATA_SEND, &[0x04, 0x6D, a, b, c, d]).unwrap_or(Request::EMPTY)
357}
358
359#[derive(Clone, Copy, Debug, PartialEq, Eq)]
361pub enum Target {
362 Primary(u8),
364 Secondary(SecondaryAddress),
366}
367
368#[derive(Clone, Debug)]
370#[allow(clippy::large_enum_variant)] pub enum Event<'a> {
372 NeedMore,
375 Telegram(Application<'a>),
377 Found(Address),
379 Ambiguous(SecondaryAddress),
382 Acknowledged,
384 Retrying,
386 NoReply,
388 Invalid(Error),
390 Unreadable(SecondaryAddress),
394 WrongMeter(Option<Address>),
397}
398
399#[derive(Clone, Copy, Debug, PartialEq, Eq)]
401pub enum Outcome {
402 Complete,
405 LimitReached,
408 Invalid(Error),
411 WrongMeter(Option<Address>),
415 NoReply,
417}
418
419impl fmt::Display for Outcome {
420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421 match self {
422 Self::Complete => f.write_str("complete"),
423 Self::LimitReached => f.write_str("telegram limit reached, the meter has more records"),
424 Self::Invalid(e) => write!(f, "invalid telegram: {e}"),
425 Self::WrongMeter(Some(a)) => write!(f, "another meter answered: {a}"),
426 Self::WrongMeter(None) => f.write_str("another meter answered (without an identity)"),
427 Self::NoReply => f.write_str("the meter does not answer"),
428 }
429 }
430}
431
432#[derive(Clone, Copy, Debug, PartialEq, Eq)]
433enum ReadState {
434 Reset,
435 Select,
436 Read,
437 Deselect,
438 Done,
439}
440
441#[derive(Clone, Debug)]
466pub struct Readout {
467 target: Target,
468 state: ReadState,
469 fcb: bool,
470 tries: u8,
471 retries: u8,
472 telegrams: u8,
473 max_telegrams: u8,
474 expect: Option<SecondaryAddress>,
475 first: Option<Address>,
477 outcome: Option<Outcome>,
478}
479
480impl Readout {
481 pub const fn new(target: Target) -> Self {
483 let (state, outcome) = match target {
486 Target::Primary(a @ (251 | 252 | BROADCAST)) => {
487 (ReadState::Done, Some(Outcome::Invalid(Error::InvalidAddress(a))))
488 }
489 _ => (ReadState::Reset, None),
490 };
491 Self {
492 target,
493 state,
494 fcb: true,
495 tries: 0,
496 retries: RETRIES,
497 telegrams: 0,
498 max_telegrams: 16,
499 expect: None,
500 first: None,
501 outcome,
502 }
503 }
504
505 #[must_use]
507 pub const fn retries(mut self, retries: u8) -> Self {
508 self.retries = retries;
509 self
510 }
511
512 #[must_use]
515 pub const fn max_telegrams(mut self, max: u8) -> Self {
516 self.max_telegrams = max;
517 self
518 }
519
520 #[must_use]
525 pub const fn expect_meter(mut self, meter: SecondaryAddress) -> Self {
526 self.expect = Some(meter);
527 self
528 }
529
530 const fn address(&self) -> u8 {
531 match self.target {
532 Target::Primary(a) => a,
533 Target::Secondary(_) => NETWORK_LAYER,
534 }
535 }
536
537 pub fn next_request(&mut self) -> Option<Request> {
539 Some(match (self.state, self.target) {
540 (ReadState::Reset, _) => link_reset(self.address()),
542 (ReadState::Select, Target::Secondary(s)) => select(&s),
543 (ReadState::Read, _) => {
544 Request::from_frame(&wired::req_ud2(self.address(), self.fcb), timeout_for(0)).ok()?
545 }
546 (ReadState::Deselect, _) => deselect(),
547 _ => return None,
548 })
549 }
550
551 pub const fn outcome(&self) -> Option<Outcome> {
553 match self.state {
554 ReadState::Done => self.outcome,
555 _ => None,
556 }
557 }
558
559 pub const fn is_complete(&self) -> bool {
561 matches!(self.outcome(), Some(Outcome::Complete))
562 }
563
564 pub const fn telegrams(&self) -> u8 {
566 self.telegrams
567 }
568
569 const fn advance(&mut self, next: ReadState) {
570 self.state = next;
571 self.tries = 0;
572 }
573
574 const fn finish(&mut self, outcome: Outcome) {
576 self.outcome = Some(outcome);
577 let next = match (self.target, self.state) {
578 (Target::Secondary(_), ReadState::Select | ReadState::Read) => ReadState::Deselect,
579 _ => ReadState::Done,
580 };
581 self.advance(next);
582 }
583
584 pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
587 let _ = received;
588 match (self.state, self.target) {
589 (ReadState::Reset, Target::Secondary(_)) => {
591 self.advance(ReadState::Select);
592 return Event::NoReply;
593 }
594 (ReadState::Deselect, _) => {
596 self.advance(ReadState::Done);
597 return Event::NoReply;
598 }
599 (ReadState::Done, _) => return Event::NoReply,
600 _ => {}
601 }
602 if self.tries < self.retries {
603 self.tries += 1;
604 Event::Retrying
605 } else {
606 self.finish(Outcome::NoReply);
607 Event::NoReply
608 }
609 }
610
611 pub fn reply<'a>(&mut self, frame: &'a [u8]) -> Event<'a> {
613 let (parsed, used) = match Frame::parse(frame) {
614 Ok(None) => return Event::NeedMore,
615 Ok(Some(parsed)) => parsed,
616 Err(_) => return self.timeout(frame),
617 };
618 if self.state == ReadState::Deselect {
619 self.advance(ReadState::Done);
620 return Event::Acknowledged;
621 }
622 if used != frame.len() {
623 return self.timeout(frame);
625 }
626 match (self.state, parsed) {
627 (ReadState::Reset, Frame::Ack) => {
628 self.fcb = true;
630 let next = match self.target {
631 Target::Primary(_) => ReadState::Read,
632 Target::Secondary(_) => ReadState::Select,
633 };
634 self.advance(next);
635 Event::Acknowledged
636 }
637 (ReadState::Select, Frame::Ack) => {
638 self.fcb = true;
639 self.advance(ReadState::Read);
640 Event::Acknowledged
641 }
642 (ReadState::Read, Frame::Ack) if self.telegrams > 0 => {
645 self.finish(Outcome::Complete);
646 Event::Acknowledged
647 }
648 (ReadState::Read, Frame::Long { c, a, ci, data }) if self.answers(c, a) => {
649 self.telegram(ci, data)
650 }
651 _ => self.timeout(frame),
652 }
653 }
654
655 const fn answers(&self, c: u8, a: u8) -> bool {
657 control::is_response(c)
658 && match self.target {
659 Target::Primary(p) if p <= 250 => a == p,
660 _ => true,
661 }
662 }
663
664 fn telegram<'a>(&mut self, ci: u8, data: &'a [u8]) -> Event<'a> {
665 let app = match Application::parse(ci, data) {
666 Ok(app) => app,
667 Err(e) => {
668 self.finish(Outcome::Invalid(e));
669 return Event::Invalid(e);
670 }
671 };
672 let meter = app.meter();
673 let selection = match self.target {
674 Target::Secondary(s) => Some(s),
675 Target::Primary(_) => None,
676 };
677 let fits = |p: &SecondaryAddress| *p == SecondaryAddress::ANY || meter.is_some_and(|m| p.matches(&m));
678 let same = self.telegrams == 0 || self.first == meter;
679 if !(selection.iter().chain(&self.expect).all(fits) && same) {
680 self.finish(Outcome::WrongMeter(meter));
681 return Event::WrongMeter(meter);
682 }
683 self.first = meter;
684 self.telegrams = self.telegrams.saturating_add(1);
685 self.fcb = !self.fcb;
686 match app.records().map(more_follows) {
687 Some(Err(e)) => self.finish(Outcome::Invalid(e)),
689 None | Some(Ok(false)) => self.finish(Outcome::Complete),
690 Some(Ok(true)) if self.telegrams >= self.max_telegrams.max(1) => {
691 self.finish(Outcome::LimitReached);
692 }
693 Some(Ok(true)) => self.advance(ReadState::Read),
694 }
695 Event::Telegram(app)
696 }
697}
698
699#[allow(clippy::needless_pass_by_value)] fn more_follows(mut records: crate::Records<'_>) -> Result<bool> {
703 for r in records.by_ref() {
704 r?;
705 }
706 Ok(records.more_follows())
707}
708
709#[derive(Clone, Debug)]
717pub struct Search {
718 prefix: [u8; 8],
719 depth: u8,
720 reading: bool,
721 done: bool,
722 tries: u8,
723 retries: u8,
724 selections: u32,
725 max_selections: u32,
726 exhausted: bool,
727}
728
729impl Default for Search {
730 fn default() -> Self {
731 Self::new()
732 }
733}
734
735impl Search {
736 pub const fn new() -> Self {
738 Self {
739 prefix: [0; 8],
740 depth: 1,
741 reading: false,
742 done: false,
743 tries: 0,
744 retries: RETRIES,
745 selections: 0,
746 max_selections: 25_000,
747 exhausted: false,
748 }
749 }
750
751 #[must_use]
755 pub const fn max_selections(mut self, max: u32) -> Self {
756 self.max_selections = max;
757 self
758 }
759
760 pub const fn is_complete(&self) -> bool {
763 self.done && !self.exhausted
764 }
765
766 pub fn probe(&self) -> SecondaryAddress {
768 let mut s = SecondaryAddress::ANY;
769 for (slot, digit) in s.digits.iter_mut().zip(self.prefix).take(usize::from(self.depth)) {
770 *slot = Some(digit);
771 }
772 s
773 }
774
775 pub const fn selections(&self) -> u32 {
777 self.selections
778 }
779
780 pub fn next_request(&mut self) -> Option<Request> {
782 if self.done {
783 return None;
784 }
785 if self.reading {
786 return Request::from_frame(&wired::req_ud2(NETWORK_LAYER, true), timeout_for(0)).ok();
787 }
788 if self.tries == 0 {
789 if self.selections >= self.max_selections {
790 self.done = true;
791 self.exhausted = true;
792 return None;
793 }
794 self.selections = self.selections.saturating_add(1);
795 }
796 Some(select(&self.probe()))
797 }
798
799 fn next_sibling(&mut self) {
801 self.tries = 0;
802 self.reading = false;
803 loop {
804 let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) else {
805 self.done = true;
806 return;
807 };
808 if *d < 9 {
809 *d += 1;
810 return;
811 }
812 *d = 0;
813 if self.depth == 1 {
814 self.done = true;
815 return;
816 }
817 self.depth -= 1;
818 }
819 }
820
821 pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
824 if !received.is_empty() {
825 return self.collision();
826 }
827 if self.tries < self.retries {
828 self.tries += 1;
829 return Event::Retrying;
830 }
831 if self.reading {
832 return self.unreadable();
834 }
835 self.next_sibling();
837 Event::NoReply
838 }
839
840 fn unreadable(&mut self) -> Event<'static> {
841 let probe = self.probe();
842 self.next_sibling();
843 Event::Unreadable(probe)
844 }
845
846 fn collision(&mut self) -> Event<'static> {
848 self.reading = false;
849 self.tries = 0;
850 if self.depth >= 8 {
851 let probe = self.probe();
853 self.next_sibling();
854 return Event::Ambiguous(probe);
855 }
856 self.depth += 1;
857 if let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) {
858 *d = 0;
859 }
860 Event::Retrying
861 }
862
863 pub fn reply(&mut self, bytes: &[u8]) -> Event<'static> {
866 match Frame::parse(bytes) {
867 Ok(None) => Event::NeedMore,
868 Ok(Some((_, used))) if used < bytes.len() => self.collision(),
870 Ok(Some((Frame::Ack, _))) if !self.reading => {
871 self.reading = true;
872 self.tries = 0;
873 Event::Acknowledged
874 }
875 Ok(Some((Frame::Ack, _))) => self.timeout(&[]),
877 Ok(Some((Frame::Long { c, ci, data, .. }, _))) if self.reading && control::is_response(c) => {
878 let probe = self.probe();
879 match Application::parse(ci, data).ok().and_then(|a| a.meter()) {
880 Some(meter) if probe.matches(&meter) => {
881 self.next_sibling();
882 Event::Found(meter)
883 }
884 _ => self.unreadable(),
885 }
886 }
887 _ => self.collision(),
889 }
890 }
891}