1pub use crate::app::Address;
25use crate::app::Application;
26use crate::crc::crc16;
27use crate::{Error, Result};
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum Format {
32 A,
34 B,
36 Stripped,
40}
41
42pub mod control {
44 pub const SND_NR: u8 = 0x44;
46 pub const SND_IR: u8 = 0x46;
48 pub const ACC_NR: u8 = 0x47;
50 pub const RSP_UD: u8 = 0x08;
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct Frame<'o> {
57 pub c: u8,
59 pub address: Address,
61 pub ci: u8,
63 pub payload: &'o [u8],
65}
66
67impl<'o> Frame<'o> {
68 pub fn application(&self) -> Result<Application<'o>> {
71 Application::parse_with_link(self.ci, self.payload, Some(self.address))
72 }
73}
74
75#[cfg(feature = "oms")]
78#[derive(Clone, Debug)]
79pub struct Telegram<'b> {
80 pub c: u8,
82 pub address: Address,
84 pub app: Application<'b>,
86}
87
88#[cfg(feature = "oms")]
100pub fn open<'b, K: crate::oms::Keys + ?Sized>(
101 raw: &[u8],
102 format: Format,
103 keys: &K,
104 buf: &'b mut [u8],
105) -> Result<Option<(Telegram<'b>, usize)>> {
106 let half = buf.len() / 2;
107 let (frame_buf, plain_buf) = buf.split_at_mut(half);
108 let Some((frame, used)) = decode(raw, format, &mut *frame_buf)? else { return Ok(None) };
109 let (c, address) = (frame.c, frame.address);
110 let app = frame.application()?;
111 let telegram = |app| Ok(Some((Telegram { c, address, app }, used)));
112 let plain = |frame_buf: &'b mut [u8]| match decode(raw, format, frame_buf)? {
114 Some((frame, _)) => telegram(frame.application()?),
115 None => Ok(None),
116 };
117 let crate::Body::Encrypted(e) = &app.body else { return plain(frame_buf) };
118 let inner = match e.decrypt(keys, plain_buf) {
119 Err(Error::NoKey) => return plain(frame_buf),
120 other => other?,
121 };
122 let crate::Body::Encrypted(e) = &inner.body else { return telegram(inner) };
124 match e.decrypt(keys, frame_buf) {
125 Err(Error::NoKey) => telegram(inner),
126 other => telegram(other?),
127 }
128}
129
130pub fn wire_len(l: u8, format: Format) -> usize {
132 let l = usize::from(l);
133 match format {
134 Format::A => {
135 let rest = l.saturating_sub(9);
136 1 + l + 2 + 2 * rest.div_ceil(16)
137 }
138 Format::B | Format::Stripped => 1 + l,
139 }
140}
141
142pub fn decode<'o>(raw: &[u8], format: Format, out: &'o mut [u8]) -> Result<Option<(Frame<'o>, usize)>> {
147 let Some(&l) = raw.first() else { return Ok(None) };
148 if l < 10 {
149 return Err(Error::InvalidLength);
150 }
151 let total = wire_len(l, format);
152 let Some(raw) = raw.get(..total) else { return Ok(None) };
153 let len = match format {
154 Format::A => strip_a(raw, out)?,
155 Format::B => strip_b(raw, out)?,
156 Format::Stripped => copy_into(out, 0, raw)?,
157 };
158 let data = out.get(..len).ok_or(Error::OutputTooSmall)?;
159 let frame = parse_fields(data)?;
160 Ok(Some((frame, total)))
161}
162
163fn copy_into(out: &mut [u8], at: usize, bytes: &[u8]) -> Result<usize> {
164 let end = at.checked_add(bytes.len()).ok_or(Error::OutputTooSmall)?;
165 out.get_mut(at..end).ok_or(Error::OutputTooSmall)?.copy_from_slice(bytes);
166 Ok(end)
167}
168
169fn check_crc(block: usize, data: &[u8], crc: &[u8]) -> Result<()> {
170 let computed = crc16(data);
171 let found = match crc {
172 [hi, lo] => u16::from_be_bytes([*hi, *lo]),
173 _ => return Err(Error::UnexpectedEnd),
174 };
175 if computed == found { Ok(()) } else { Err(Error::Crc { block, computed, found }) }
176}
177
178fn strip_a(raw: &[u8], out: &mut [u8]) -> Result<usize> {
179 let mut pos = 0usize;
180 let mut written = 0usize;
181 let mut block = 0usize;
182 let mut size = 10usize;
183 while pos < raw.len() {
184 let data_end = (pos + size).min(raw.len().saturating_sub(2));
185 let data = raw.get(pos..data_end).ok_or(Error::UnexpectedEnd)?;
186 let crc = raw.get(data_end..data_end + 2).ok_or(Error::UnexpectedEnd)?;
187 check_crc(block, data, crc)?;
188 written = copy_into(out, written, data)?;
189 pos = data_end + 2;
190 block += 1;
191 size = 16;
192 }
193 Ok(written)
194}
195
196fn strip_b(raw: &[u8], out: &mut [u8]) -> Result<usize> {
197 if matches!(raw.len(), 129 | 130) {
199 return Err(Error::InvalidLength);
200 }
201 let first_end = raw.len().min(128);
203 let first = raw.get(..first_end.saturating_sub(2)).ok_or(Error::UnexpectedEnd)?;
204 check_crc(0, first, raw.get(first.len()..first_end).ok_or(Error::UnexpectedEnd)?)?;
205 let mut written = copy_into(out, 0, first)?;
206 if raw.len() > 128 {
207 let third = raw.get(128..raw.len() - 2).ok_or(Error::UnexpectedEnd)?;
208 check_crc(1, third, raw.get(raw.len() - 2..).ok_or(Error::UnexpectedEnd)?)?;
209 written = copy_into(out, written, third)?;
210 }
211 Ok(written)
212}
213
214fn parse_fields(data: &[u8]) -> Result<Frame<'_>> {
215 let Some((&[_l, c, m0, m1, i0, i1, i2, i3, version, medium, ci], payload)) =
216 data.split_first_chunk::<11>()
217 else {
218 return Err(Error::UnexpectedEnd);
219 };
220 Ok(Frame { c, address: Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium]), ci, payload })
221}
222
223pub fn encode(
231 format: Format,
232 c: u8,
233 address: &Address,
234 ci: u8,
235 payload: &[u8],
236 out: &mut [u8],
237) -> Result<usize> {
238 let n = payload.len().checked_add(11).ok_or(Error::InvalidLength)?;
240 let l = match format {
241 Format::A | Format::Stripped => n - 1,
242 Format::B if n <= 126 => n + 1,
244 Format::B => n + 3,
245 };
246 let l = u8::try_from(l).map_err(|_| Error::InvalidLength)?;
247 let total = wire_len(l, format);
248 let out = out.get_mut(..total).ok_or(Error::OutputTooSmall)?;
249 let mut head = [0u8; 11];
250 head[0] = l;
251 head[1] = c;
252 head[2..10].copy_from_slice(&address.to_bytes());
253 head[10] = ci;
254 match format {
255 Format::Stripped => {
256 let at = copy_into(out, 0, &head)?;
257 copy_into(out, at, payload)
258 }
259 Format::B => {
260 let at = copy_into(out, 0, &head)?;
261 let first = n.min(126);
262 let (p1, p2) = payload.split_at(first - 11);
263 let at = copy_into(out, at, p1)?;
264 let crc = crc16(out.get(..at).ok_or(Error::OutputTooSmall)?).to_be_bytes();
265 let at = copy_into(out, at, &crc)?;
266 if p2.is_empty() {
267 return Ok(at);
268 }
269 let end = copy_into(out, at, p2)?;
270 let crc = crc16(out.get(at..end).ok_or(Error::OutputTooSmall)?).to_be_bytes();
271 copy_into(out, end, &crc)
272 }
273 Format::A => {
274 let mut written = 0usize;
276 let mut block = [0u8; 16];
277 let mut in_block = 0usize;
278 let mut size = 10usize;
279 for b in head.iter().chain(payload) {
280 *block.get_mut(in_block).ok_or(Error::InvalidLength)? = *b;
281 in_block += 1;
282 if in_block == size {
283 let data = block.get(..in_block).unwrap_or(&[]);
284 written = copy_into(out, written, data)?;
285 written = copy_into(out, written, &crc16(data).to_be_bytes())?;
286 in_block = 0;
287 size = 16;
288 }
289 }
290 if in_block > 0 {
291 let data = block.get(..in_block).unwrap_or(&[]);
292 written = copy_into(out, written, data)?;
293 written = copy_into(out, written, &crc16(data).to_be_bytes())?;
294 }
295 Ok(written)
296 }
297 }
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303 use crate::app::{Manufacturer, Medium};
304
305 #[test]
306 fn format_b_lengths_without_room_for_a_third_block_are_invalid() {
307 for l in [128u8, 129] {
309 let mut raw = [0u8; 130];
310 raw[0] = l;
311 let mut out = [0u8; 300];
312 assert_eq!(
313 decode(&raw[..=usize::from(l)], Format::B, &mut out).unwrap_err(),
314 Error::InvalidLength,
315 "L {l}"
316 );
317 }
318 }
319
320 fn addr() -> Address {
321 Address {
322 manufacturer: Manufacturer::from_letters(*b"KAM").unwrap(),
323 id: [0x78, 0x56, 0x34, 0x12],
324 version: 0x1B,
325 medium: Medium::WATER,
326 }
327 }
328
329 #[test]
330 fn format_a_round_trip_for_every_length() {
331 for n in 0..60usize {
332 let payload: [u8; 60] = core::array::from_fn(|i| u8::try_from(i).unwrap() ^ 0x5A);
333 let mut wire = [0u8; 128];
334 let w = encode(Format::A, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut wire).unwrap();
335 assert_eq!(w, wire_len(wire[0], Format::A));
336 let mut out = [0u8; 128];
337 let (frame, used) = decode(&wire[..w], Format::A, &mut out).unwrap().unwrap();
338 assert_eq!(used, w);
339 assert_eq!(frame.c, control::SND_NR);
340 assert_eq!(frame.address, addr());
341 assert_eq!(frame.address.id_number(), Some(12_345_678));
342 assert_eq!(frame.ci, 0x7A);
343 assert_eq!(frame.payload, &payload[..n]);
344 }
345 }
346
347 #[test]
348 fn every_flipped_byte_is_caught() {
349 let mut wire = [0u8; 64];
350 let w = encode(
351 Format::A,
352 control::SND_NR,
353 &addr(),
354 0x7A,
355 &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
356 &mut wire,
357 )
358 .unwrap();
359 for i in 1..w {
360 let mut bad = wire;
361 bad[i] ^= 0x10;
362 let mut out = [0u8; 64];
363 assert!(decode(&bad[..w], Format::A, &mut out).is_err(), "byte {i}");
364 }
365 }
366
367 #[test]
368 fn short_input_asks_for_more() {
369 let mut wire = [0u8; 64];
370 let w = encode(Format::A, control::SND_NR, &addr(), 0x7A, &[0; 20], &mut wire).unwrap();
371 let mut out = [0u8; 64];
372 assert_eq!(decode(&wire[..w - 1], Format::A, &mut out).unwrap(), None);
373 }
374
375 #[test]
376 fn format_b_single_block() {
377 let a = addr().to_bytes();
379 let mut data = [0u8; 15];
380 data[0] = 14; data[1] = control::SND_NR;
382 data[2..10].copy_from_slice(&a);
383 data[10] = 0x78;
384 data[11] = 0x2F;
385 data[12] = 0x2F;
386 let crc = crc16(&data[..13]).to_be_bytes();
387 data[13..15].copy_from_slice(&crc);
388 let mut out = [0u8; 32];
389 let (frame, used) = decode(&data, Format::B, &mut out).unwrap().unwrap();
390 assert_eq!(used, 15);
391 assert_eq!(frame.payload, &[0x2F, 0x2F]);
392 }
393
394 #[test]
395 fn every_format_round_trips_every_length() {
396 let payload: [u8; 250] = core::array::from_fn(|i| u8::try_from(i % 251).unwrap() ^ 0xA5);
398 for format in [Format::A, Format::B, Format::Stripped] {
399 for n in 0..=245usize {
400 let mut wire = [0u8; 320];
401 let w = match encode(format, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut wire) {
402 Ok(w) => w,
403 Err(e) => {
404 assert!(format == Format::B && n > 241, "{format:?} {n}: {e:?}");
405 assert_eq!(e, Error::InvalidLength);
406 continue;
407 }
408 };
409 assert_eq!(w, wire_len(wire[0], format), "{format:?} {n}");
410 let mut out = [0u8; 320];
411 let (frame, used) = decode(&wire[..w], format, &mut out).unwrap().unwrap();
412 assert_eq!((used, frame.ci, frame.payload), (w, 0x7A, &payload[..n]), "{format:?} {n}");
413 if w > 1 {
414 let mut short = [0u8; 320];
415 assert_eq!(
416 encode(format, control::SND_NR, &addr(), 0x7A, &payload[..n], &mut short[..w - 1]),
417 Err(Error::OutputTooSmall)
418 );
419 }
420 }
421 let mut wire = [0u8; 400];
422 assert_eq!(
423 encode(format, control::SND_NR, &addr(), 0x7A, &[0; 246], &mut wire),
424 Err(Error::InvalidLength)
425 );
426 }
427 }
428}