Skip to main content

zwave_serial/
driver.rs

1//! The Serial API link layer.
2//!
3//! [`SerialApi::start`] spawns a task that owns the port. Callers submit a
4//! [`Request`]; the task runs one exchange at a time:
5//!
6//! 1. write the frame and wait up to [`Config::ack_timeout`] for ACK; on NAK,
7//!    CAN or timeout retransmit after 100 ms, then 1.1 s, giving up after
8//!    three transmissions;
9//! 2. if a response is expected, wait for the RES frame with the same
10//!    function id;
11//! 3. if a callback is expected (and the response did not say the request
12//!    was refused), wait for the REQ frame with the same function id whose
13//!    first byte is the callback id.
14//!
15//! Every data frame from the controller is acknowledged at once (NAK when its
16//! checksum is bad). Request frames that are not the awaited callback are
17//! handed to the unsolicited channel: received commands, node information,
18//! inclusion progress, SmartStart requests.
19
20use crate::frame::{DataFrame, Frame, FrameCodec, FrameType};
21use futures_util::{SinkExt, StreamExt};
22use std::sync::atomic::{AtomicU8, Ordering};
23use std::sync::Arc;
24use std::time::Duration;
25use tokio::io::{AsyncRead, AsyncWrite};
26use tokio::sync::{mpsc, oneshot};
27use tokio::time::{sleep_until, Instant};
28use tokio_util::codec::Framed;
29use tracing::{debug, trace, warn};
30
31/// Link layer timing.
32#[derive(Debug, Clone)]
33pub struct Config {
34    /// How long to wait for ACK after a frame (1600 ms in the Host API).
35    pub ack_timeout: Duration,
36    /// Transmissions of one frame before giving up.
37    pub max_attempts: u32,
38    /// How long a partially received frame may take to complete.
39    pub byte_timeout: Duration,
40    /// Unsolicited frames buffered for the consumer before the oldest are dropped.
41    pub unsolicited_capacity: usize,
42}
43
44impl Default for Config {
45    fn default() -> Self {
46        Config {
47            ack_timeout: Duration::from_millis(1600),
48            max_attempts: 3,
49            byte_timeout: Duration::from_millis(150),
50            unsolicited_capacity: 512,
51        }
52    }
53}
54
55/// One exchange with the controller.
56#[derive(Debug, Clone)]
57pub struct Request {
58    /// The frame to send.
59    pub frame: DataFrame,
60    /// Wait this long for a response frame; `None` when none comes.
61    pub response: Option<Duration>,
62    /// Wait this long for the callback with this id; `None` when none comes.
63    pub callback: Option<(u8, Duration)>,
64    /// Given the response, whether a callback will follow (e.g. SendData's
65    /// "accepted" byte). Defaults to the first response byte being non-zero.
66    pub callback_follows: fn(&DataFrame) -> bool,
67}
68
69fn first_byte_nonzero(f: &DataFrame) -> bool {
70    f.payload.first().is_some_and(|&b| b != 0)
71}
72
73impl Request {
74    /// A request that expects only a response.
75    pub fn with_response(frame: DataFrame, timeout: Duration) -> Self {
76        Request {
77            frame,
78            response: Some(timeout),
79            callback: None,
80            callback_follows: first_byte_nonzero,
81        }
82    }
83
84    /// A request that expects only an ACK.
85    pub fn ack_only(frame: DataFrame) -> Self {
86        Request {
87            frame,
88            response: None,
89            callback: None,
90            callback_follows: first_byte_nonzero,
91        }
92    }
93
94    /// A request that expects a response and then a callback.
95    pub fn with_callback(
96        frame: DataFrame,
97        response: Duration,
98        callback_id: u8,
99        callback: Duration,
100    ) -> Self {
101        Request {
102            frame,
103            response: Some(response),
104            callback: Some((callback_id, callback)),
105            callback_follows: first_byte_nonzero,
106        }
107    }
108}
109
110/// What came back from an exchange.
111#[derive(Debug, Clone, PartialEq, Eq, Default)]
112pub struct Exchange {
113    /// The response frame, if one was expected.
114    pub response: Option<DataFrame>,
115    /// The callback frame, if one was expected and the request was accepted.
116    pub callback: Option<DataFrame>,
117}
118
119/// Link layer failures.
120#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
121pub enum SerialError {
122    /// No ACK after every transmission.
123    #[error("no ACK from the controller after {0} attempts")]
124    NoAck(u32),
125    /// The controller kept answering NAK or CAN.
126    #[error("controller rejected the frame {0} times")]
127    Rejected(u32),
128    /// No response in time.
129    #[error("no response from the controller")]
130    ResponseTimeout,
131    /// No callback in time.
132    #[error("no callback from the controller")]
133    CallbackTimeout,
134    /// The port closed or failed.
135    #[error("serial port closed: {0}")]
136    Closed(String),
137}
138
139struct Job {
140    req: Request,
141    reply: oneshot::Sender<Result<Exchange, SerialError>>,
142}
143
144enum Phase {
145    Backoff { until: Instant },
146    AwaitAck { deadline: Instant },
147    AwaitResponse { deadline: Instant },
148    AwaitCallback { deadline: Instant },
149}
150
151struct Current {
152    job: Job,
153    attempts: u32,
154    nak_or_can: u32,
155    phase: Phase,
156    exchange: Exchange,
157}
158
159impl Current {
160    fn deadline(&self) -> Instant {
161        match self.phase {
162            Phase::Backoff { until } => until,
163            Phase::AwaitAck { deadline }
164            | Phase::AwaitResponse { deadline }
165            | Phase::AwaitCallback { deadline } => deadline,
166        }
167    }
168}
169
170/// A handle to the link layer task. Cloning is cheap; all clones share one port.
171#[derive(Clone, Debug)]
172pub struct SerialApi {
173    jobs: mpsc::Sender<Job>,
174    callback_id: Arc<AtomicU8>,
175    stop: Arc<tokio::sync::Notify>,
176}
177
178impl SerialApi {
179    /// Starts the link layer on `io` and returns the handle and the
180    /// unsolicited frame channel.
181    pub fn start<T>(io: T, config: Config) -> (SerialApi, mpsc::Receiver<DataFrame>)
182    where
183        T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
184    {
185        let (jobs_tx, jobs_rx) = mpsc::channel(64);
186        let (unsolicited_tx, unsolicited_rx) = mpsc::channel(config.unsolicited_capacity.max(1));
187        let stop = Arc::new(tokio::sync::Notify::new());
188        tokio::spawn(run(io, config, jobs_rx, unsolicited_tx, stop.clone()));
189        (
190            SerialApi {
191                jobs: jobs_tx,
192                callback_id: Arc::new(AtomicU8::new(0)),
193                stop,
194            },
195            unsolicited_rx,
196        )
197    }
198
199    /// The next callback id, 1 to 255 (0 means "no callback" on the wire).
200    pub fn next_callback_id(&self) -> u8 {
201        loop {
202            let id = self
203                .callback_id
204                .fetch_add(1, Ordering::Relaxed)
205                .wrapping_add(1);
206            if id != 0 {
207                return id;
208            }
209        }
210    }
211
212    /// Runs one exchange.
213    pub async fn execute(&self, req: Request) -> Result<Exchange, SerialError> {
214        let (tx, rx) = oneshot::channel();
215        self.jobs
216            .send(Job { req, reply: tx })
217            .await
218            .map_err(|_| SerialError::Closed("link task stopped".into()))?;
219        rx.await
220            .map_err(|_| SerialError::Closed("link task stopped".into()))?
221    }
222
223    /// Sends a request and returns its response frame.
224    pub async fn request(
225        &self,
226        frame: DataFrame,
227        timeout: Duration,
228    ) -> Result<DataFrame, SerialError> {
229        self.execute(Request::with_response(frame, timeout))
230            .await?
231            .response
232            .ok_or(SerialError::ResponseTimeout)
233    }
234
235    /// Whether the link task is still running.
236    pub fn is_open(&self) -> bool {
237        !self.jobs.is_closed()
238    }
239
240    /// Stops the link task and closes the port, for every clone of this
241    /// handle: the exchange in progress fails, the unsolicited channel ends,
242    /// and later requests fail with [`SerialError::Closed`].
243    pub fn close(&self) {
244        self.stop.notify_one();
245    }
246}
247
248async fn run<T>(
249    io: T,
250    config: Config,
251    mut jobs: mpsc::Receiver<Job>,
252    unsolicited: mpsc::Sender<DataFrame>,
253    stop: Arc<tokio::sync::Notify>,
254) where
255    T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
256{
257    let mut framed = Framed::new(io, FrameCodec::default());
258    // Resynchronize a controller that may be mid-frame from an earlier host.
259    if let Err(e) = framed.send(Frame::Nak).await {
260        warn!("serial write failed: {e}");
261        return;
262    }
263    let mut current: Option<Current> = None;
264    let mut partial_since: Option<Instant> = None;
265    let fail_all = |current: &mut Option<Current>, e: SerialError| {
266        if let Some(c) = current.take() {
267            let _ = c.job.reply.send(Err(e));
268        }
269    };
270
271    loop {
272        let deadline = current.as_ref().map(Current::deadline);
273        let byte_deadline = partial_since.map(|t| t + config.byte_timeout);
274        tokio::select! {
275            biased;
276            () = stop.notified() => {
277                fail_all(&mut current, SerialError::Closed("closed by the host".into()));
278                debug!("link closed");
279                return;
280            }
281            incoming = framed.next() => {
282                let frame = match incoming {
283                    Some(Ok(f)) => f,
284                    Some(Err(e)) => { fail_all(&mut current, SerialError::Closed(e.to_string())); return; }
285                    None => { fail_all(&mut current, SerialError::Closed("port closed".into())); return; }
286                };
287                partial_since = if framed.read_buffer().is_empty() { None } else { partial_since.or(Some(Instant::now())) };
288                match frame {
289                    Frame::Ack => {
290                        if let Some(c) = current.as_mut() {
291                            if matches!(c.phase, Phase::AwaitAck { .. }) {
292                                after_ack(c);
293                            }
294                        }
295                    }
296                    Frame::Nak | Frame::Can => {
297                        if let Some(c) = current.as_mut() {
298                            if matches!(c.phase, Phase::AwaitAck { .. }) {
299                                c.nak_or_can += 1;
300                                debug!(attempt = c.attempts, "controller sent {frame:?}");
301                                if c.attempts >= config.max_attempts {
302                                    let n = c.attempts;
303                                    fail_all(&mut current, SerialError::Rejected(n));
304                                } else {
305                                    c.phase = Phase::Backoff { until: Instant::now() + backoff(c.attempts) };
306                                }
307                            }
308                        }
309                    }
310                    Frame::Invalid => {
311                        debug!("frame with bad checksum, sending NAK");
312                        if framed.send(Frame::Nak).await.is_err() { fail_all(&mut current, SerialError::Closed("write failed".into())); return; }
313                    }
314                    Frame::Data(df) => {
315                        if let Err(e) = framed.send(Frame::Ack).await {
316                            fail_all(&mut current, SerialError::Closed(e.to_string()));
317                            return;
318                        }
319                        trace!(kind = ?df.kind, function = df.function, len = df.payload.len(), "rx");
320                        let consumed = match current.as_mut() {
321                            Some(c) => offer(c, &df),
322                            None => false,
323                        };
324                        if !consumed {
325                            if df.kind == FrameType::Request {
326                                if unsolicited.try_send(df).is_err() {
327                                    warn!("unsolicited frame dropped: consumer is not keeping up");
328                                }
329                            } else {
330                                debug!(function = df.function, "unexpected response frame dropped");
331                            }
332                        }
333                        if current.as_ref().is_some_and(|c| c.exchange_done()) {
334                            let c = current.take().expect("checked");
335                            let _ = c.job.reply.send(Ok(c.exchange));
336                        }
337                    }
338                }
339                if current.as_ref().is_some_and(|c| c.exchange_done()) {
340                    let c = current.take().expect("checked");
341                    let _ = c.job.reply.send(Ok(c.exchange));
342                }
343            }
344            _ = async { sleep_until(byte_deadline.expect("guarded")).await }, if byte_deadline.is_some() => {
345                debug!("partial frame timed out");
346                let mut codec = FrameCodec::default();
347                codec.reset(framed.read_buffer_mut());
348                partial_since = None;
349                let _ = framed.send(Frame::Nak).await;
350            }
351            _ = async { sleep_until(deadline.expect("guarded")).await }, if deadline.is_some() => {
352                let c = current.as_mut().expect("deadline implies current");
353                match c.phase {
354                    Phase::Backoff { .. } => {
355                        c.attempts += 1;
356                        c.phase = Phase::AwaitAck { deadline: Instant::now() + config.ack_timeout };
357                        if framed.send(Frame::Data(c.job.req.frame.clone())).await.is_err() {
358                            fail_all(&mut current, SerialError::Closed("write failed".into()));
359                            return;
360                        }
361                    }
362                    Phase::AwaitAck { .. } => {
363                        debug!(attempt = c.attempts, "no ACK");
364                        if c.attempts >= config.max_attempts {
365                            let n = c.attempts;
366                            let e = if c.nak_or_can > 0 { SerialError::Rejected(n) } else { SerialError::NoAck(n) };
367                            fail_all(&mut current, e);
368                        } else {
369                            c.phase = Phase::Backoff { until: Instant::now() + backoff(c.attempts) };
370                        }
371                    }
372                    Phase::AwaitResponse { .. } => fail_all(&mut current, SerialError::ResponseTimeout),
373                    Phase::AwaitCallback { .. } => fail_all(&mut current, SerialError::CallbackTimeout),
374                }
375            }
376            job = jobs.recv(), if current.is_none() => {
377                // Every handle is gone: stop, closing the port.
378                let Some(job) = job else { return; };
379                trace!(function = job.req.frame.function, len = job.req.frame.payload.len(), "tx");
380                if let Err(e) = framed.send(Frame::Data(job.req.frame.clone())).await {
381                    let _ = job.reply.send(Err(SerialError::Closed(e.to_string())));
382                    return;
383                }
384                current = Some(Current {
385                    job,
386                    attempts: 1,
387                    nak_or_can: 0,
388                    phase: Phase::AwaitAck { deadline: Instant::now() + config.ack_timeout },
389                    exchange: Exchange::default(),
390                });
391            }
392            else => return,
393        }
394    }
395}
396
397fn backoff(attempts: u32) -> Duration {
398    Duration::from_millis(100 + 1000 * u64::from(attempts.saturating_sub(1)))
399}
400
401fn after_ack(c: &mut Current) {
402    let now = Instant::now();
403    c.phase = if let Some(t) = c.job.req.response {
404        Phase::AwaitResponse { deadline: now + t }
405    } else if let Some((_, t)) = c.job.req.callback {
406        Phase::AwaitCallback { deadline: now + t }
407    } else {
408        // Nothing more to wait for; exchange_done() completes it.
409        Phase::AwaitCallback { deadline: now }
410    };
411}
412
413impl Current {
414    fn exchange_done(&self) -> bool {
415        let req = &self.job.req;
416        if matches!(self.phase, Phase::AwaitAck { .. } | Phase::Backoff { .. }) {
417            return false;
418        }
419        if req.response.is_some() && self.exchange.response.is_none() {
420            return false;
421        }
422        match (req.callback, &self.exchange.response) {
423            (None, _) => true,
424            (Some(_), Some(r)) if !(req.callback_follows)(r) => true,
425            (Some(_), _) => self.exchange.callback.is_some(),
426        }
427    }
428}
429
430/// Offers a received frame to the exchange in progress; true if consumed.
431fn offer(c: &mut Current, df: &DataFrame) -> bool {
432    let func = c.job.req.frame.function;
433    let response = c.job.req.response;
434    let callback = c.job.req.callback;
435    let callback_follows = c.job.req.callback_follows;
436    match df.kind {
437        FrameType::Response
438            if df.function == func && response.is_some() && c.exchange.response.is_none() =>
439        {
440            // A response implies the ACK was sent even if we missed it.
441            if matches!(c.phase, Phase::AwaitAck { .. } | Phase::Backoff { .. }) {
442                after_ack(c);
443            }
444            c.exchange.response = Some(df.clone());
445            if let Some((_, t)) = callback {
446                if callback_follows(df) {
447                    c.phase = Phase::AwaitCallback {
448                        deadline: Instant::now() + t,
449                    };
450                }
451            }
452            true
453        }
454        FrameType::Request => match callback {
455            Some((id, _))
456                if df.function == func
457                    && df.payload.first() == Some(&id)
458                    && matches!(c.phase, Phase::AwaitCallback { .. })
459                    && (response.is_none() || c.exchange.response.is_some()) =>
460            {
461                c.exchange.callback = Some(df.clone());
462                true
463            }
464            _ => false,
465        },
466        _ => false,
467    }
468}