divecomputer_core/transport.rs
1//! Transport traits that protocols are written against.
2//!
3//! Protocols are `async` and generic over these traits, so the same protocol code runs on
4//! every backend: native serial, USB and Bluetooth stacks, and the browser's Web Serial,
5//! WebUSB, WebHID and Web Bluetooth APIs. Each trait describes one kind of link; a
6//! protocol asks for exactly the kind it needs. See the
7//! [transport documents](https://michidk.github.io/divecomputer-rs/spec/transports/README.html).
8
9// The traits have no `Send` bound because browser futures are not `Send`; whether to add
10// `Send` variants is an open decision in ARCHITECTURE.md.
11#![allow(async_fn_in_trait)]
12
13use alloc::vec::Vec;
14use core::time::Duration;
15
16use crate::Result;
17
18/// A byte stream: serial ports, USB-serial chips, Bluetooth classic RFCOMM, or a BLE
19/// GATT link that behaves like a serial line.
20pub trait ByteStream {
21 /// Reads at least one byte into `buf` and returns how many bytes were read.
22 ///
23 /// # Errors
24 ///
25 /// [`Error::Timeout`](crate::Error::Timeout) if no byte arrives within `timeout`, or
26 /// a transport error.
27 async fn read(&mut self, buf: &mut [u8], timeout: Duration) -> Result<usize>;
28
29 /// Writes all of `data`.
30 ///
31 /// # Errors
32 ///
33 /// A transport error if the write fails.
34 async fn write(&mut self, data: &[u8]) -> Result<()>;
35
36 /// Discards any received data that has not been read yet.
37 ///
38 /// # Errors
39 ///
40 /// A transport error if the backend cannot purge.
41 async fn purge(&mut self) -> Result<()>;
42}
43
44/// A packet link that keeps message boundaries: USB HID reports, USB bulk transfers or
45/// BLE characteristic writes and notifications.
46pub trait PacketLink {
47 /// The largest packet [`send`](Self::send) accepts, in bytes. For BLE this is the
48 /// ATT MTU minus 3.
49 fn max_packet_len(&self) -> usize;
50
51 /// Sends one packet of at most [`max_packet_len`](Self::max_packet_len) bytes.
52 ///
53 /// # Errors
54 ///
55 /// A transport error if the send fails.
56 async fn send(&mut self, packet: &[u8]) -> Result<()>;
57
58 /// Receives the next packet.
59 ///
60 /// # Errors
61 ///
62 /// [`Error::Timeout`](crate::Error::Timeout) if no packet arrives within `timeout`,
63 /// or a transport error.
64 async fn receive(&mut self, timeout: Duration) -> Result<Vec<u8>>;
65
66 /// Discards any received packets that have not been read yet.
67 ///
68 /// # Errors
69 ///
70 /// A transport error if the backend cannot purge.
71 async fn purge(&mut self) -> Result<()>;
72}
73
74/// Time for protocols: native timers, the browser's `setTimeout`, or a virtual clock in
75/// tests.
76pub trait Clock {
77 /// Waits for `duration`.
78 async fn sleep(&self, duration: Duration);
79}