Skip to main content

usb_stack/
endpoint.rs

1//! USB endpoint types and handles.
2//!
3//! [`Endpoint`] (and its type aliases [`EndpointIn`] / [`EndpointOut`]) provide
4//! type-safe access to an individual USB endpoint.  A class constructor receives
5//! a reference to the [`crate::bus::UsbBusAllocator`], which allocates endpoints
6//! and returns handles that borrow from that allocator.  The owned bus inside the
7//! allocator is therefore kept alive for as long as any endpoint handle exists.
8
9use core::marker::PhantomData;
10
11use crate::bus::UsbBus;
12use crate::error::UsbResult;
13
14// ─── Direction ───────────────────────────────────────────────────────────────
15
16/// Marker trait for endpoint direction.
17pub trait EndpointDir: Sized + 'static {
18    /// The concrete direction value for this marker.
19    const DIRECTION: Direction;
20}
21
22/// Direction marker for device-to-host (IN) endpoints.
23pub struct In;
24impl EndpointDir for In {
25    const DIRECTION: Direction = Direction::In;
26}
27
28/// Direction marker for host-to-device (OUT) endpoints.
29pub struct Out;
30impl EndpointDir for Out {
31    const DIRECTION: Direction = Direction::Out;
32}
33
34/// USB transfer direction (host-centric: IN = device→host, OUT = host→device).
35#[derive(Clone, Copy, PartialEq, Eq, Debug)]
36#[cfg_attr(feature = "defmt", derive(defmt::Format))]
37pub enum Direction {
38    /// Host-to-device.
39    Out = 0x00,
40    /// Device-to-host.
41    In = 0x80,
42}
43
44impl From<u8> for Direction {
45    #[inline]
46    fn from(v: u8) -> Self {
47        if v & 0x80 != 0 {
48            Direction::In
49        } else {
50            Direction::Out
51        }
52    }
53}
54
55// ─── EndpointType ─────────────────────────────────────────────────────────────
56
57/// USB endpoint transfer type.
58#[derive(Clone, Copy, PartialEq, Eq, Debug)]
59#[cfg_attr(feature = "defmt", derive(defmt::Format))]
60pub enum EndpointType {
61    /// Control endpoint — only EP0 uses this in practice.
62    Control,
63    /// Isochronous endpoint — time-critical, unreliable.
64    Isochronous {
65        /// Synchronization type.
66        synchronization: IsoSynchronization,
67        /// Usage type.
68        usage: IsoUsage,
69    },
70    /// Bulk endpoint — large, reliable, best-effort.
71    Bulk,
72    /// Interrupt endpoint — small, reliable, bounded latency.
73    Interrupt,
74}
75
76impl EndpointType {
77    /// Encode this type into the `bmAttributes` transfer-type field (USB 2.0 §9.6.6).
78    pub fn bm_attributes(self) -> u8 {
79        match self {
80            EndpointType::Control => 0b00,
81            EndpointType::Bulk => 0b10,
82            EndpointType::Interrupt => 0b11,
83            EndpointType::Isochronous {
84                synchronization,
85                usage,
86            } => {
87                let sync = match synchronization {
88                    IsoSynchronization::None => 0b00,
89                    IsoSynchronization::Asynchronous => 0b01,
90                    IsoSynchronization::Adaptive => 0b10,
91                    IsoSynchronization::Synchronous => 0b11,
92                };
93                let usg = match usage {
94                    IsoUsage::Data => 0b00,
95                    IsoUsage::Feedback => 0b01,
96                    IsoUsage::ImplicitFeedbackData => 0b10,
97                };
98                0b01 | (sync << 2) | (usg << 4)
99            }
100        }
101    }
102}
103
104/// Isochronous synchronization type (USB 2.0 §5.12.4.1).
105#[derive(Clone, Copy, PartialEq, Eq, Debug)]
106#[cfg_attr(feature = "defmt", derive(defmt::Format))]
107pub enum IsoSynchronization {
108    /// No synchronization.
109    None,
110    /// Asynchronous sink/source.
111    Asynchronous,
112    /// Adaptive sink/source.
113    Adaptive,
114    /// Synchronous sink/source.
115    Synchronous,
116}
117
118/// Isochronous usage type (USB 2.0 §9.6.6).
119#[derive(Clone, Copy, PartialEq, Eq, Debug)]
120#[cfg_attr(feature = "defmt", derive(defmt::Format))]
121pub enum IsoUsage {
122    /// Isochronous data endpoint.
123    Data,
124    /// Isochronous feedback endpoint.
125    Feedback,
126    /// Implicit feedback data endpoint.
127    ImplicitFeedbackData,
128}
129
130// ─── EndpointAddress ──────────────────────────────────────────────────────────
131
132/// Type-safe USB endpoint address (number + direction encoded in one byte).
133#[derive(Clone, Copy, PartialEq, Eq)]
134pub struct EndpointAddress(u8);
135
136impl EndpointAddress {
137    /// EP0 OUT address (control, host→device).
138    pub const EP0_OUT: EndpointAddress = EndpointAddress(0x00);
139    /// EP0 IN address (control, device→host).
140    pub const EP0_IN: EndpointAddress = EndpointAddress(0x80);
141
142    /// Construct from an endpoint number and direction.
143    #[inline]
144    pub const fn new(number: u8, direction: Direction) -> Self {
145        Self((number & 0x0f) | direction as u8)
146    }
147
148    /// Construct an OUT endpoint address.
149    #[inline]
150    pub const fn out(number: u8) -> Self {
151        Self(number & 0x0f)
152    }
153
154    /// Construct an IN endpoint address.
155    #[inline]
156    pub const fn in_(number: u8) -> Self {
157        Self((number & 0x0f) | 0x80)
158    }
159
160    /// Raw address byte.
161    #[inline]
162    pub const fn raw(self) -> u8 {
163        self.0
164    }
165
166    /// Endpoint number (0–15).
167    #[inline]
168    pub const fn number(self) -> u8 {
169        self.0 & 0x0f
170    }
171
172    /// Transfer direction.
173    #[inline]
174    pub fn direction(self) -> Direction {
175        Direction::from(self.0)
176    }
177
178    /// `true` if this is an IN (device→host) endpoint.
179    #[inline]
180    pub const fn is_in(self) -> bool {
181        self.0 & 0x80 != 0
182    }
183
184    /// `true` if this is an OUT (host→device) endpoint.
185    #[inline]
186    pub const fn is_out(self) -> bool {
187        !self.is_in()
188    }
189}
190
191impl From<u8> for EndpointAddress {
192    #[inline]
193    fn from(v: u8) -> Self {
194        Self(v)
195    }
196}
197
198impl From<EndpointAddress> for u8 {
199    #[inline]
200    fn from(a: EndpointAddress) -> Self {
201        a.0
202    }
203}
204
205impl core::fmt::Debug for EndpointAddress {
206    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
207        write!(
208            f,
209            "EP{} {}",
210            self.number(),
211            if self.is_in() { "IN" } else { "OUT" }
212        )
213    }
214}
215
216#[cfg(feature = "defmt")]
217impl defmt::Format for EndpointAddress {
218    fn format(&self, f: defmt::Formatter) {
219        defmt::write!(
220            f,
221            "EP{} {}",
222            self.number(),
223            if self.is_in() { "IN" } else { "OUT" }
224        );
225    }
226}
227
228// ─── Endpoint handle ──────────────────────────────────────────────────────────
229
230/// A handle to a specific USB endpoint.
231///
232/// The lifetime `'a` is tied to the [`crate::bus::UsbBusAllocator`] that produced
233/// this handle, ensuring the underlying bus cannot be dropped or moved while the
234/// handle is alive.
235///
236/// Use the type aliases [`EndpointIn`] and [`EndpointOut`] for convenience.
237pub struct Endpoint<'a, B: UsbBus, D: EndpointDir> {
238    /// Shared reference to the bus — valid for `'a`.
239    bus: &'a B,
240    address: EndpointAddress,
241    ep_type: EndpointType,
242    max_packet_size: u16,
243    interval: u8,
244    _dir: PhantomData<fn() -> D>,
245}
246
247impl<'a, B: UsbBus, D: EndpointDir> Endpoint<'a, B, D> {
248    /// Construct a new endpoint handle (called only by `UsbBusAllocator`).
249    pub(crate) fn new(
250        bus: &'a B,
251        address: EndpointAddress,
252        ep_type: EndpointType,
253        max_packet_size: u16,
254        interval: u8,
255    ) -> Self {
256        Self {
257            bus,
258            address,
259            ep_type,
260            max_packet_size,
261            interval,
262            _dir: PhantomData,
263        }
264    }
265
266    /// Endpoint address (number + direction).
267    #[inline]
268    pub fn address(&self) -> EndpointAddress {
269        self.address
270    }
271
272    /// Transfer type of this endpoint.
273    #[inline]
274    pub fn ep_type(&self) -> EndpointType {
275        self.ep_type
276    }
277
278    /// Maximum packet size in bytes.
279    #[inline]
280    pub fn max_packet_size(&self) -> u16 {
281        self.max_packet_size
282    }
283
284    /// Polling interval for interrupt / isochronous endpoints.
285    #[inline]
286    pub fn interval(&self) -> u8 {
287        self.interval
288    }
289
290    /// Stall this endpoint.
291    pub fn stall(&self) {
292        self.bus.set_stalled(self.address, true);
293    }
294
295    /// Clear the stall condition on this endpoint.
296    pub fn unstall(&self) {
297        self.bus.set_stalled(self.address, false);
298    }
299}
300
301/// A device-to-host (IN) endpoint handle.
302pub type EndpointIn<'a, B> = Endpoint<'a, B, In>;
303/// A host-to-device (OUT) endpoint handle.
304pub type EndpointOut<'a, B> = Endpoint<'a, B, Out>;
305
306impl<B: UsbBus> EndpointIn<'_, B> {
307    /// Write a single packet to this endpoint.
308    ///
309    /// Returns the number of bytes actually written.  If the USB peripheral's
310    /// transmit buffer is still occupied, returns [`UsbError::WouldBlock`](crate::error::UsbError::WouldBlock).
311    pub fn write(&self, data: &[u8]) -> UsbResult<usize> {
312        self.bus.write(self.address, data)
313    }
314}
315
316impl<B: UsbBus> EndpointOut<'_, B> {
317    /// Read a single packet from this endpoint into `buf`.
318    ///
319    /// Returns the number of bytes read.  Returns [`UsbError::WouldBlock`](crate::error::UsbError::WouldBlock) when
320    /// no packet is available.
321    pub fn read(&self, buf: &mut [u8]) -> UsbResult<usize> {
322        self.bus.read(self.address, buf)
323    }
324}
325
326// Safety: Endpoint<'a, B, D> is Send/Sync if B is Send/Sync; the shared &'a B
327// is sound because the bus uses interior mutability for hardware state.
328unsafe impl<B: UsbBus + Sync, D: EndpointDir> Sync for Endpoint<'_, B, D> {}
329unsafe impl<B: UsbBus + Send, D: EndpointDir> Send for Endpoint<'_, B, D> {}