use core::fmt;
use crate::crc::crc16_x25;
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Stick {
Im871a,
Iu891a,
Amb8465,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LinkMode {
S1,
T1,
C1,
C1T1,
}
impl fmt::Display for LinkMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::S1 => "S1",
Self::T1 => "T1",
Self::C1 => "C1",
Self::C1T1 => "C1+T1",
})
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Command {
bytes: [u8; 32],
len: u8,
}
impl Command {
pub fn bytes(&self) -> &[u8] {
self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
}
fn new() -> Self {
Self { bytes: [0; 32], len: 0 }
}
fn push(&mut self, b: u8) {
if let Some(slot) = self.bytes.get_mut(usize::from(self.len)) {
*slot = b;
self.len += 1;
}
}
fn imst(endpoint: u8, msg: u8, payload: &[u8]) -> Self {
let mut c = Self::new();
c.push(0xA5);
c.push(0x80 | endpoint);
c.push(msg);
c.push(u8::try_from(payload.len()).unwrap_or(0));
for &b in payload {
c.push(b);
}
let [lo, hi] = crc16_x25(c.bytes().get(1..).unwrap_or(&[])).to_le_bytes();
c.push(lo);
c.push(hi);
c
}
fn slip(sap: u8, msg: u8, payload: &[u8]) -> Self {
let mut body = [0u8; 16];
let mut n = 0usize;
for &b in [sap, msg].iter().chain(payload) {
if let Some(slot) = body.get_mut(n) {
*slot = b;
n += 1;
}
}
let [lo, hi] = crc16_x25(body.get(..n).unwrap_or(&[])).to_le_bytes();
let mut c = Self::new();
c.push(SLIP_END);
for &b in body.get(..n).unwrap_or(&[]).iter().chain(&[lo, hi]) {
match b {
SLIP_END => [SLIP_ESC, 0xDC].iter().for_each(|&e| c.push(e)),
SLIP_ESC => [SLIP_ESC, 0xDD].iter().for_each(|&e| c.push(e)),
b => c.push(b),
}
}
c.push(SLIP_END);
c
}
fn amber(cmd: u8, payload: &[u8]) -> Self {
let mut c = Self::new();
c.push(0xFF);
c.push(cmd);
c.push(u8::try_from(payload.len()).unwrap_or(0));
for &b in payload {
c.push(b);
}
let cs = c.bytes().iter().fold(0u8, |x, &b| x ^ b);
c.push(cs);
c
}
}
impl fmt::Debug for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Command({:02X?})", self.bytes())
}
}
const SLIP_END: u8 = 0xC0;
const SLIP_ESC: u8 = 0xDB;
impl Stick {
pub const fn baud(self) -> u32 {
match self {
Self::Im871a => 57_600,
Self::Iu891a => 115_200,
Self::Amb8465 => 9_600,
}
}
pub fn listen(self, mode: LinkMode) -> Option<Command> {
Some(match self {
Self::Im871a => {
let code = match mode {
LinkMode::S1 => 0x00,
LinkMode::T1 => 0x03,
LinkMode::C1 => 0x07,
LinkMode::C1T1 => 0x0A,
};
Command::imst(0x01, 0x03, &[0x00, 0x02, code, 0x10, 0x01])
}
Self::Iu891a => {
let code = match mode {
LinkMode::S1 => 0x01,
LinkMode::T1 => 0x02,
LinkMode::C1 => 0x05,
LinkMode::C1T1 => 0x03,
};
let [l0, l1] = 50u16.to_le_bytes();
let [r0, r1, r2, r3] = 60_000u32.to_le_bytes();
Command::slip(0x09, 0x03, &[code, 0x0A, 0x00, 0x00, 0x00, l0, l1, r0, r1, r2, r3])
}
Self::Amb8465 => {
let code = match mode {
LinkMode::S1 => return None,
LinkMode::T1 => 0x08,
LinkMode::C1 => 0x0E,
LinkMode::C1T1 => 0x09,
};
Command::amber(0x04, &[code])
}
})
}
pub fn ping(self) -> Command {
match self {
Self::Im871a => Command::imst(0x01, 0x01, &[]),
Self::Iu891a => Command::slip(0x01, 0x01, &[]),
Self::Amb8465 => Command::amber(0x0C, &[]),
}
}
pub fn setup(self) -> impl Iterator<Item = Command> {
let amber = matches!(self, Self::Amb8465);
[
Command::amber(0x09, &[0x05, 0x01, 0x01]),
Command::amber(0x09, &[0x45, 0x01, 0x01]),
Command::amber(0x05, &[]),
]
.into_iter()
.filter(move |_| amber)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Received<'a> {
pub frame: &'a [u8],
pub rssi_dbm: Option<i16>,
pub rssi_raw: Option<u8>,
pub timestamp: Option<u32>,
pub mode: Option<(LinkMode, bool)>,
pub decrypted_by_stick: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Message<'a> {
Telegram(Received<'a>),
Response {
group: u8,
id: u8,
payload: &'a [u8],
},
}
const CAPACITY: usize = 640;
#[derive(Clone)]
pub struct Receiver {
stick: Stick,
buf: [u8; CAPACITY],
len: usize,
used: usize,
}
#[allow(clippy::missing_fields_in_debug)] impl fmt::Debug for Receiver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Receiver")
.field("stick", &self.stick)
.field("buffered", &(self.len - self.used))
.finish()
}
}
impl Receiver {
pub const fn new(stick: Stick) -> Self {
Self { stick, buf: [0; CAPACITY], len: 0, used: 0 }
}
pub fn extend(&mut self, bytes: &[u8]) -> usize {
self.compact();
let free = CAPACITY - self.len;
let n = bytes.len().min(free);
if let (Some(dst), Some(src)) = (self.buf.get_mut(self.len..self.len + n), bytes.get(..n)) {
dst.copy_from_slice(src);
self.len += n;
}
n
}
fn data(&self) -> &[u8] {
self.buf.get(..self.len).unwrap_or(&[])
}
fn compact(&mut self) {
if self.used > 0 {
self.buf.copy_within(self.used..self.len, 0);
self.len -= self.used;
self.used = 0;
}
}
pub fn next_message(&mut self) -> Option<Result<Message<'_>>> {
self.compact();
let r = match self.stick {
Stick::Im871a => self.imst(),
Stick::Iu891a => self.gateway(),
Stick::Amb8465 => self.amber(),
};
match r {
Step::Wait if self.len == CAPACITY => {
self.used = self.len;
Some(Err(Error::InvalidLength))
}
Step::Wait => None,
Step::Skip(n, e) => {
self.used = n.max(1).min(self.len);
Some(Err(e))
}
Step::Done(n, kind) => {
self.used = n;
Some(Ok(self.message(kind)))
}
}
}
fn seek(&mut self, start: u8) -> bool {
let skip = self.data().get(..).and_then(|b| b.iter().position(|&x| x == start)).unwrap_or(self.len);
if skip > 0 {
self.used = skip;
self.compact();
}
self.len > 0
}
fn imst(&mut self) -> Step {
if !self.seek(0xA5) {
return Step::Wait;
}
let Some(&[_, ctrl, msg, len]) = self.data().get(..4).and_then(|b| <&[u8; 4]>::try_from(b).ok())
else {
return Step::Wait;
};
if ctrl & 0x10 != 0 || ctrl.trailing_zeros() >= 4 {
return Step::Skip(1, Error::InvalidHeader);
}
let (ts, rssi, crc) = (ctrl & 0x20 != 0, ctrl & 0x40 != 0, ctrl & 0x80 != 0);
let body = 4 + usize::from(len);
let total = body + if ts { 4 } else { 0 } + usize::from(rssi) + if crc { 2 } else { 0 };
let Some(frame) = self.data().get(..total) else { return Step::Wait };
if crc {
let (data, fcs) = frame.split_at(total - 2);
let computed = crc16_x25(data.get(1..).unwrap_or(&[]));
let found = fcs.first().zip(fcs.get(1)).map_or(0, |(&lo, &hi)| u16::from_le_bytes([lo, hi]));
if computed != found {
return Step::Skip(1, Error::Crc { block: 0, computed, found });
}
}
let timestamp = ts.then(|| self.u32_le(body)).flatten();
let raw = rssi.then(|| self.data().get(body + if ts { 4 } else { 0 }).copied()).flatten();
if ctrl & 0x0F == 0x02 && msg == 0x03 {
let rssi_dbm = raw.map(|r| i16::try_from((8 * i32::from(r) - 1900) / 15).unwrap_or(i16::MIN));
let t = Kind::Telegram {
at: 3,
len: 1 + usize::from(len),
rssi_dbm,
raw,
timestamp,
mode: None,
decrypted: false,
};
return Step::Done(total, t);
}
Step::Done(total, Kind::Response { group: ctrl & 0x0F, id: msg, at: 4, len: usize::from(len) })
}
fn gateway(&mut self) -> Step {
while self.data().get(..).and_then(<[u8]>::first) == Some(&SLIP_END) {
self.used = 1;
self.compact();
}
let Some(end) = self.data().get(..).and_then(|b| b.iter().position(|&x| x == SLIP_END)) else {
return Step::Wait;
};
let mut w = 0usize;
let mut r = 0usize;
while r < end {
let b = self.data().get(r).copied().unwrap_or(0);
let out = if b == SLIP_ESC {
r += 1;
match self.data().get(r) {
Some(0xDC) => SLIP_END,
Some(0xDD) => SLIP_ESC,
_ => return Step::Skip(end, Error::InvalidHeader),
}
} else {
b
};
if let Some(slot) = self.buf.get_mut(w) {
*slot = out;
}
w += 1;
r += 1;
}
if w < 4 {
return Step::Skip(end, Error::UnexpectedEnd);
}
let Some(body) = self.data().get(..w) else { return Step::Skip(end, Error::UnexpectedEnd) };
let (data, fcs) = body.split_at(w - 2);
let computed = crc16_x25(data);
let found = fcs.first().zip(fcs.get(1)).map_or(0, |(&lo, &hi)| u16::from_le_bytes([lo, hi]));
if computed != found {
return Step::Skip(end, Error::Crc { block: 0, computed, found });
}
let (sap, msg) = (data.first().copied().unwrap_or(0), data.get(1).copied().unwrap_or(0));
let payload = w - 4;
if sap == 0x09 && msg == 0x20 && payload > 8 {
let timestamp = self.u32_le(2);
let decrypted = self.data().get(6) == Some(&1);
let info = self.data().get(8).copied().unwrap_or(0);
let raw = self.data().get(9).copied();
let mode = match info {
1 => Some((LinkMode::S1, false)),
2 | 6 | 7 => Some((LinkMode::T1, false)),
4 | 5 | 8 => Some((LinkMode::C1, false)),
20 | 21 | 24 => Some((LinkMode::C1, true)),
_ => None,
};
let rssi_dbm = raw.map(|r| i16::from(i8::from_le_bytes([r])));
let t = Kind::Telegram { at: 10, len: payload - 8, rssi_dbm, raw, timestamp, mode, decrypted };
return Step::Done(end, t);
}
Step::Done(end, Kind::Response { group: sap, id: msg, at: 2, len: payload })
}
fn amber(&mut self) -> Step {
if !self.seek(0xFF) {
return Step::Wait;
}
let Some(&[_, cmd, len]) = self.data().get(..3).and_then(|b| <&[u8; 3]>::try_from(b).ok()) else {
return Step::Wait;
};
if cmd != 0x03 && cmd & 0x80 == 0 {
return Step::Skip(1, Error::InvalidHeader);
}
let total = 4 + usize::from(len);
let Some(frame) = self.data().get(..total) else { return Step::Wait };
let (data, cs) = frame.split_at(total - 1);
let computed = data.iter().fold(0u8, |x, &b| x ^ b);
let found = cs.first().copied().unwrap_or(0);
if computed != found {
return Step::Skip(1, Error::Checksum { computed, found });
}
if cmd == 0x03 && len >= 2 {
let raw = self.data().get(total - 2).copied();
if let Some(l) = self.buf.get_mut(2) {
*l = len - 1;
}
let rssi_dbm = raw.map(|r| i16::from(i8::from_le_bytes([r])) / 2 - 74);
let t = Kind::Telegram {
at: 2,
len: usize::from(len),
rssi_dbm,
raw,
timestamp: None,
mode: None,
decrypted: false,
};
return Step::Done(total, t);
}
Step::Done(total, Kind::Response { group: 0, id: cmd, at: 3, len: usize::from(len) })
}
fn u32_le(&self, at: usize) -> Option<u32> {
let b = self.data().get(at..at + 4)?;
Some(u32::from_le_bytes(b.try_into().ok()?))
}
fn message(&self, kind: Kind) -> Message<'_> {
match kind {
Kind::Telegram { at, len, rssi_dbm, raw, timestamp, mode, decrypted } => {
Message::Telegram(Received {
frame: self.data().get(at..at + len).unwrap_or(&[]),
rssi_dbm,
rssi_raw: raw,
timestamp,
mode,
decrypted_by_stick: decrypted,
})
}
Kind::Response { group, id, at, len } => {
Message::Response { group, id, payload: self.data().get(at..at + len).unwrap_or(&[]) }
}
}
}
}
enum Step {
Wait,
Skip(usize, Error),
Done(usize, Kind),
}
#[derive(Clone, Copy)]
enum Kind {
Telegram {
at: usize,
len: usize,
rssi_dbm: Option<i16>,
raw: Option<u8>,
timestamp: Option<u32>,
mode: Option<(LinkMode, bool)>,
decrypted: bool,
},
Response {
group: u8,
id: u8,
at: usize,
len: usize,
},
}