1use core::fmt;
37
38use crate::crc::crc16_x25;
39use crate::{Error, Result};
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub enum Stick {
44 Im871a,
46 Iu891a,
48 Amb8465,
50}
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub enum LinkMode {
56 S1,
58 T1,
60 C1,
62 C1T1,
64}
65
66impl fmt::Display for LinkMode {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.write_str(match self {
69 Self::S1 => "S1",
70 Self::T1 => "T1",
71 Self::C1 => "C1",
72 Self::C1T1 => "C1+T1",
73 })
74 }
75}
76
77#[derive(Clone, Copy, PartialEq, Eq)]
79pub struct Command {
80 bytes: [u8; 32],
81 len: u8,
82}
83
84impl Command {
85 pub fn bytes(&self) -> &[u8] {
87 self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
88 }
89
90 fn new() -> Self {
91 Self { bytes: [0; 32], len: 0 }
92 }
93
94 fn push(&mut self, b: u8) {
95 if let Some(slot) = self.bytes.get_mut(usize::from(self.len)) {
96 *slot = b;
97 self.len += 1;
98 }
99 }
100
101 fn imst(endpoint: u8, msg: u8, payload: &[u8]) -> Self {
103 let mut c = Self::new();
104 c.push(0xA5);
105 c.push(0x80 | endpoint);
106 c.push(msg);
107 c.push(u8::try_from(payload.len()).unwrap_or(0));
108 for &b in payload {
109 c.push(b);
110 }
111 let [lo, hi] = crc16_x25(c.bytes().get(1..).unwrap_or(&[])).to_le_bytes();
112 c.push(lo);
113 c.push(hi);
114 c
115 }
116
117 fn slip(sap: u8, msg: u8, payload: &[u8]) -> Self {
119 let mut body = [0u8; 16];
120 let mut n = 0usize;
121 for &b in [sap, msg].iter().chain(payload) {
122 if let Some(slot) = body.get_mut(n) {
123 *slot = b;
124 n += 1;
125 }
126 }
127 let [lo, hi] = crc16_x25(body.get(..n).unwrap_or(&[])).to_le_bytes();
128 let mut c = Self::new();
129 c.push(SLIP_END);
130 for &b in body.get(..n).unwrap_or(&[]).iter().chain(&[lo, hi]) {
131 match b {
132 SLIP_END => [SLIP_ESC, 0xDC].iter().for_each(|&e| c.push(e)),
133 SLIP_ESC => [SLIP_ESC, 0xDD].iter().for_each(|&e| c.push(e)),
134 b => c.push(b),
135 }
136 }
137 c.push(SLIP_END);
138 c
139 }
140
141 fn amber(cmd: u8, payload: &[u8]) -> Self {
143 let mut c = Self::new();
144 c.push(0xFF);
145 c.push(cmd);
146 c.push(u8::try_from(payload.len()).unwrap_or(0));
147 for &b in payload {
148 c.push(b);
149 }
150 let cs = c.bytes().iter().fold(0u8, |x, &b| x ^ b);
151 c.push(cs);
152 c
153 }
154}
155
156impl fmt::Debug for Command {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 write!(f, "Command({:02X?})", self.bytes())
159 }
160}
161
162const SLIP_END: u8 = 0xC0;
163const SLIP_ESC: u8 = 0xDB;
164
165impl Stick {
166 pub const fn baud(self) -> u32 {
168 match self {
169 Self::Im871a => 57_600,
170 Self::Iu891a => 115_200,
171 Self::Amb8465 => 9_600,
172 }
173 }
174
175 pub fn listen(self, mode: LinkMode) -> Option<Command> {
184 Some(match self {
185 Self::Im871a => {
186 let code = match mode {
187 LinkMode::S1 => 0x00,
188 LinkMode::T1 => 0x03,
189 LinkMode::C1 => 0x07,
190 LinkMode::C1T1 => 0x0A,
191 };
192 Command::imst(0x01, 0x03, &[0x00, 0x02, code, 0x10, 0x01])
194 }
195 Self::Iu891a => {
196 let code = match mode {
197 LinkMode::S1 => 0x01,
198 LinkMode::T1 => 0x02,
199 LinkMode::C1 => 0x05,
200 LinkMode::C1T1 => 0x03,
201 };
202 let [l0, l1] = 50u16.to_le_bytes();
205 let [r0, r1, r2, r3] = 60_000u32.to_le_bytes();
206 Command::slip(0x09, 0x03, &[code, 0x0A, 0x00, 0x00, 0x00, l0, l1, r0, r1, r2, r3])
207 }
208 Self::Amb8465 => {
209 let code = match mode {
210 LinkMode::S1 => return None,
211 LinkMode::T1 => 0x08,
212 LinkMode::C1 => 0x0E,
213 LinkMode::C1T1 => 0x09,
214 };
215 Command::amber(0x04, &[code])
216 }
217 })
218 }
219
220 pub fn ping(self) -> Command {
223 match self {
224 Self::Im871a => Command::imst(0x01, 0x01, &[]),
225 Self::Iu891a => Command::slip(0x01, 0x01, &[]),
226 Self::Amb8465 => Command::amber(0x0C, &[]),
227 }
228 }
229
230 pub fn setup(self) -> impl Iterator<Item = Command> {
235 let amber = matches!(self, Self::Amb8465);
236 [
237 Command::amber(0x09, &[0x05, 0x01, 0x01]),
238 Command::amber(0x09, &[0x45, 0x01, 0x01]),
239 Command::amber(0x05, &[]),
240 ]
241 .into_iter()
242 .filter(move |_| amber)
243 }
244}
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248pub struct Received<'a> {
249 pub frame: &'a [u8],
251 pub rssi_dbm: Option<i16>,
254 pub rssi_raw: Option<u8>,
256 pub timestamp: Option<u32>,
258 pub mode: Option<(LinkMode, bool)>,
260 pub decrypted_by_stick: bool,
262}
263
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum Message<'a> {
267 Telegram(Received<'a>),
269 Response {
273 group: u8,
275 id: u8,
277 payload: &'a [u8],
279 },
280}
281
282const CAPACITY: usize = 640;
283
284#[derive(Clone)]
290pub struct Receiver {
291 stick: Stick,
292 buf: [u8; CAPACITY],
293 len: usize,
294 used: usize,
296}
297
298#[allow(clippy::missing_fields_in_debug)] impl fmt::Debug for Receiver {
300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301 f.debug_struct("Receiver")
302 .field("stick", &self.stick)
303 .field("buffered", &(self.len - self.used))
304 .finish()
305 }
306}
307
308impl Receiver {
309 pub const fn new(stick: Stick) -> Self {
311 Self { stick, buf: [0; CAPACITY], len: 0, used: 0 }
312 }
313
314 pub fn extend(&mut self, bytes: &[u8]) -> usize {
318 self.compact();
319 let free = CAPACITY - self.len;
320 let n = bytes.len().min(free);
321 if let (Some(dst), Some(src)) = (self.buf.get_mut(self.len..self.len + n), bytes.get(..n)) {
322 dst.copy_from_slice(src);
323 self.len += n;
324 }
325 n
326 }
327
328 fn data(&self) -> &[u8] {
330 self.buf.get(..self.len).unwrap_or(&[])
331 }
332
333 fn compact(&mut self) {
334 if self.used > 0 {
335 self.buf.copy_within(self.used..self.len, 0);
336 self.len -= self.used;
337 self.used = 0;
338 }
339 }
340
341 pub fn next_message(&mut self) -> Option<Result<Message<'_>>> {
344 self.compact();
345 let r = match self.stick {
347 Stick::Im871a => self.imst(),
348 Stick::Iu891a => self.gateway(),
349 Stick::Amb8465 => self.amber(),
350 };
351 match r {
352 Step::Wait if self.len == CAPACITY => {
353 self.used = self.len;
354 Some(Err(Error::InvalidLength))
355 }
356 Step::Wait => None,
357 Step::Skip(n, e) => {
358 self.used = n.max(1).min(self.len);
359 Some(Err(e))
360 }
361 Step::Done(n, kind) => {
362 self.used = n;
363 Some(Ok(self.message(kind)))
364 }
365 }
366 }
367
368 fn seek(&mut self, start: u8) -> bool {
370 let skip = self.data().get(..).and_then(|b| b.iter().position(|&x| x == start)).unwrap_or(self.len);
371 if skip > 0 {
372 self.used = skip;
373 self.compact();
374 }
375 self.len > 0
376 }
377
378 fn imst(&mut self) -> Step {
379 if !self.seek(0xA5) {
380 return Step::Wait;
381 }
382 let Some(&[_, ctrl, msg, len]) = self.data().get(..4).and_then(|b| <&[u8; 4]>::try_from(b).ok())
383 else {
384 return Step::Wait;
385 };
386 if ctrl & 0x10 != 0 || ctrl.trailing_zeros() >= 4 {
387 return Step::Skip(1, Error::InvalidHeader);
388 }
389 let (ts, rssi, crc) = (ctrl & 0x20 != 0, ctrl & 0x40 != 0, ctrl & 0x80 != 0);
390 let body = 4 + usize::from(len);
391 let total = body + if ts { 4 } else { 0 } + usize::from(rssi) + if crc { 2 } else { 0 };
392 let Some(frame) = self.data().get(..total) else { return Step::Wait };
393 if crc {
394 let (data, fcs) = frame.split_at(total - 2);
395 let computed = crc16_x25(data.get(1..).unwrap_or(&[]));
396 let found = fcs.first().zip(fcs.get(1)).map_or(0, |(&lo, &hi)| u16::from_le_bytes([lo, hi]));
397 if computed != found {
398 return Step::Skip(1, Error::Crc { block: 0, computed, found });
399 }
400 }
401 let timestamp = ts.then(|| self.u32_le(body)).flatten();
402 let raw = rssi.then(|| self.data().get(body + if ts { 4 } else { 0 }).copied()).flatten();
403 if ctrl & 0x0F == 0x02 && msg == 0x03 {
404 let rssi_dbm = raw.map(|r| i16::try_from((8 * i32::from(r) - 1900) / 15).unwrap_or(i16::MIN));
406 let t = Kind::Telegram {
407 at: 3,
408 len: 1 + usize::from(len),
409 rssi_dbm,
410 raw,
411 timestamp,
412 mode: None,
413 decrypted: false,
414 };
415 return Step::Done(total, t);
416 }
417 Step::Done(total, Kind::Response { group: ctrl & 0x0F, id: msg, at: 4, len: usize::from(len) })
418 }
419
420 fn gateway(&mut self) -> Step {
421 while self.data().get(..).and_then(<[u8]>::first) == Some(&SLIP_END) {
423 self.used = 1;
424 self.compact();
425 }
426 let Some(end) = self.data().get(..).and_then(|b| b.iter().position(|&x| x == SLIP_END)) else {
427 return Step::Wait;
428 };
429 let mut w = 0usize;
431 let mut r = 0usize;
432 while r < end {
433 let b = self.data().get(r).copied().unwrap_or(0);
434 let out = if b == SLIP_ESC {
435 r += 1;
436 match self.data().get(r) {
437 Some(0xDC) => SLIP_END,
438 Some(0xDD) => SLIP_ESC,
439 _ => return Step::Skip(end, Error::InvalidHeader),
440 }
441 } else {
442 b
443 };
444 if let Some(slot) = self.buf.get_mut(w) {
445 *slot = out;
446 }
447 w += 1;
448 r += 1;
449 }
450 if w < 4 {
451 return Step::Skip(end, Error::UnexpectedEnd);
452 }
453 let Some(body) = self.data().get(..w) else { return Step::Skip(end, Error::UnexpectedEnd) };
454 let (data, fcs) = body.split_at(w - 2);
455 let computed = crc16_x25(data);
456 let found = fcs.first().zip(fcs.get(1)).map_or(0, |(&lo, &hi)| u16::from_le_bytes([lo, hi]));
457 if computed != found {
458 return Step::Skip(end, Error::Crc { block: 0, computed, found });
459 }
460 let (sap, msg) = (data.first().copied().unwrap_or(0), data.get(1).copied().unwrap_or(0));
461 let payload = w - 4;
462 if sap == 0x09 && msg == 0x20 && payload > 8 {
463 let timestamp = self.u32_le(2);
466 let decrypted = self.data().get(6) == Some(&1);
467 let info = self.data().get(8).copied().unwrap_or(0);
468 let raw = self.data().get(9).copied();
469 let mode = match info {
470 1 => Some((LinkMode::S1, false)),
471 2 | 6 | 7 => Some((LinkMode::T1, false)),
472 4 | 5 | 8 => Some((LinkMode::C1, false)),
473 20 | 21 | 24 => Some((LinkMode::C1, true)),
474 _ => None,
475 };
476 let rssi_dbm = raw.map(|r| i16::from(i8::from_le_bytes([r])));
477 let t = Kind::Telegram { at: 10, len: payload - 8, rssi_dbm, raw, timestamp, mode, decrypted };
478 return Step::Done(end, t);
479 }
480 Step::Done(end, Kind::Response { group: sap, id: msg, at: 2, len: payload })
481 }
482
483 fn amber(&mut self) -> Step {
484 if !self.seek(0xFF) {
485 return Step::Wait;
486 }
487 let Some(&[_, cmd, len]) = self.data().get(..3).and_then(|b| <&[u8; 3]>::try_from(b).ok()) else {
488 return Step::Wait;
489 };
490 if cmd != 0x03 && cmd & 0x80 == 0 {
492 return Step::Skip(1, Error::InvalidHeader);
493 }
494 let total = 4 + usize::from(len);
495 let Some(frame) = self.data().get(..total) else { return Step::Wait };
496 let (data, cs) = frame.split_at(total - 1);
497 let computed = data.iter().fold(0u8, |x, &b| x ^ b);
498 let found = cs.first().copied().unwrap_or(0);
499 if computed != found {
500 return Step::Skip(1, Error::Checksum { computed, found });
501 }
502 if cmd == 0x03 && len >= 2 {
503 let raw = self.data().get(total - 2).copied();
505 if let Some(l) = self.buf.get_mut(2) {
506 *l = len - 1;
507 }
508 let rssi_dbm = raw.map(|r| i16::from(i8::from_le_bytes([r])) / 2 - 74);
509 let t = Kind::Telegram {
510 at: 2,
511 len: usize::from(len),
512 rssi_dbm,
513 raw,
514 timestamp: None,
515 mode: None,
516 decrypted: false,
517 };
518 return Step::Done(total, t);
519 }
520 Step::Done(total, Kind::Response { group: 0, id: cmd, at: 3, len: usize::from(len) })
521 }
522
523 fn u32_le(&self, at: usize) -> Option<u32> {
524 let b = self.data().get(at..at + 4)?;
525 Some(u32::from_le_bytes(b.try_into().ok()?))
526 }
527
528 fn message(&self, kind: Kind) -> Message<'_> {
529 match kind {
530 Kind::Telegram { at, len, rssi_dbm, raw, timestamp, mode, decrypted } => {
531 Message::Telegram(Received {
532 frame: self.data().get(at..at + len).unwrap_or(&[]),
533 rssi_dbm,
534 rssi_raw: raw,
535 timestamp,
536 mode,
537 decrypted_by_stick: decrypted,
538 })
539 }
540 Kind::Response { group, id, at, len } => {
541 Message::Response { group, id, payload: self.data().get(at..at + len).unwrap_or(&[]) }
542 }
543 }
544 }
545}
546
547enum Step {
548 Wait,
549 Skip(usize, Error),
550 Done(usize, Kind),
551}
552
553#[derive(Clone, Copy)]
554enum Kind {
555 Telegram {
556 at: usize,
557 len: usize,
558 rssi_dbm: Option<i16>,
559 raw: Option<u8>,
560 timestamp: Option<u32>,
561 mode: Option<(LinkMode, bool)>,
562 decrypted: bool,
563 },
564 Response {
565 group: u8,
566 id: u8,
567 at: usize,
568 len: usize,
569 },
570}