1use core::fmt;
33
34use crate::app::{Address, Application, Manufacturer, Medium};
35use crate::time::DateTime;
36use crate::wired::{self, BROADCAST, Frame, NETWORK_LAYER, control};
37use crate::{Error, Result};
38
39pub mod ci {
41 pub const APPLICATION_RESET: u8 = 0x50;
43 pub const DATA_SEND: u8 = 0x51;
45 pub const SELECT: u8 = 0x52;
47 pub const BAUD_300: u8 = 0xB8;
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56pub struct SecondaryAddress {
57 pub digits: [Option<u8>; 8],
59 pub manufacturer: Option<Manufacturer>,
61 pub version: Option<u8>,
63 pub medium: Option<Medium>,
65}
66
67impl SecondaryAddress {
68 pub const ANY: Self = Self { digits: [None; 8], manufacturer: None, version: None, medium: None };
70
71 pub fn id(number: u32) -> Option<Self> {
74 if number > 99_999_999 {
75 return None;
76 }
77 #[allow(clippy::cast_possible_truncation)] let d = |k: u32| Some((number / k % 10) as u8);
80 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)];
81 Some(Self { digits, ..Self::ANY })
82 }
83
84 pub fn exact(address: &Address) -> Self {
86 let mut digits = [None; 8];
87 let [a, b, c, d] = address.id;
88 for (slot, byte) in digits.chunks_exact_mut(2).zip([d, c, b, a]) {
89 if let [high, low] = slot {
90 *high = Some(byte >> 4).filter(|&x| x <= 9);
91 *low = Some(byte & 0x0F).filter(|&x| x <= 9);
92 }
93 }
94 Self {
95 digits,
96 manufacturer: Some(address.manufacturer),
97 version: Some(address.version),
98 medium: Some(address.medium),
99 }
100 }
101
102 pub fn pattern(text: &str) -> Option<Self> {
105 let mut out = Self::ANY;
106 for (n, c) in text.bytes().enumerate() {
107 let slot = out.digits.get_mut(n)?;
108 *slot = match c {
109 b'0'..=b'9' => Some(c - b'0'),
110 b'F' | b'f' | b'*' | b'?' => None,
111 _ => return None,
112 };
113 }
114 Some(out)
115 }
116
117 pub fn id_bytes(&self) -> [u8; 4] {
119 let nibble = |d: Option<u8>| d.unwrap_or(0x0F);
120 let mut out = [0u8; 4];
121 for (i, pair) in self.digits.chunks_exact(2).enumerate() {
122 if let ([high, low], Some(slot)) = (pair, out.get_mut(3 - i)) {
123 *slot = (nibble(*high) << 4) | nibble(*low);
124 }
125 }
126 out
127 }
128
129 pub fn matches(&self, address: &Address) -> bool {
131 let exact = Self::exact(address);
132 self.digits.iter().zip(exact.digits).all(|(want, got)| want.is_none() || *want == got)
133 && self.manufacturer.is_none_or(|m| m == address.manufacturer)
134 && self.version.is_none_or(|v| v == address.version)
135 && self.medium.is_none_or(|m| m == address.medium)
136 }
137
138 pub fn to_bytes(&self) -> [u8; 8] {
141 let [i0, i1, i2, i3] = self.id_bytes();
142 let [m0, m1] = self.manufacturer.map_or(0xFFFF, |m| m.0).to_le_bytes();
143 [i0, i1, i2, i3, m0, m1, self.version.unwrap_or(0xFF), self.medium.map_or(0xFF, |m| m.0)]
144 }
145}
146
147impl fmt::Display for SecondaryAddress {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 for d in self.digits {
151 match d {
152 Some(d) => write!(f, "{d}")?,
153 None => f.write_str("F")?,
154 }
155 }
156 if let Some(m) = self.manufacturer {
157 write!(f, " {m}")?;
158 }
159 if let Some(v) = self.version {
160 write!(f, " v{v}")?;
161 }
162 if let Some(m) = self.medium {
163 write!(f, " {m}")?;
164 }
165 Ok(())
166 }
167}
168
169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171pub enum Baud {
172 B300,
174 B600,
176 B1200,
178 B2400,
180 B4800,
182 B9600,
184 B19200,
186 B38400,
188}
189
190impl Baud {
191 pub const fn bits_per_second(self) -> u32 {
193 match self {
194 Self::B300 => 300,
195 Self::B600 => 600,
196 Self::B1200 => 1200,
197 Self::B2400 => 2400,
198 Self::B4800 => 4800,
199 Self::B9600 => 9600,
200 Self::B19200 => 19200,
201 Self::B38400 => 38400,
202 }
203 }
204
205 const fn ci(self) -> u8 {
206 ci::BAUD_300
207 + match self {
208 Self::B300 => 0,
209 Self::B600 => 1,
210 Self::B1200 => 2,
211 Self::B2400 => 3,
212 Self::B4800 => 4,
213 Self::B9600 => 5,
214 Self::B19200 => 6,
215 Self::B38400 => 7,
216 }
217 }
218}
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222pub struct Request {
223 bytes: [u8; 32],
224 len: u8,
225 reply: bool,
226}
227
228pub const fn response_timeout_ms(baud: Baud) -> u32 {
231 (330 * 1000u32).div_ceil(baud.bits_per_second()) + 50
232}
233
234pub const RETRIES: u8 = 2;
236
237impl Request {
238 const EMPTY: Self = Self { bytes: [0; 32], len: 0, reply: false };
239
240 fn from_frame(frame: &Frame<'_>, reply: bool) -> Result<Self> {
241 let mut bytes = [0u8; 32];
242 let n = frame.encode(&mut bytes)?;
243 Ok(Self { bytes, len: u8::try_from(n).map_err(|_| Error::OutputTooSmall)?, reply })
244 }
245
246 pub fn bytes(&self) -> &[u8] {
248 self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
249 }
250
251 pub const fn timeout_ms(&self, baud: Baud) -> u32 {
254 if self.reply { response_timeout_ms(baud) } else { 0 }
255 }
256
257 #[must_use]
261 pub fn with_fcb(mut self, fcb: bool) -> Self {
262 let len = usize::from(self.len);
263 let (c_at, sum) = match self.bytes() {
264 [0x10, ..] => (1, 1..3),
265 [0x68, ..] if len >= 6 => (4, 4..len - 2),
266 _ => return self,
267 };
268 if let Some(c) = self.bytes.get_mut(c_at) {
269 *c = (*c & !control::FCB) | if fcb { control::FCB } else { 0 };
270 }
271 let cs = self.bytes.get(sum).map_or(0, |b| b.iter().fold(0u8, |s, &x| s.wrapping_add(x)));
272 if let Some(slot) = self.bytes.get_mut(len - 2) {
273 *slot = cs;
274 }
275 self
276 }
277
278 pub const fn expects_reply(&self) -> bool {
280 self.reply
281 }
282}
283
284const fn timeout_for(address: u8) -> bool {
285 address != BROADCAST
286}
287
288pub fn link_reset(address: u8) -> Request {
290 Request::from_frame(&wired::snd_nke(address), timeout_for(address)).unwrap_or(Request::EMPTY)
292}
293
294fn snd_ud(address: u8, fcb: bool, ci: u8, data: &[u8]) -> Result<Request> {
295 let c = control::SND_UD | if fcb { control::FCB } else { 0 };
296 Request::from_frame(&Frame::Long { c, a: address, ci, data }, timeout_for(address))
297}
298
299pub fn select(address: &SecondaryAddress) -> Request {
303 snd_ud(NETWORK_LAYER, true, ci::SELECT, &address.to_bytes()).unwrap_or(Request::EMPTY)
304}
305
306pub fn select_enhanced(address: &SecondaryAddress, fabrication: Option<u32>) -> Request {
310 let fab = fabrication.and_then(SecondaryAddress::id).map_or([0xFF; 4], |f| f.id_bytes());
311 let [a, b, c, d, e, f, g, h] = address.to_bytes();
312 let [f0, f1, f2, f3] = fab;
313 snd_ud(NETWORK_LAYER, true, ci::SELECT, &[a, b, c, d, e, f, g, h, 0x0C, 0x78, f0, f1, f2, f3])
314 .unwrap_or(Request::EMPTY)
315}
316
317pub fn deselect() -> Request {
319 link_reset(NETWORK_LAYER)
320}
321
322pub fn set_primary_address(address: u8, new: u8) -> Option<Request> {
326 (new <= 250).then(|| snd_ud(address, false, ci::DATA_SEND, &[0x01, 0x7A, new]).unwrap_or(Request::EMPTY))
327}
328
329pub fn application_reset(address: u8, subcode: Option<u8>) -> Request {
333 let data = subcode.map(|s| [s]);
334 snd_ud(address, false, ci::APPLICATION_RESET, data.as_ref().map_or(&[][..], |d| &d[..]))
335 .unwrap_or(Request::EMPTY)
336}
337
338pub fn request_all_data(address: u8) -> Request {
340 snd_ud(address, false, ci::DATA_SEND, &[0x7F]).unwrap_or(Request::EMPTY)
341}
342
343pub fn set_baud(address: u8, baud: Baud) -> Request {
346 snd_ud(address, false, baud.ci(), &[]).unwrap_or(Request::EMPTY)
347}
348
349pub fn set_time(address: u8, time: &DateTime) -> Request {
351 let [a, b, c, d] = time.to_type_f();
352 snd_ud(address, false, ci::DATA_SEND, &[0x04, 0x6D, a, b, c, d]).unwrap_or(Request::EMPTY)
353}
354
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub enum Target {
358 Primary(u8),
360 Secondary(SecondaryAddress),
362}
363
364#[derive(Clone, Debug)]
366#[allow(clippy::large_enum_variant)] pub enum Event<'a> {
368 NeedMore,
371 Telegram(Application<'a>),
373 Found(Address),
375 Ambiguous(SecondaryAddress),
378 Acknowledged,
380 Retrying,
382 NoReply,
384 Invalid(Error),
386}
387
388#[derive(Clone, Copy, Debug, PartialEq, Eq)]
389enum ReadState {
390 Reset,
391 Select,
392 Read,
393 Deselect,
394 Done,
395 Failed,
396}
397
398#[derive(Clone, Debug)]
403pub struct Readout {
404 target: Target,
405 state: ReadState,
406 fcb: bool,
407 tries: u8,
408 retries: u8,
409 telegrams: u8,
410 max_telegrams: u8,
411}
412
413impl Readout {
414 pub const fn new(target: Target) -> Self {
416 let state = ReadState::Reset;
419 let _ = target;
420 Self { target, state, fcb: true, tries: 0, retries: RETRIES, telegrams: 0, max_telegrams: 16 }
421 }
422
423 #[must_use]
425 pub const fn retries(mut self, retries: u8) -> Self {
426 self.retries = retries;
427 self
428 }
429
430 #[must_use]
432 pub const fn max_telegrams(mut self, max: u8) -> Self {
433 self.max_telegrams = max;
434 self
435 }
436
437 const fn address(&self) -> u8 {
438 match self.target {
439 Target::Primary(a) => a,
440 Target::Secondary(_) => NETWORK_LAYER,
441 }
442 }
443
444 pub fn next_request(&mut self) -> Option<Request> {
446 Some(match (self.state, self.target) {
447 (ReadState::Reset, _) => link_reset(self.address()),
449 (ReadState::Select, Target::Secondary(s)) => select(&s),
450 (ReadState::Read, _) => {
451 Request::from_frame(&wired::req_ud2(self.address(), self.fcb), timeout_for(0)).ok()?
452 }
453 (ReadState::Deselect, _) => deselect(),
454 _ => return None,
455 })
456 }
457
458 pub const fn is_complete(&self) -> bool {
460 matches!(self.state, ReadState::Done)
461 }
462
463 pub const fn telegrams(&self) -> u8 {
465 self.telegrams
466 }
467
468 fn advance(&mut self, next: ReadState) {
469 self.state = next;
470 self.tries = 0;
471 }
472
473 fn after_read(&self) -> ReadState {
474 match self.target {
475 Target::Primary(_) => ReadState::Done,
476 Target::Secondary(_) => ReadState::Deselect,
477 }
478 }
479
480 pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
483 let _ = received;
484 if let (ReadState::Reset, Target::Secondary(_)) = (self.state, self.target) {
485 self.advance(ReadState::Select);
487 return Event::NoReply;
488 }
489 if self.state == ReadState::Deselect {
490 self.advance(ReadState::Done);
492 return Event::NoReply;
493 }
494 if self.tries < self.retries {
495 self.tries += 1;
496 Event::Retrying
497 } else {
498 self.state = ReadState::Failed;
499 Event::NoReply
500 }
501 }
502
503 pub fn reply<'a>(&mut self, bytes: &'a [u8]) -> Event<'a> {
505 let frame = match Frame::parse(bytes) {
506 Ok(None) => return Event::NeedMore,
507 Ok(Some((frame, _))) => frame,
508 Err(_) => return self.timeout(bytes),
509 };
510 match (self.state, frame) {
511 (ReadState::Reset, Frame::Ack) => {
512 self.fcb = true;
514 let next = match self.target {
515 Target::Primary(_) => ReadState::Read,
516 Target::Secondary(_) => ReadState::Select,
517 };
518 self.advance(next);
519 Event::Acknowledged
520 }
521 (ReadState::Select, Frame::Ack) => {
522 self.fcb = true;
523 self.advance(ReadState::Read);
524 Event::Acknowledged
525 }
526 (ReadState::Deselect, _) => {
527 self.advance(ReadState::Done);
528 Event::Acknowledged
529 }
530 (ReadState::Read, Frame::Ack) => {
532 self.advance(self.after_read());
533 Event::Acknowledged
534 }
535 (ReadState::Read, Frame::Long { ci, data, .. }) => match Application::parse(ci, data) {
536 Ok(app) => {
537 self.telegrams = self.telegrams.saturating_add(1);
538 let more =
539 app.records().is_some_and(|r| more_follows(r)) && self.telegrams < self.max_telegrams;
540 self.fcb = !self.fcb;
541 let next = if more { ReadState::Read } else { self.after_read() };
542 self.advance(next);
543 Event::Telegram(app)
544 }
545 Err(e) => {
546 self.advance(self.after_read());
547 Event::Invalid(e)
548 }
549 },
550 _ => self.timeout(bytes),
551 }
552 }
553}
554
555fn more_follows(mut records: crate::Records<'_>) -> bool {
557 for _ in records.by_ref() {}
558 records.more_follows()
559}
560
561#[derive(Clone, Debug)]
569pub struct Search {
570 prefix: [u8; 8],
571 depth: u8,
572 reading: bool,
573 done: bool,
574 tries: u8,
575 retries: u8,
576 selections: u32,
577 max_selections: u32,
578 exhausted: bool,
579}
580
581impl Default for Search {
582 fn default() -> Self {
583 Self::new()
584 }
585}
586
587impl Search {
588 pub const fn new() -> Self {
590 Self {
591 prefix: [0; 8],
592 depth: 1,
593 reading: false,
594 done: false,
595 tries: 0,
596 retries: RETRIES,
597 selections: 0,
598 max_selections: 20_000,
599 exhausted: false,
600 }
601 }
602
603 #[must_use]
607 pub const fn max_selections(mut self, max: u32) -> Self {
608 self.max_selections = max;
609 self
610 }
611
612 pub const fn is_complete(&self) -> bool {
615 self.done && !self.exhausted
616 }
617
618 pub fn probe(&self) -> SecondaryAddress {
620 let mut s = SecondaryAddress::ANY;
621 for (slot, digit) in s.digits.iter_mut().zip(self.prefix).take(usize::from(self.depth)) {
622 *slot = Some(digit);
623 }
624 s
625 }
626
627 pub const fn selections(&self) -> u32 {
629 self.selections
630 }
631
632 pub fn next_request(&mut self) -> Option<Request> {
634 if self.done {
635 return None;
636 }
637 if self.reading {
638 return Request::from_frame(&wired::req_ud2(NETWORK_LAYER, true), timeout_for(0)).ok();
639 }
640 if self.tries == 0 {
641 if self.selections >= self.max_selections {
642 self.done = true;
643 self.exhausted = true;
644 return None;
645 }
646 self.selections = self.selections.saturating_add(1);
647 }
648 Some(select(&self.probe()))
649 }
650
651 fn next_sibling(&mut self) {
653 self.tries = 0;
654 self.reading = false;
655 loop {
656 let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) else {
657 self.done = true;
658 return;
659 };
660 if *d < 9 {
661 *d += 1;
662 return;
663 }
664 *d = 0;
665 if self.depth == 1 {
666 self.done = true;
667 return;
668 }
669 self.depth -= 1;
670 }
671 }
672
673 pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
676 if !received.is_empty() {
677 return self.collision();
678 }
679 if self.tries < self.retries {
680 self.tries += 1;
681 return Event::Retrying;
682 }
683 self.next_sibling();
685 Event::NoReply
686 }
687
688 fn collision(&mut self) -> Event<'static> {
690 self.reading = false;
691 self.tries = 0;
692 if self.depth >= 8 {
693 let probe = self.probe();
695 self.next_sibling();
696 return Event::Ambiguous(probe);
697 }
698 self.depth += 1;
699 if let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) {
700 *d = 0;
701 }
702 Event::Retrying
703 }
704
705 pub fn reply(&mut self, bytes: &[u8]) -> Event<'static> {
708 match Frame::parse(bytes) {
709 Ok(None) => Event::NeedMore,
710 Ok(Some((_, used))) if used < bytes.len() => self.collision(),
712 Ok(Some((Frame::Ack, _))) if !self.reading => {
713 self.reading = true;
714 self.tries = 0;
715 Event::Acknowledged
716 }
717 Ok(Some((Frame::Long { ci, data, .. }, _))) if self.reading => {
718 let found = Application::parse(ci, data).ok().and_then(|a| a.meter());
719 self.next_sibling();
720 found.map_or(Event::NoReply, Event::Found)
721 }
722 _ => self.collision(),
724 }
725 }
726}