Skip to main content

zigbee_ash/
conn.rs

1//! The ASH link layer as a sans-IO state machine.
2//!
3//! [`Connection`] does no I/O and reads no clock: feed it received frames
4//! with [`Connection::handle_frame`], timer expiries with
5//! [`Connection::handle_timeout`], and payloads with [`Connection::send`];
6//! take bytes to write from [`Connection::poll_transmit`] and events from
7//! [`Connection::poll_event`]. The same machine serves both ends of the
8//! link ([`Role`]), which is how the repository's NCP simulator speaks ASH.
9
10use std::collections::VecDeque;
11use std::time::{Duration, Instant};
12
13use crate::frame::{reset_code, Frame, FrameError, ASH_VERSION, MAX_DATA_LEN};
14
15/// Which end of the link this is.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Role {
18    /// The host: sends RST, waits for RSTACK.
19    Host,
20    /// The network co-processor: answers RST with RSTACK.
21    Ncp,
22}
23
24/// Link timing and window settings. The defaults follow UG101.
25#[derive(Debug, Clone)]
26pub struct Config {
27    /// DATA frames in flight before an ACK, 1 to 7.
28    pub tx_window: u8,
29    /// Initial ACK timeout.
30    pub ack_time_init: Duration,
31    /// Lower bound of the adaptive ACK timeout.
32    pub ack_time_min: Duration,
33    /// Upper bound of the adaptive ACK timeout.
34    pub ack_time_max: Duration,
35    /// Consecutive ACK timeouts before the link is declared down.
36    pub max_timeouts: u32,
37    /// How long the host waits for RSTACK before sending RST again.
38    pub rst_timeout: Duration,
39    /// RST attempts before giving up.
40    pub rst_attempts: u32,
41    /// How long to hold DATA after the peer said it is not ready.
42    pub not_ready_time: Duration,
43    /// Payloads queued but not yet sent, beyond which [`Connection::send`] refuses.
44    pub max_queue: usize,
45}
46
47impl Default for Config {
48    fn default() -> Self {
49        Config {
50            tx_window: 3,
51            ack_time_init: Duration::from_millis(800),
52            ack_time_min: Duration::from_millis(400),
53            ack_time_max: Duration::from_millis(2400),
54            max_timeouts: 4,
55            rst_timeout: Duration::from_millis(3200),
56            rst_attempts: 3,
57            not_ready_time: Duration::from_millis(1000),
58            max_queue: 64,
59        }
60    }
61}
62
63/// Why the link went down.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum DownReason {
66    /// The NCP reset while connected (RSTACK out of the blue).
67    NcpReset {
68        /// The NCP's reset code.
69        code: u8,
70    },
71    /// The NCP sent ERROR.
72    NcpError {
73        /// The NCP's error code.
74        code: u8,
75    },
76    /// Too many DATA frames went unacknowledged.
77    AckTimeouts,
78    /// No RSTACK after every RST attempt.
79    ResetTimeout,
80    /// The peer speaks another ASH version.
81    BadVersion(u8),
82}
83
84/// Something the link wants the layer above to know.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum Event {
87    /// The link is up. On the host, `reset_code` is the NCP's reset reason.
88    Connected {
89        /// The reset code from RSTACK (host) or [`reset_code::SOFTWARE`] (NCP).
90        reset_code: u8,
91    },
92    /// An EZSP frame arrived, in order and exactly once.
93    Data(Vec<u8>),
94    /// The link is down; queued and unacknowledged payloads were dropped.
95    Down(DownReason),
96}
97
98/// [`Connection::send`] refused a payload.
99#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
100pub enum SendError {
101    /// The link is not connected.
102    #[error("ASH link is not connected")]
103    NotConnected,
104    /// The queue is full.
105    #[error("ASH transmit queue is full")]
106    QueueFull,
107    /// The payload is not 3 to 220 bytes.
108    #[error("payload of {0} bytes is outside 3..=220")]
109    BadLength(usize),
110}
111
112/// Link counters, for diagnostics.
113#[derive(Debug, Clone, Default, PartialEq, Eq)]
114pub struct Counters {
115    /// DATA frames sent, retransmissions included.
116    pub tx_data: u64,
117    /// DATA frames retransmitted.
118    pub tx_retransmits: u64,
119    /// DATA frames accepted.
120    pub rx_data: u64,
121    /// Frames dropped as malformed (CRC, length, UART error).
122    pub rx_bad: u64,
123    /// DATA frames out of sequence.
124    pub rx_out_of_sequence: u64,
125    /// ACK timer expiries.
126    pub ack_timeouts: u64,
127    /// NAKs sent.
128    pub tx_naks: u64,
129}
130
131#[derive(Debug)]
132enum State {
133    Down,
134    Resetting { deadline: Instant, attempts: u32 },
135    Connected,
136}
137
138#[derive(Debug)]
139struct Sent {
140    num: u8,
141    payload: Vec<u8>,
142    sent_at: Instant,
143    retransmitted: bool,
144}
145
146/// One end of an ASH link.
147#[derive(Debug)]
148pub struct Connection {
149    role: Role,
150    config: Config,
151    state: State,
152    /// Next frame number to give a new DATA frame.
153    frm_tx: u8,
154    /// Oldest frame number not yet acknowledged by the peer.
155    ack_rx: u8,
156    /// Next frame number expected from the peer.
157    frm_rx: u8,
158    queue: VecDeque<Vec<u8>>,
159    unacked: VecDeque<Sent>,
160    /// Index into `unacked` of the next frame to retransmit.
161    retransmit_from: Option<usize>,
162    ack_deadline: Option<Instant>,
163    ack_period: Duration,
164    timeouts: u32,
165    /// A NAK was sent and no in-sequence frame has arrived since.
166    rejecting: bool,
167    send_ack: bool,
168    send_nak: bool,
169    peer_not_ready_until: Option<Instant>,
170    out: VecDeque<Vec<u8>>,
171    events: VecDeque<Event>,
172    counters: Counters,
173}
174
175fn next(n: u8) -> u8 {
176    (n + 1) & 7
177}
178
179/// Distance from `from` forward to `to`, modulo 8.
180fn distance(from: u8, to: u8) -> u8 {
181    to.wrapping_sub(from) & 7
182}
183
184impl Connection {
185    /// A link in the down state. A host starts it with [`Connection::reset`];
186    /// an NCP waits for the host's RST.
187    pub fn new(role: Role, mut config: Config) -> Self {
188        config.tx_window = config.tx_window.clamp(1, 7);
189        let ack_period = config.ack_time_init;
190        Connection {
191            role,
192            config,
193            state: State::Down,
194            frm_tx: 0,
195            ack_rx: 0,
196            frm_rx: 0,
197            queue: VecDeque::new(),
198            unacked: VecDeque::new(),
199            retransmit_from: None,
200            ack_deadline: None,
201            ack_period,
202            timeouts: 0,
203            rejecting: false,
204            send_ack: false,
205            send_nak: false,
206            peer_not_ready_until: None,
207            out: VecDeque::new(),
208            events: VecDeque::new(),
209            counters: Counters::default(),
210        }
211    }
212
213    /// True once RST/RSTACK has completed.
214    pub fn is_connected(&self) -> bool {
215        matches!(self.state, State::Connected)
216    }
217
218    /// Link counters.
219    pub fn counters(&self) -> &Counters {
220        &self.counters
221    }
222
223    /// The current adaptive ACK timeout.
224    pub fn ack_period(&self) -> Duration {
225        self.ack_period
226    }
227
228    fn clear_link(&mut self) {
229        self.frm_tx = 0;
230        self.ack_rx = 0;
231        self.frm_rx = 0;
232        self.queue.clear();
233        self.unacked.clear();
234        self.retransmit_from = None;
235        self.ack_deadline = None;
236        self.ack_period = self.config.ack_time_init;
237        self.timeouts = 0;
238        self.rejecting = false;
239        self.send_ack = false;
240        self.send_nak = false;
241        self.peer_not_ready_until = None;
242        self.out.clear();
243    }
244
245    /// Host: drop everything and send RST. The link reports
246    /// [`Event::Connected`] when the NCP answers.
247    pub fn reset(&mut self, now: Instant) {
248        self.clear_link();
249        if self.role == Role::Host {
250            self.state = State::Resetting {
251                deadline: now + self.config.rst_timeout,
252                attempts: 1,
253            };
254            self.out.push_back(Frame::Rst.encode());
255        } else {
256            self.state = State::Down;
257        }
258    }
259
260    fn go_down(&mut self, reason: DownReason) {
261        self.clear_link();
262        self.state = State::Down;
263        self.events.push_back(Event::Down(reason));
264    }
265
266    /// Queue an EZSP frame for sending.
267    pub fn send(&mut self, payload: Vec<u8>, now: Instant) -> Result<(), SendError> {
268        if !self.is_connected() {
269            return Err(SendError::NotConnected);
270        }
271        if !(crate::frame::MIN_DATA_LEN..=MAX_DATA_LEN).contains(&payload.len()) {
272            return Err(SendError::BadLength(payload.len()));
273        }
274        if self.queue.len() >= self.config.max_queue {
275            return Err(SendError::QueueFull);
276        }
277        self.queue.push_back(payload);
278        self.pump(now);
279        Ok(())
280    }
281
282    /// A frame the decoder rejected (bad CRC, length, UART error).
283    pub fn handle_bad_frame(&mut self, _error: FrameError, now: Instant) {
284        self.counters.rx_bad += 1;
285        if self.is_connected() && !self.rejecting {
286            self.rejecting = true;
287            self.send_nak = true;
288            self.pump(now);
289        }
290    }
291
292    /// A well-formed frame from the peer.
293    pub fn handle_frame(&mut self, frame: Frame, now: Instant) {
294        match (&self.state, self.role, &frame) {
295            // NCP: RST (re)starts the link at any time.
296            (_, Role::Ncp, Frame::Rst) => {
297                self.clear_link();
298                self.state = State::Connected;
299                self.out.push_back(
300                    Frame::RstAck {
301                        version: ASH_VERSION,
302                        code: reset_code::SOFTWARE,
303                    }
304                    .encode(),
305                );
306                self.events.push_back(Event::Connected {
307                    reset_code: reset_code::SOFTWARE,
308                });
309                return;
310            }
311            (State::Resetting { .. }, Role::Host, Frame::RstAck { version, code }) => {
312                if *version != ASH_VERSION {
313                    self.go_down(DownReason::BadVersion(*version));
314                    return;
315                }
316                self.clear_link();
317                self.state = State::Connected;
318                self.events
319                    .push_back(Event::Connected { reset_code: *code });
320                return;
321            }
322            (State::Connected, Role::Host, Frame::RstAck { code, .. }) => {
323                self.go_down(DownReason::NcpReset { code: *code });
324                return;
325            }
326            (State::Connected, Role::Host, Frame::Error { code, .. }) => {
327                self.go_down(DownReason::NcpError { code: *code });
328                return;
329            }
330            (State::Connected, _, Frame::Data { .. } | Frame::Ack { .. } | Frame::Nak { .. }) => {}
331            // Anything else outside a connection is ignored, as UG101 says.
332            _ => return,
333        }
334
335        let (ack_num, not_ready) = match &frame {
336            Frame::Data { ack_num, .. } => (*ack_num, None),
337            Frame::Ack { ack_num, not_ready } | Frame::Nak { ack_num, not_ready } => {
338                (*ack_num, Some(*not_ready))
339            }
340            _ => return,
341        };
342        // An acknowledgement outside the window is a corrupted or stale
343        // frame; drop it whole.
344        if distance(self.ack_rx, ack_num) > distance(self.ack_rx, self.frm_tx) {
345            self.counters.rx_bad += 1;
346            return;
347        }
348        self.acknowledge(ack_num, now);
349        if let Some(not_ready) = not_ready {
350            self.peer_not_ready_until = not_ready.then(|| now + self.config.not_ready_time);
351        }
352
353        match frame {
354            Frame::Nak { .. } => {
355                if !self.unacked.is_empty() {
356                    self.retransmit_from = Some(0);
357                }
358            }
359            Frame::Data {
360                frm_num,
361                re_tx,
362                payload,
363                ..
364            } => {
365                if frm_num == self.frm_rx {
366                    self.frm_rx = next(self.frm_rx);
367                    self.rejecting = false;
368                    self.send_ack = true;
369                    self.counters.rx_data += 1;
370                    self.events.push_back(Event::Data(payload));
371                } else if re_tx {
372                    // A retransmission of a frame already delivered.
373                    self.send_ack = true;
374                } else {
375                    self.counters.rx_out_of_sequence += 1;
376                    if !self.rejecting {
377                        self.rejecting = true;
378                        self.send_nak = true;
379                    }
380                }
381            }
382            _ => {}
383        }
384        self.pump(now);
385    }
386
387    /// The peer acknowledged every frame before `ack_num`.
388    fn acknowledge(&mut self, ack_num: u8, now: Instant) {
389        let mut acked = 0usize;
390        while self.ack_rx != ack_num {
391            if let Some(sent) = self.unacked.pop_front() {
392                if !sent.retransmitted {
393                    self.adapt_ack_period(now.saturating_duration_since(sent.sent_at));
394                }
395            }
396            self.ack_rx = next(self.ack_rx);
397            acked += 1;
398        }
399        if acked > 0 {
400            self.timeouts = 0;
401            self.retransmit_from = self.retransmit_from.map(|i| i.saturating_sub(acked));
402            self.ack_deadline = if self.unacked.is_empty() {
403                None
404            } else {
405                Some(now + self.ack_period)
406            };
407        }
408    }
409
410    /// UG101: T_RX_ACK = 7/8 T_RX_ACK + 1/2 measured, within bounds.
411    fn adapt_ack_period(&mut self, measured: Duration) {
412        let period = self.ack_period * 7 / 8 + measured / 2;
413        self.ack_period = period.clamp(self.config.ack_time_min, self.config.ack_time_max);
414    }
415
416    /// The earliest time [`Connection::handle_timeout`] must be called.
417    pub fn poll_timeout(&self) -> Option<Instant> {
418        let reset = match self.state {
419            State::Resetting { deadline, .. } => Some(deadline),
420            _ => None,
421        };
422        [reset, self.ack_deadline, self.peer_not_ready_until]
423            .into_iter()
424            .flatten()
425            .min()
426    }
427
428    /// Run the timers.
429    pub fn handle_timeout(&mut self, now: Instant) {
430        if let State::Resetting { deadline, attempts } = self.state {
431            if now >= deadline {
432                if attempts >= self.config.rst_attempts {
433                    self.go_down(DownReason::ResetTimeout);
434                } else {
435                    self.state = State::Resetting {
436                        deadline: now + self.config.rst_timeout,
437                        attempts: attempts + 1,
438                    };
439                    self.out.push_back(Frame::Rst.encode());
440                }
441            }
442            return;
443        }
444        if self.peer_not_ready_until.is_some_and(|t| now >= t) {
445            self.peer_not_ready_until = None;
446        }
447        if let Some(deadline) = self.ack_deadline {
448            if now >= deadline && !self.unacked.is_empty() {
449                self.counters.ack_timeouts += 1;
450                self.timeouts += 1;
451                if self.timeouts > self.config.max_timeouts {
452                    self.go_down(DownReason::AckTimeouts);
453                    return;
454                }
455                self.ack_period = (self.ack_period * 2).min(self.config.ack_time_max);
456                self.retransmit_from = Some(0);
457                self.ack_deadline = Some(now + self.ack_period);
458            }
459        }
460        self.pump(now);
461    }
462
463    /// Move whatever may be sent now into the output queue.
464    fn pump(&mut self, now: Instant) {
465        if !self.is_connected() {
466            return;
467        }
468        // Retransmissions first, oldest first.
469        while let Some(index) = self.retransmit_from {
470            let ack_num = self.frm_rx;
471            match self.unacked.get_mut(index) {
472                Some(sent) => {
473                    sent.retransmitted = true;
474                    let frame = Frame::Data {
475                        frm_num: sent.num,
476                        re_tx: true,
477                        ack_num,
478                        payload: sent.payload.clone(),
479                    };
480                    self.out.push_back(frame.encode());
481                    self.counters.tx_data += 1;
482                    self.counters.tx_retransmits += 1;
483                    self.send_ack = false;
484                    self.retransmit_from = Some(index + 1);
485                }
486                None => self.retransmit_from = None,
487            }
488        }
489        let peer_ready = self.peer_not_ready_until.is_none_or(|t| now >= t);
490        while peer_ready && self.unacked.len() < usize::from(self.config.tx_window) {
491            let Some(payload) = self.queue.pop_front() else {
492                break;
493            };
494            let num = self.frm_tx;
495            self.frm_tx = next(self.frm_tx);
496            let frame = Frame::Data {
497                frm_num: num,
498                re_tx: false,
499                ack_num: self.frm_rx,
500                payload,
501            };
502            self.out.push_back(frame.encode());
503            self.counters.tx_data += 1;
504            self.send_ack = false;
505            if let Frame::Data { payload, .. } = frame {
506                self.unacked.push_back(Sent {
507                    num,
508                    payload,
509                    sent_at: now,
510                    retransmitted: false,
511                });
512            }
513            if self.ack_deadline.is_none() {
514                self.ack_deadline = Some(now + self.ack_period);
515            }
516        }
517        if self.send_nak {
518            self.send_nak = false;
519            self.send_ack = false;
520            self.counters.tx_naks += 1;
521            self.out.push_back(
522                Frame::Nak {
523                    ack_num: self.frm_rx,
524                    not_ready: false,
525                }
526                .encode(),
527            );
528        } else if self.send_ack {
529            self.send_ack = false;
530            self.out.push_back(
531                Frame::Ack {
532                    ack_num: self.frm_rx,
533                    not_ready: false,
534                }
535                .encode(),
536            );
537        }
538    }
539
540    /// Bytes to write to the serial port, if any.
541    pub fn poll_transmit(&mut self) -> Option<Vec<u8>> {
542        self.out.pop_front()
543    }
544
545    /// The next event for the layer above, if any.
546    pub fn poll_event(&mut self) -> Option<Event> {
547        self.events.pop_front()
548    }
549}
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554    use crate::frame::Decoder;
555
556    /// Two connections joined by a link that can drop or corrupt frames,
557    /// on a virtual clock.
558    struct Pair {
559        host: Connection,
560        ncp: Connection,
561        host_rx: Decoder,
562        ncp_rx: Decoder,
563        now: Instant,
564        /// Return true to drop the n-th frame host to NCP.
565        drop_to_ncp: Box<dyn FnMut(usize) -> bool>,
566        drop_to_host: Box<dyn FnMut(usize) -> bool>,
567        sent_to_ncp: usize,
568        sent_to_host: usize,
569        host_events: Vec<Event>,
570        ncp_events: Vec<Event>,
571    }
572
573    impl Pair {
574        fn new() -> Self {
575            Pair {
576                host: Connection::new(Role::Host, Config::default()),
577                ncp: Connection::new(Role::Ncp, Config::default()),
578                host_rx: Decoder::new(),
579                ncp_rx: Decoder::new(),
580                now: Instant::now(),
581                drop_to_ncp: Box::new(|_| false),
582                drop_to_host: Box::new(|_| false),
583                sent_to_ncp: 0,
584                sent_to_host: 0,
585                host_events: vec![],
586                ncp_events: vec![],
587            }
588        }
589
590        /// Deliver everything in flight until both sides are quiet.
591        fn settle(&mut self) {
592            for _ in 0..1000 {
593                let mut moved = false;
594                while let Some(bytes) = self.host.poll_transmit() {
595                    moved = true;
596                    self.sent_to_ncp += 1;
597                    if (self.drop_to_ncp)(self.sent_to_ncp) {
598                        continue;
599                    }
600                    for b in bytes {
601                        if let Some(r) = self.ncp_rx.push(b) {
602                            match r {
603                                Ok(f) => self.ncp.handle_frame(f, self.now),
604                                Err(e) => self.ncp.handle_bad_frame(e, self.now),
605                            }
606                        }
607                    }
608                }
609                while let Some(bytes) = self.ncp.poll_transmit() {
610                    moved = true;
611                    self.sent_to_host += 1;
612                    if (self.drop_to_host)(self.sent_to_host) {
613                        continue;
614                    }
615                    for b in bytes {
616                        if let Some(r) = self.host_rx.push(b) {
617                            match r {
618                                Ok(f) => self.host.handle_frame(f, self.now),
619                                Err(e) => self.host.handle_bad_frame(e, self.now),
620                            }
621                        }
622                    }
623                }
624                while let Some(e) = self.host.poll_event() {
625                    self.host_events.push(e);
626                }
627                while let Some(e) = self.ncp.poll_event() {
628                    self.ncp_events.push(e);
629                }
630                if !moved {
631                    return;
632                }
633            }
634            panic!("link did not settle");
635        }
636
637        /// Advance the clock to the next timer and run it.
638        fn tick(&mut self) {
639            let next = [self.host.poll_timeout(), self.ncp.poll_timeout()]
640                .into_iter()
641                .flatten()
642                .min();
643            if let Some(t) = next {
644                self.now = self.now.max(t);
645            }
646            self.host.handle_timeout(self.now);
647            self.ncp.handle_timeout(self.now);
648            self.settle();
649        }
650
651        fn connect(&mut self) {
652            self.host.reset(self.now);
653            self.settle();
654            assert!(self.host.is_connected() && self.ncp.is_connected());
655            assert_eq!(
656                self.host_events.remove(0),
657                Event::Connected {
658                    reset_code: reset_code::SOFTWARE
659                }
660            );
661            assert_eq!(
662                self.ncp_events.remove(0),
663                Event::Connected {
664                    reset_code: reset_code::SOFTWARE
665                }
666            );
667        }
668
669        fn data(events: &[Event]) -> Vec<Vec<u8>> {
670            events
671                .iter()
672                .filter_map(|e| match e {
673                    Event::Data(d) => Some(d.clone()),
674                    _ => None,
675                })
676                .collect()
677        }
678    }
679
680    fn payload(i: u8) -> Vec<u8> {
681        vec![i, 0x80, 0x00, i, i ^ 0x7E]
682    }
683
684    #[test]
685    fn delivers_in_order_both_ways() {
686        let mut p = Pair::new();
687        p.connect();
688        for i in 0..20 {
689            p.host.send(payload(i), p.now).unwrap();
690            p.ncp.send(payload(100 + i), p.now).unwrap();
691        }
692        p.settle();
693        assert_eq!(
694            Pair::data(&p.ncp_events),
695            (0..20).map(payload).collect::<Vec<_>>()
696        );
697        assert_eq!(
698            Pair::data(&p.host_events),
699            (100..120).map(payload).collect::<Vec<_>>()
700        );
701        assert_eq!(p.host.counters().tx_retransmits, 0);
702        assert!(p.host.poll_timeout().is_none());
703    }
704
705    #[test]
706    fn recovers_from_lost_frames_both_ways() {
707        let mut p = Pair::new();
708        p.connect();
709        // Lose about a quarter of the frames in each direction, pseudo-randomly.
710        fn lossy(seed: u32) -> Box<dyn FnMut(usize) -> bool> {
711            let mut state = seed;
712            Box::new(move |_| {
713                state ^= state << 13;
714                state ^= state >> 17;
715                state ^= state << 5;
716                state.is_multiple_of(4)
717            })
718        }
719        p.drop_to_ncp = lossy(0x1234_5678);
720        p.drop_to_host = lossy(0x9abc_def1);
721        for i in 0..30 {
722            p.host.send(payload(i), p.now).unwrap();
723            p.ncp.send(payload(100 + i), p.now).unwrap();
724        }
725        p.settle();
726        for _ in 0..2000 {
727            assert!(
728                !p.host_events.iter().any(|e| matches!(e, Event::Down(_))),
729                "{:?}",
730                p.host_events
731            );
732            if Pair::data(&p.ncp_events).len() == 30 && Pair::data(&p.host_events).len() == 30 {
733                break;
734            }
735            p.tick();
736        }
737        assert_eq!(
738            Pair::data(&p.ncp_events),
739            (0..30).map(payload).collect::<Vec<_>>()
740        );
741        assert_eq!(
742            Pair::data(&p.host_events),
743            (100..130).map(payload).collect::<Vec<_>>()
744        );
745        assert!(p.host.counters().tx_retransmits > 0);
746        assert!(p.host.is_connected() && p.ncp.is_connected());
747    }
748
749    #[test]
750    fn corrupted_frame_triggers_nak_and_resend() {
751        let mut p = Pair::new();
752        p.connect();
753        p.host.send(payload(1), p.now).unwrap();
754        // The DATA frame arrives with a bad CRC.
755        assert!(p.host.poll_transmit().is_some());
756        p.ncp.handle_bad_frame(FrameError::BadCrc, p.now);
757        p.settle();
758        assert_eq!(p.ncp.counters().tx_naks, 1);
759        assert_eq!(Pair::data(&p.ncp_events), vec![payload(1)]);
760        assert_eq!(p.host.counters().tx_retransmits, 1);
761    }
762
763    #[test]
764    fn link_goes_down_after_repeated_ack_timeouts() {
765        let mut p = Pair::new();
766        p.connect();
767        p.drop_to_ncp = Box::new(|_| true);
768        p.host.send(payload(1), p.now).unwrap();
769        p.settle();
770        for _ in 0..10 {
771            p.tick();
772        }
773        assert_eq!(
774            p.host_events.last(),
775            Some(&Event::Down(DownReason::AckTimeouts))
776        );
777        assert!(!p.host.is_connected());
778        assert_eq!(p.host.send(payload(2), p.now), Err(SendError::NotConnected));
779    }
780
781    #[test]
782    fn rst_is_retried_then_gives_up() {
783        let mut p = Pair::new();
784        p.drop_to_ncp = Box::new(|_| true);
785        p.host.reset(p.now);
786        p.settle();
787        for _ in 0..5 {
788            p.tick();
789        }
790        assert_eq!(p.sent_to_ncp, 3);
791        assert_eq!(p.host_events, vec![Event::Down(DownReason::ResetTimeout)]);
792    }
793
794    #[test]
795    fn unexpected_rstack_takes_the_link_down() {
796        let mut p = Pair::new();
797        p.connect();
798        p.host.handle_frame(
799            Frame::RstAck {
800                version: 2,
801                code: reset_code::WATCHDOG,
802            },
803            p.now,
804        );
805        assert_eq!(
806            p.host.poll_event(),
807            Some(Event::Down(DownReason::NcpReset {
808                code: reset_code::WATCHDOG
809            }))
810        );
811    }
812
813    #[test]
814    fn ack_period_adapts_within_bounds() {
815        let mut p = Pair::new();
816        p.connect();
817        for i in 0..50 {
818            p.host.send(payload(i), p.now).unwrap();
819            p.settle();
820        }
821        // Instant replies pull the period down to the minimum.
822        assert_eq!(p.host.ack_period(), Config::default().ack_time_min);
823    }
824
825    #[test]
826    fn window_limits_frames_in_flight() {
827        let mut p = Pair::new();
828        p.connect();
829        for i in 0..10 {
830            p.host.send(payload(i), p.now).unwrap();
831        }
832        let mut frames = 0;
833        while p.host.poll_transmit().is_some() {
834            frames += 1;
835        }
836        assert_eq!(frames, 3);
837    }
838}