]> code.octet-stream.net Git - m17rt/blob - m17core/src/tnc.rs
a64f367e70c1f152eafb1892c311ee663b36ec35
[m17rt] / m17core / src / tnc.rs
1 use crate::address::{Address, Callsign};
2 use crate::kiss::{
3 KissBuffer, KissCommand, KissFrame, PORT_PACKET_BASIC, PORT_PACKET_FULL, PORT_STREAM,
4 };
5 use crate::modem::ModulatorFrame;
6 use crate::protocol::{
7 Frame, LichCollection, LsfFrame, Mode, PacketFrame, PacketFrameCounter, StreamFrame,
8 };
9
10 /// Handles the KISS protocol and frame management for `SoftModulator` and `SoftDemodulator`.
11 ///
12 /// These components work alongside each other. User is responsible for chaining them together
13 /// or doing something else with the data.
14 pub struct SoftTnc {
15 /// Handle framing of KISS commands from the host, which may arrive in arbitrary binary blobs.
16 kiss_buffer: KissBuffer,
17
18 /// Kiss message that needs to be sent to the host.
19 outgoing_kiss: Option<OutgoingKiss>,
20
21 /// Current RX or TX function of the TNC.
22 state: State,
23
24 /// Latest state of data carrier detect from demodulator - controls whether we can go to TX
25 dcd: bool,
26
27 /// If CSMA declined to transmit into an idle slot, at what point do we next check it?
28 next_csma_check: Option<u64>,
29
30 /// Current monotonic time, counted in samples
31 now: u64,
32
33 // TODO: use a static ring buffer crate of some sort?
34 /// Circular buffer of packets enqueued for transmission
35 packet_queue: [PendingPacket; 4],
36
37 /// Next slot to fill
38 packet_next: usize,
39
40 /// Current packet index, which is either partly transmitted or not transmitted at all.
41 packet_curr: usize,
42
43 /// If true, packet_next == packet_curr implies full queue. packet_next is invalid.
44 /// If false, it implies empty queue.
45 packet_full: bool,
46
47 /// The LSF for a stream we are going to start transmitting.
48 ///
49 /// This serves as a general indicator that we want to tx a stream.
50 stream_pending_lsf: Option<LsfFrame>,
51
52 /// Circular buffer of stream data enqueued for transmission.
53 ///
54 /// When the queue empties out, we hope that the last one has the end-of-stream flag set.
55 /// Otherwise a buffer underrun has occurred.
56 ///
57 /// Overruns are less troublesome - we can drop frames and receiving stations should cope.
58 stream_queue: [StreamFrame; 8],
59
60 /// Next slot to fill
61 stream_next: usize,
62
63 /// Current unsent stream frame index
64 stream_curr: usize,
65
66 /// True if stream_next == stream_curr because the queue is full. stream_next is invalid.
67 stream_full: bool,
68
69 /// Should PTT be on right now? Polled by external
70 ptt: bool,
71
72 /// TxDelay raw value, number of 10ms units. We will optimistically start with default 0.
73 tx_delay: u8,
74
75 /// This is a full duplex channel so we do not need to monitor DCD or use CSMA. Default false.
76 full_duplex: bool,
77 }
78
79 impl SoftTnc {
80 pub fn new() -> Self {
81 Self {
82 kiss_buffer: KissBuffer::new(),
83 outgoing_kiss: None,
84 state: State::Idle,
85 dcd: false,
86 next_csma_check: None,
87 now: 0,
88 packet_queue: Default::default(),
89 packet_next: 0,
90 packet_curr: 0,
91 packet_full: false,
92 stream_pending_lsf: None,
93 stream_queue: Default::default(),
94 stream_next: 0,
95 stream_curr: 0,
96 stream_full: false,
97 ptt: false,
98 tx_delay: 0,
99 full_duplex: false,
100 }
101 }
102
103 /// Process an individual `Frame` that has been decoded by the modem.
104 pub fn handle_frame(&mut self, frame: Frame) {
105 if self.ptt {
106 // Ignore self-decodes
107 return;
108 }
109 match frame {
110 Frame::Lsf(lsf) => {
111 // A new LSF implies a clean slate.
112 // If we were partway through decoding something else then we missed it.
113 match lsf.mode() {
114 Mode::Packet => {
115 self.state = State::RxPacket(RxPacketState {
116 lsf,
117 packet: [0u8; 825],
118 count: 0,
119 })
120 }
121 Mode::Stream => {
122 let kiss = KissFrame::new_stream_setup(&lsf.0).unwrap();
123 self.kiss_to_host(kiss);
124 self.state = State::RxStream(RxStreamState {
125 _lsf: lsf,
126 index: 0,
127 });
128 }
129 }
130 }
131 Frame::Packet(packet) => {
132 match &mut self.state {
133 State::RxPacket(ref mut rx) => {
134 match packet.counter {
135 PacketFrameCounter::Frame { index } => {
136 if index == rx.count && index < 32 {
137 let start = 25 * index;
138 rx.packet[start..(start + 25)].copy_from_slice(&packet.payload);
139 rx.count += 1;
140 } else {
141 // unexpected order - something has gone wrong
142 self.state = State::Idle;
143 }
144 }
145 PacketFrameCounter::FinalFrame { payload_len } => {
146 let start = 25 * rx.count;
147 let end = start + payload_len;
148 rx.packet[start..(start + payload_len)]
149 .copy_from_slice(&packet.payload[0..payload_len]);
150 // TODO: compatible packets should be sent on port 0 too
151 let kiss =
152 KissFrame::new_full_packet(&rx.lsf.0, &rx.packet[0..end])
153 .unwrap();
154 self.kiss_to_host(kiss);
155 self.state = State::Idle;
156 }
157 }
158 }
159 _ => {
160 // Invalid transition
161 self.state = State::Idle;
162 }
163 }
164 }
165 Frame::Stream(stream) => {
166 match &mut self.state {
167 State::RxStream(ref mut rx) => {
168 // TODO: consider wraparound from 0x7fff
169 if stream.frame_number < rx.index {
170 let mut lich = LichCollection::new();
171 lich.set_segment(stream.lich_idx, stream.lich_part);
172 self.state = State::RxAcquiringStream(RxAcquiringStreamState { lich });
173 } else {
174 rx.index = stream.frame_number + 1;
175 let kiss = KissFrame::new_stream_data(&stream).unwrap();
176 self.kiss_to_host(kiss);
177 // TODO: end stream if LICH updates indicate non-META part has changed
178 // (this implies a new station)
179 if stream.end_of_stream {
180 self.state = State::Idle;
181 }
182 }
183 }
184 State::RxAcquiringStream(ref mut rx) => {
185 rx.lich.set_segment(stream.lich_idx, stream.lich_part);
186 if let Some(maybe_lsf) = rx.lich.try_assemble() {
187 let lsf = LsfFrame(maybe_lsf);
188 // LICH can change mid-transmission so wait until the CRC is correct
189 // to ensure (to high probability) we haven't done a "torn read"
190 if lsf.check_crc() == 0 {
191 let kiss = KissFrame::new_stream_setup(&lsf.0).unwrap();
192 self.kiss_to_host(kiss);
193 // TODO: avoid discarding the first data payload here
194 // need a queue depth of 2 for outgoing kiss
195 self.state = State::RxStream(RxStreamState {
196 _lsf: lsf,
197 index: stream.frame_number + 1,
198 });
199 }
200 }
201 }
202 _ => {
203 // If coming from another state, we have missed something.
204 // Never mind, let's start tracking LICH.
205 let mut lich = LichCollection::new();
206 lich.set_segment(stream.lich_idx, stream.lich_part);
207 self.state = State::RxAcquiringStream(RxAcquiringStreamState { lich })
208 }
209 }
210 }
211 }
212 }
213
214 pub fn set_data_carrier_detect(&mut self, dcd: bool) {
215 self.dcd = dcd;
216 }
217
218 pub fn set_now(&mut self, now_samples: u64) {
219 self.now = now_samples;
220 if let State::TxEndingAtTime(time) = self.state {
221 if now_samples >= time {
222 self.ptt = false;
223 self.state = State::Idle;
224 }
225 }
226 }
227
228 pub fn ptt(&self) -> bool {
229 self.ptt
230 }
231
232 pub fn set_tx_end_time(&mut self, in_samples: usize) {
233 log::debug!("tnc has been told that tx will complete in {in_samples} samples");
234 if let State::TxEnding = self.state {
235 self.state = State::TxEndingAtTime(self.now + in_samples as u64);
236 }
237 }
238
239 pub fn read_tx_frame(&mut self) -> Option<ModulatorFrame> {
240 match self.state {
241 State::Idle | State::RxAcquiringStream(_) | State::RxStream(_) | State::RxPacket(_) => {
242 let stream_wants_to_tx = self.stream_pending_lsf.is_some();
243 let packet_wants_to_tx = self.packet_full || (self.packet_next != self.packet_curr);
244 if !stream_wants_to_tx && !packet_wants_to_tx {
245 return None;
246 }
247
248 // We have something we might send if the channel is free
249
250 // TODO: Proper full duplex support
251 // A true full duplex TNC should be able to rx and tx concurrently, implying
252 // separate states.
253 if !self.full_duplex {
254 match self.next_csma_check {
255 None => {
256 if self.dcd {
257 self.next_csma_check = Some(self.now + 1920);
258 return None;
259 } else {
260 // channel is idle at the moment we get a frame to send
261 // go right ahead
262 }
263 }
264 Some(at_time) => {
265 if self.now < at_time {
266 return None;
267 }
268 // 25% chance that we'll transmit this slot.
269 // Using self.now as random is probably fine so long as it's not being set in
270 // a lumpy manner. m17app's soundmodem should be fine.
271 // TODO: bring in prng to help in cases where `now` never ends in 0b11
272 let p1_4 = (self.now & 3) == 3;
273 if !self.dcd || !p1_4 {
274 self.next_csma_check = Some(self.now + 1920);
275 return None;
276 } else {
277 self.next_csma_check = None;
278 }
279 }
280 }
281 }
282
283 if stream_wants_to_tx {
284 self.state = State::TxStream;
285 } else {
286 self.state = State::TxPacket;
287 }
288 self.ptt = true;
289 Some(ModulatorFrame::Preamble {
290 tx_delay: self.tx_delay,
291 })
292 }
293 State::TxStream => {
294 if !self.stream_full && self.stream_next == self.stream_curr {
295 return None;
296 }
297 if let Some(lsf) = self.stream_pending_lsf.take() {
298 return Some(ModulatorFrame::Lsf(lsf));
299 }
300 let frame = self.stream_queue[self.stream_curr].clone();
301 if self.stream_full {
302 self.stream_full = false;
303 }
304 self.stream_curr = (self.stream_curr + 1) % 8;
305 if frame.end_of_stream {
306 self.state = State::TxStreamSentEndOfStream;
307 }
308 Some(ModulatorFrame::Stream(frame))
309 }
310 State::TxStreamSentEndOfStream => {
311 self.state = State::TxEnding;
312 Some(ModulatorFrame::EndOfTransmission)
313 }
314 State::TxPacket => {
315 if !self.packet_full && self.packet_next == self.packet_curr {
316 return None;
317 }
318 while self.packet_next != self.packet_curr {
319 match self.packet_queue[self.packet_curr].next_frame() {
320 Some(frame) => {
321 return Some(frame);
322 }
323 None => {
324 self.packet_curr = (self.packet_curr + 1) % 4;
325 }
326 }
327 }
328 self.state = State::TxEnding;
329 Some(ModulatorFrame::EndOfTransmission)
330 }
331 State::TxEnding | State::TxEndingAtTime(_) => {
332 // Once we have signalled EOT we withold any new frames until
333 // the channel fully clears and we are ready to TX again
334 None
335 }
336 }
337 }
338
339 /// Read KISS message to be sent to host.
340 ///
341 /// After each frame input, this should be consumed in a loop until length 0 is returned.
342 /// This component will never block. Upstream interface can provide blocking `read()` if desired.
343 pub fn read_kiss(&mut self, target_buf: &mut [u8]) -> usize {
344 match self.outgoing_kiss.as_mut() {
345 Some(outgoing) => {
346 let n = (outgoing.kiss_frame.len - outgoing.sent).min(target_buf.len());
347 target_buf[0..n]
348 .copy_from_slice(&outgoing.kiss_frame.data[outgoing.sent..(outgoing.sent + n)]);
349 outgoing.sent += n;
350 if outgoing.sent == outgoing.kiss_frame.len {
351 self.outgoing_kiss = None;
352 }
353 n
354 }
355 None => 0,
356 }
357 }
358
359 /// Host sends in some KISS data.
360 pub fn write_kiss(&mut self, buf: &[u8]) -> usize {
361 let target_buf = self.kiss_buffer.buf_remaining();
362 let n = buf.len().min(target_buf.len());
363 target_buf[0..n].copy_from_slice(&buf[0..n]);
364 self.kiss_buffer.did_write(n);
365 while let Some(kiss_frame) = self.kiss_buffer.next_frame() {
366 let Ok(port) = kiss_frame.port() else {
367 continue;
368 };
369 let Ok(command) = kiss_frame.command() else {
370 continue;
371 };
372 if port != PORT_PACKET_BASIC && port != PORT_PACKET_FULL && port != PORT_STREAM {
373 continue;
374 }
375 if command == KissCommand::TxDelay {
376 let mut new_delay = [0u8; 1];
377 if kiss_frame.decode_payload(&mut new_delay) == Ok(1) {
378 self.tx_delay = new_delay[0];
379 }
380 continue;
381 }
382 if command == KissCommand::FullDuplex {
383 let mut new_duplex = [0u8; 1];
384 if kiss_frame.decode_payload(&mut new_duplex) == Ok(1) {
385 self.full_duplex = new_duplex[0] != 0;
386 }
387 continue;
388 }
389 if command != KissCommand::DataFrame {
390 // Not supporting any other settings yet
391 // TODO: allow adjusting P persistence parameter for CSMA
392 continue;
393 }
394 if port == PORT_PACKET_BASIC {
395 if self.packet_full {
396 continue;
397 }
398 let mut pending = PendingPacket::new();
399 pending.app_data[0] = 0x00; // RAW
400 let Ok(mut len) = kiss_frame.decode_payload(&mut pending.app_data[1..]) else {
401 continue;
402 };
403 len += 1; // for RAW prefix
404 let packet_crc = crate::crc::m17_crc(&pending.app_data[0..len]);
405 pending.app_data[len..len + 2].copy_from_slice(&packet_crc.to_be_bytes());
406 pending.app_data_len = len + 2;
407 pending.lsf = Some(LsfFrame::new_packet(
408 &Address::Callsign(Callsign(*b"M17RT-PKT")),
409 &Address::Broadcast,
410 ));
411 self.packet_queue[self.packet_next] = pending;
412 self.packet_next = (self.packet_next + 1) % 4;
413 if self.packet_next == self.packet_curr {
414 self.packet_full = true;
415 }
416 } else if port == PORT_PACKET_FULL {
417 if self.packet_full {
418 continue;
419 }
420 let mut pending = PendingPacket::new();
421 let mut payload = [0u8; 855];
422 let Ok(len) = kiss_frame.decode_payload(&mut payload) else {
423 continue;
424 };
425 if len < 33 {
426 continue;
427 }
428 let mut lsf = LsfFrame([0u8; 30]);
429 lsf.0.copy_from_slice(&payload[0..30]);
430 if lsf.check_crc() != 0 {
431 continue;
432 }
433 pending.lsf = Some(lsf);
434 let app_data_len = len - 30;
435 pending.app_data[0..app_data_len].copy_from_slice(&payload[30..len]);
436 pending.app_data_len = app_data_len;
437 self.packet_queue[self.packet_next] = pending;
438 self.packet_next = (self.packet_next + 1) % 4;
439 if self.packet_next == self.packet_curr {
440 self.packet_full = true;
441 }
442 } else if port == PORT_STREAM {
443 let mut payload = [0u8; 30];
444 let Ok(len) = kiss_frame.decode_payload(&mut payload) else {
445 continue;
446 };
447 if len < 26 {
448 log::debug!("payload len too short");
449 continue;
450 }
451 if len == 30 {
452 let lsf = LsfFrame(payload);
453 if lsf.check_crc() != 0 {
454 continue;
455 }
456 self.stream_pending_lsf = Some(lsf);
457 } else {
458 if self.stream_full {
459 log::debug!("stream full");
460 continue;
461 }
462 let frame_num_part = u16::from_be_bytes([payload[6], payload[7]]);
463 self.stream_queue[self.stream_next] = StreamFrame {
464 lich_idx: payload[5] >> 5,
465 lich_part: payload[0..5].try_into().unwrap(),
466 frame_number: frame_num_part & 0x7fff,
467 end_of_stream: frame_num_part & 0x8000 > 0,
468 stream_data: payload[8..24].try_into().unwrap(),
469 };
470 self.stream_next = (self.stream_next + 1) % 8;
471 if self.stream_next == self.stream_curr {
472 self.stream_full = true;
473 }
474 }
475 }
476 }
477 n
478 }
479
480 fn kiss_to_host(&mut self, kiss_frame: KissFrame) {
481 self.outgoing_kiss = Some(OutgoingKiss {
482 kiss_frame,
483 sent: 0,
484 });
485 }
486 }
487
488 impl Default for SoftTnc {
489 fn default() -> Self {
490 Self::new()
491 }
492 }
493
494 #[derive(Debug, PartialEq, Eq, Clone)]
495 pub enum SoftTncError {
496 General(&'static str),
497 InvalidState,
498 }
499
500 struct OutgoingKiss {
501 kiss_frame: KissFrame,
502 sent: usize,
503 }
504
505 #[allow(clippy::large_enum_variant)]
506 enum State {
507 /// Nothing happening. We may have TX data queued but we won't act on it until CSMA opens up.
508 Idle,
509
510 /// We received some stream data but missed the leading LSF so we are trying to assemble from LICH.
511 RxAcquiringStream(RxAcquiringStreamState),
512
513 /// We have acquired an identified stream transmission and are sending data payloads to the host.
514 RxStream(RxStreamState),
515
516 /// We are receiving a packet. All is well so far, and there is more data to come before we tell the host.
517 RxPacket(RxPacketState),
518
519 /// PTT is on and this is a stream-type transmission. New data may be added.
520 TxStream,
521
522 /// We have delivered the last frame in the current stream
523 TxStreamSentEndOfStream,
524
525 /// PTT is on and this is a packet-type transmission. New packets may be enqueued.
526 TxPacket,
527
528 /// We gave modulator an EndOfTransmission. PTT is still on, waiting for modulator to advise end time.
529 TxEnding,
530
531 /// Ending transmission, PTT remains on, but we know the timestamp at which we should disengage it.
532 TxEndingAtTime(u64),
533 }
534
535 struct RxAcquiringStreamState {
536 /// Partial assembly of LSF by accumulating LICH fields.
537 lich: LichCollection,
538 }
539
540 struct RxStreamState {
541 /// Track identifying information for this transmission so we can tell if it changes.
542 _lsf: LsfFrame,
543
544 /// Expected next frame number. Allowed to skip values on RX, but not go backwards.
545 index: u16,
546 }
547
548 struct RxPacketState {
549 /// Initial LSF
550 lsf: LsfFrame,
551
552 /// Accumulation of packet data that we have received so far.
553 packet: [u8; 825],
554
555 /// Number of payload frames we have received. If we are stably in the RxPacket state,
556 /// this will be between 0 and 32 inclusive.
557 count: usize,
558 }
559
560 struct PendingPacket {
561 lsf: Option<LsfFrame>,
562
563 app_data: [u8; 825],
564 app_data_len: usize,
565 app_data_transmitted: usize,
566 }
567
568 impl PendingPacket {
569 fn new() -> Self {
570 Self {
571 lsf: None,
572 app_data: [0u8; 825],
573 app_data_len: 0,
574 app_data_transmitted: 0,
575 }
576 }
577
578 /// Returns next frame, not including preamble or EOT.
579 ///
580 /// False means all data frames have been sent.
581 fn next_frame(&mut self) -> Option<ModulatorFrame> {
582 if let Some(lsf) = self.lsf.take() {
583 return Some(ModulatorFrame::Lsf(lsf));
584 }
585 if self.app_data_len == self.app_data_transmitted {
586 return None;
587 }
588 let remaining = self.app_data_len - self.app_data_transmitted;
589 let (counter, data_len) = if remaining <= 25 {
590 (
591 PacketFrameCounter::FinalFrame {
592 payload_len: remaining,
593 },
594 remaining,
595 )
596 } else {
597 (
598 PacketFrameCounter::Frame {
599 index: self.app_data_transmitted / 25,
600 },
601 25,
602 )
603 };
604 let mut payload = [0u8; 25];
605 payload[0..data_len].copy_from_slice(
606 &self.app_data[self.app_data_transmitted..(self.app_data_transmitted + data_len)],
607 );
608 self.app_data_transmitted += data_len;
609 Some(ModulatorFrame::Packet(PacketFrame { payload, counter }))
610 }
611 }
612
613 impl Default for PendingPacket {
614 fn default() -> Self {
615 Self {
616 lsf: None,
617 app_data: [0u8; 825],
618 app_data_len: 0,
619 app_data_transmitted: 0,
620 }
621 }
622 }
623
624 #[cfg(test)]
625 mod tests {
626 use super::*;
627 use crate::kiss::{KissCommand, PORT_STREAM};
628 use crate::protocol::StreamFrame;
629
630 // TODO: finish all handle_frame tests as below
631 // this will be much more straightforward when we have a way to create LSFs programatically
632
633 // receiving a single-frame packet
634
635 // receiving a multi-frame packet
636
637 // part of one packet and then another
638
639 #[test]
640 fn tnc_receive_stream() {
641 let lsf = LsfFrame([
642 255, 255, 255, 255, 255, 255, 0, 0, 0, 159, 221, 81, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0,
643 0, 0, 0, 0, 0, 131, 53,
644 ]);
645 let stream1 = StreamFrame {
646 lich_idx: 0,
647 lich_part: [255, 255, 255, 255, 255],
648 frame_number: 0,
649 end_of_stream: false,
650 stream_data: [
651 128, 0, 119, 115, 220, 252, 41, 235, 8, 0, 116, 195, 94, 244, 45, 75,
652 ],
653 };
654 let stream2 = StreamFrame {
655 lich_idx: 1,
656 lich_part: [255, 0, 0, 0, 159],
657 frame_number: 1,
658 end_of_stream: true,
659 stream_data: [
660 17, 0, 94, 82, 216, 135, 181, 15, 30, 0, 125, 195, 152, 183, 41, 57,
661 ],
662 };
663 let mut tnc = SoftTnc::new();
664 let mut kiss = KissFrame::new_empty();
665 assert_eq!(tnc.read_kiss(&mut kiss.data), 0);
666
667 tnc.handle_frame(Frame::Lsf(lsf));
668 kiss.len = tnc.read_kiss(&mut kiss.data);
669 assert_eq!(kiss.command().unwrap(), KissCommand::DataFrame);
670 assert_eq!(kiss.port().unwrap(), PORT_STREAM);
671
672 let mut payload_buf = [0u8; 2048];
673 let n = kiss.decode_payload(&mut payload_buf).unwrap();
674 assert_eq!(n, 30);
675
676 tnc.handle_frame(Frame::Stream(stream1));
677 kiss.len = tnc.read_kiss(&mut kiss.data);
678 assert_eq!(kiss.command().unwrap(), KissCommand::DataFrame);
679 assert_eq!(kiss.port().unwrap(), PORT_STREAM);
680
681 let n = kiss.decode_payload(&mut payload_buf).unwrap();
682 assert_eq!(n, 26);
683
684 tnc.handle_frame(Frame::Stream(stream2));
685 kiss.len = tnc.read_kiss(&mut kiss.data);
686 assert_eq!(kiss.command().unwrap(), KissCommand::DataFrame);
687 assert_eq!(kiss.port().unwrap(), PORT_STREAM);
688
689 let n = kiss.decode_payload(&mut payload_buf).unwrap();
690 assert_eq!(n, 26);
691 }
692
693 #[test]
694 fn tnc_acquire_stream() {
695 let frames = [
696 StreamFrame {
697 lich_idx: 0,
698 lich_part: [255, 255, 255, 255, 255],
699 frame_number: 0,
700 end_of_stream: false,
701 stream_data: [
702 128, 0, 119, 115, 220, 252, 41, 235, 8, 0, 116, 195, 94, 244, 45, 75,
703 ],
704 },
705 StreamFrame {
706 lich_idx: 1,
707 lich_part: [255, 0, 0, 0, 159],
708 frame_number: 1,
709 end_of_stream: false,
710 stream_data: [
711 17, 0, 94, 82, 216, 135, 181, 15, 30, 0, 125, 195, 152, 183, 41, 57,
712 ],
713 },
714 StreamFrame {
715 lich_idx: 2,
716 lich_part: [221, 81, 5, 5, 0],
717 frame_number: 2,
718 end_of_stream: false,
719 stream_data: [
720 17, 128, 93, 74, 154, 167, 169, 11, 20, 0, 116, 91, 158, 220, 45, 111,
721 ],
722 },
723 StreamFrame {
724 lich_idx: 3,
725 lich_part: [0, 0, 0, 0, 0],
726 frame_number: 3,
727 end_of_stream: false,
728 stream_data: [
729 15, 128, 114, 83, 218, 252, 59, 111, 31, 128, 116, 91, 84, 231, 45, 105,
730 ],
731 },
732 StreamFrame {
733 lich_idx: 4,
734 lich_part: [0, 0, 0, 0, 0],
735 frame_number: 4,
736 end_of_stream: false,
737 stream_data: [
738 9, 128, 119, 115, 220, 220, 57, 15, 48, 128, 124, 83, 158, 236, 181, 91,
739 ],
740 },
741 StreamFrame {
742 lich_idx: 5,
743 lich_part: [0, 0, 0, 131, 53],
744 frame_number: 5,
745 end_of_stream: false,
746 stream_data: [
747 52, 0, 116, 90, 152, 167, 225, 216, 32, 0, 116, 83, 156, 212, 33, 216,
748 ],
749 },
750 ];
751
752 let mut tnc = SoftTnc::new();
753 let mut kiss = KissFrame::new_empty();
754 for f in frames {
755 tnc.handle_frame(Frame::Stream(f));
756 }
757 kiss.len = tnc.read_kiss(&mut kiss.data);
758 let mut payload_buf = [0u8; 2048];
759 let n = kiss.decode_payload(&mut payload_buf).unwrap();
760 assert_eq!(n, 30);
761 assert_eq!(
762 &payload_buf[0..30],
763 [
764 255, 255, 255, 255, 255, 255, 0, 0, 0, 159, 221, 81, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0,
765 0, 0, 0, 0, 0, 0, 131, 53,
766 ]
767 );
768 }
769
770 #[test]
771 fn tnc_handle_skipped_stream_frame() {
772 let lsf = LsfFrame([
773 255, 255, 255, 255, 255, 255, 0, 0, 0, 159, 221, 81, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0,
774 0, 0, 0, 0, 0, 131, 53,
775 ]);
776 let stream1 = StreamFrame {
777 lich_idx: 0,
778 lich_part: [255, 255, 255, 255, 255],
779 frame_number: 0,
780 end_of_stream: false,
781 stream_data: [
782 128, 0, 119, 115, 220, 252, 41, 235, 8, 0, 116, 195, 94, 244, 45, 75,
783 ],
784 };
785 let stream3 = StreamFrame {
786 lich_idx: 2,
787 lich_part: [221, 81, 5, 5, 0],
788 frame_number: 2,
789 end_of_stream: false,
790 stream_data: [
791 17, 128, 93, 74, 154, 167, 169, 11, 20, 0, 116, 91, 158, 220, 45, 111,
792 ],
793 };
794 let mut tnc = SoftTnc::new();
795 let mut kiss = KissFrame::new_empty();
796 assert_eq!(tnc.read_kiss(&mut kiss.data), 0);
797
798 tnc.handle_frame(Frame::Lsf(lsf));
799 kiss.len = tnc.read_kiss(&mut kiss.data);
800 assert_eq!(kiss.command().unwrap(), KissCommand::DataFrame);
801 assert_eq!(kiss.port().unwrap(), PORT_STREAM);
802
803 let mut payload_buf = [0u8; 2048];
804 let n = kiss.decode_payload(&mut payload_buf).unwrap();
805 assert_eq!(n, 30);
806
807 tnc.handle_frame(Frame::Stream(stream1));
808 kiss.len = tnc.read_kiss(&mut kiss.data);
809 assert_eq!(kiss.command().unwrap(), KissCommand::DataFrame);
810 assert_eq!(kiss.port().unwrap(), PORT_STREAM);
811
812 let n = kiss.decode_payload(&mut payload_buf).unwrap();
813 assert_eq!(n, 26);
814
815 tnc.handle_frame(Frame::Stream(stream3));
816 kiss.len = tnc.read_kiss(&mut kiss.data);
817 assert_eq!(kiss.command().unwrap(), KissCommand::DataFrame);
818 assert_eq!(kiss.port().unwrap(), PORT_STREAM);
819
820 let n = kiss.decode_payload(&mut payload_buf).unwrap();
821 assert_eq!(n, 26);
822 }
823 }