usb-stack 0.3.0

MCU-independent USB device and host stack core: bus traits, control transfers, enumeration, classes (CDC-ACM, HID, GS_USB, i2c-tiny-usb, UAC 1.0) and a HID host
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! CDC ACM (USB Communication Device Class – Abstract Control Model).
//!
//! Creates a virtual serial port visible to the host operating system.
//!
//! # Example
//!
//! ```ignore
//! use my_hal_usb::{UsbBusAllocator, UsbDeviceBuilder};
//! use my_hal_usb::class::cdc_acm::CdcAcm;
//! use my_hal_usb::MyBus;
//!
//! let alloc = UsbBusAllocator::new(MyBus::new(/* peripheral */));
//! let mut serial = CdcAcm::new(&alloc);
//! let mut dev = UsbDeviceBuilder::new(&alloc, 0x1234, 0x5678)
//!     .product("CDC Serial")
//!     .composite_with_iads()
//!     .build();
//!
//! loop {
//!     dev.poll(&mut [&mut serial]);
//!     let mut buf = [0u8; 64];
//!     if let Ok(n) = serial.read(&mut buf) {
//!         let _ = serial.write(&buf[..n]);
//!     }
//! }
//! ```

use core::cell::Cell;

use crate::descriptor::{cdc_descriptor, cdc_protocol, cdc_subclass, class_code};
use crate::device::bus::{InterfaceNumber, UsbBus, UsbBusAllocator};
use crate::device::class::UsbClass;
use crate::device::control::{ControlIn, ControlOut};
use crate::device::descriptor::DescriptorWriter;
use crate::device::endpoint::{EndpointIn, EndpointOut};
use crate::device::error::{UsbError, UsbResult};
use crate::request::{Recipient, RequestType};

// ─── CDC-ACM request codes ────────────────────────────────────────────────────

mod req {
    pub const SET_LINE_CODING: u8 = 0x20;
    pub const GET_LINE_CODING: u8 = 0x21;
    pub const SET_CONTROL_LINE_STATE: u8 = 0x22;
    pub const SEND_BREAK: u8 = 0x23;
}

// ─── LineCoding ───────────────────────────────────────────────────────────────

/// Serial port line-coding parameters (7-byte CDC structure).
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct LineCoding {
    /// Data terminal rate in bits per second.
    pub baud_rate: u32,
    /// Stop bits: 0 = 1 bit, 1 = 1.5 bits, 2 = 2 bits.
    pub stop_bits: u8,
    /// Parity: 0 = None, 1 = Odd, 2 = Even, 3 = Mark, 4 = Space.
    pub parity: u8,
    /// Data bits: 5, 6, 7, 8, or 16.
    pub data_bits: u8,
}

impl Default for LineCoding {
    fn default() -> Self {
        Self {
            baud_rate: 115_200,
            stop_bits: 0,
            parity: 0,
            data_bits: 8,
        }
    }
}

impl LineCoding {
    fn to_bytes(self) -> [u8; 7] {
        let b = self.baud_rate.to_le_bytes();
        [
            b[0],
            b[1],
            b[2],
            b[3],
            self.stop_bits,
            self.parity,
            self.data_bits,
        ]
    }

    fn from_bytes(b: &[u8]) -> Option<Self> {
        if b.len() < 7 {
            return None;
        }
        Some(Self {
            baud_rate: u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
            stop_bits: b[4],
            parity: b[5],
            data_bits: b[6],
        })
    }
}

// ─── CdcAcm ───────────────────────────────────────────────────────────────────

/// CDC ACM virtual serial port class.
///
/// Construct with [`CdcAcm::new`], passing the [`UsbBusAllocator`].
pub struct CdcAcm<'a, B: UsbBus> {
    comm_if: InterfaceNumber,
    data_if: InterfaceNumber,
    int_in: EndpointIn<'a, B>,
    bulk_in: EndpointIn<'a, B>,
    bulk_out: EndpointOut<'a, B>,
    line_coding: LineCoding,
    dtr: bool,
    rts: bool,
    configured: bool,
    /// The last packet queued was a full-size one, so the transfer still needs
    /// its terminating zero-length packet (sent from [`UsbClass::poll`]).
    needs_zlp: Cell<bool>,
}

impl<'a, B: UsbBus> CdcAcm<'a, B> {
    /// Create a CDC ACM instance, allocating the required endpoints and interfaces.
    ///
    /// Bulk endpoints use the bus's [`UsbBus::MAX_PACKET_SIZE`] (64 bytes on
    /// full-speed buses, 512 on high-speed ones).
    pub fn new(alloc: &'a UsbBusAllocator<B>) -> Self {
        let comm_if = alloc.interface();
        let data_if = alloc.interface();
        let int_in = alloc.interrupt(8, 16);
        let bulk_size = B::MAX_PACKET_SIZE;
        let bulk_in = alloc.bulk(bulk_size);
        let bulk_out = alloc.bulk(bulk_size);
        Self {
            comm_if,
            data_if,
            int_in,
            bulk_in,
            bulk_out,
            line_coding: LineCoding::default(),
            dtr: false,
            rts: false,
            configured: false,
            needs_zlp: Cell::new(false),
        }
    }

    // ── Public API ────────────────────────────────────────────────────────────

    /// Read received bytes from the host into `buf`.
    ///
    /// Returns the number of bytes read, or [`UsbError::WouldBlock`] when no
    /// data is available.
    pub fn read(&self, buf: &mut [u8]) -> UsbResult<usize> {
        if !self.configured {
            return Err(UsbError::InvalidState);
        }
        self.bulk_out.read(buf)
    }

    /// Write one packet to the host.
    ///
    /// Returns the number of bytes actually written, or [`UsbError::WouldBlock`]
    /// when the previous packet has not yet been sent.
    ///
    /// A bulk transfer ends on a short packet. When `data` is exactly the
    /// maximum packet size the class sends the terminating zero-length packet
    /// itself, from the next [`UsbClass::poll`]; the caller does not have to.
    pub fn write(&self, data: &[u8]) -> UsbResult<usize> {
        if !self.configured {
            return Err(UsbError::InvalidState);
        }
        let written = self.bulk_in.write(data)?;
        self.needs_zlp.set(written == self.max_packet());
        Ok(written)
    }

    /// Queue `data`, splitting it into endpoint-sized packets.
    ///
    /// While the endpoint is busy the call spins, spending one unit of `budget`
    /// per attempt; the budget bounds the time spent waiting for a host that is
    /// not collecting. Returns the number of bytes queued.
    ///
    /// As with [`write`](Self::write), a payload that ends on a full packet is
    /// terminated with a zero-length packet from the next [`UsbClass::poll`];
    /// an empty `data` queues nothing but that terminator, flushing a
    /// previously queued full packet.
    pub fn write_all(&self, data: &[u8], mut budget: u32) -> usize {
        if !self.configured {
            return 0;
        }
        let max_packet = self.max_packet();
        let mut sent = 0;
        while sent < data.len() {
            let end = (sent + max_packet).min(data.len());
            loop {
                match self.bulk_in.write(&data[sent..end]) {
                    Ok(_) => break,
                    Err(UsbError::WouldBlock) if budget > 0 => {
                        budget -= 1;
                        core::hint::spin_loop();
                    }
                    Err(_) => return sent,
                }
            }
            sent = end;
        }
        self.needs_zlp.set(sent % max_packet == 0);
        sent
    }

    /// Maximum packet size of the bulk IN endpoint.
    #[inline]
    fn max_packet(&self) -> usize {
        self.bulk_in.max_packet_size() as usize
    }

    /// The communication interface number.
    #[inline]
    pub fn communication_interface(&self) -> InterfaceNumber {
        self.comm_if
    }

    /// The data interface number.
    #[inline]
    pub fn data_interface(&self) -> InterfaceNumber {
        self.data_if
    }

    /// `true` if the host has opened the serial port (DTR set).
    pub fn dtr(&self) -> bool {
        self.dtr
    }

    /// `true` if the host has asserted RTS.
    pub fn rts(&self) -> bool {
        self.rts
    }

    /// `true` if the device is configured and the host has opened the serial port.
    pub fn port_open(&self) -> bool {
        self.configured && self.dtr
    }

    /// `true` if the device has been configured by the host.
    pub fn configured(&self) -> bool {
        self.configured
    }

    /// Returns the current line coding (baud rate, data bits, etc.).
    pub fn line_coding(&self) -> LineCoding {
        self.line_coding
    }
}

// ─── UsbClass<B> implementation ───────────────────────────────────────────────

impl<B: UsbBus> UsbClass<B> for CdcAcm<'_, B> {
    fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
        // ── IAD (Interface Association Descriptor) ────────────────────────────
        w.iad(
            self.comm_if,
            2, // 2 interfaces
            class_code::CDC,
            cdc_subclass::ACM,
            cdc_protocol::NONE,
        )?;

        // ── Communication Interface ───────────────────────────────────────────
        w.interface(
            self.comm_if,
            1, // 1 endpoint (interrupt IN)
            class_code::CDC,
            cdc_subclass::ACM,
            cdc_protocol::NONE,
        )?;

        // Header functional descriptor.
        w.write(
            cdc_descriptor::CS_INTERFACE,
            &[cdc_descriptor::HEADER, 0x10, 0x01], // bcdCDC 1.10
        )?;
        // Call Management functional descriptor.
        w.write(
            cdc_descriptor::CS_INTERFACE,
            &[
                cdc_descriptor::CALL_MANAGEMENT,
                0x00, // bmCapabilities: no call management
                self.data_if.into(),
            ],
        )?;
        // ACM functional descriptor.
        w.write(
            cdc_descriptor::CS_INTERFACE,
            &[
                cdc_descriptor::ABSTRACT_CONTROL_MANAGEMENT,
                0x02, // bmCapabilities: supports SetLineCoding/GetLineCoding/SetControlLineState
            ],
        )?;
        // Union functional descriptor.
        w.write(
            cdc_descriptor::CS_INTERFACE,
            &[
                cdc_descriptor::UNION,
                self.comm_if.into(),
                self.data_if.into(),
            ],
        )?;
        // Interrupt IN endpoint.
        w.endpoint(
            self.int_in.address(),
            self.int_in.ep_type(),
            self.int_in.max_packet_size(),
            self.int_in.interval(),
        )?;

        // ── Data Interface ────────────────────────────────────────────────────
        w.interface(
            self.data_if,
            2, // 2 endpoints (bulk IN + OUT)
            class_code::CDC_DATA,
            0x00,
            0x00,
        )?;
        w.endpoint(
            self.bulk_out.address(),
            self.bulk_out.ep_type(),
            self.bulk_out.max_packet_size(),
            0,
        )?;
        w.endpoint(
            self.bulk_in.address(),
            self.bulk_in.ep_type(),
            self.bulk_in.max_packet_size(),
            0,
        )?;

        Ok(())
    }

    fn control_in(&mut self, xfer: ControlIn<'_, B>) {
        let req = xfer.request();

        if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
            return;
        }
        if req.index as u8 != u8::from(self.comm_if) {
            return;
        }

        match req.request {
            req::GET_LINE_CODING => {
                let bytes = self.line_coding.to_bytes();
                let _ = xfer.accept_with(&bytes);
            }
            _ => {
                let _ = xfer.reject();
            }
        }
    }

    fn control_out(&mut self, xfer: ControlOut<'_, B>) {
        let req = xfer.request();

        if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
            return;
        }
        if req.index as u8 != u8::from(self.comm_if) {
            return;
        }

        match req.request {
            req::SET_LINE_CODING => {
                if let Some(lc) = LineCoding::from_bytes(xfer.data()) {
                    self.line_coding = lc;
                    #[cfg(feature = "defmt")]
                    crate::log::debug!("CDC: SET_LINE_CODING baud={}", lc.baud_rate);
                }
                let _ = xfer.accept();
            }
            req::SET_CONTROL_LINE_STATE => {
                let value = req.value;
                self.dtr = value & 0x01 != 0;
                self.rts = value & 0x02 != 0;
                #[cfg(feature = "defmt")]
                crate::log::debug!("CDC: control line state dtr={} rts={}", self.dtr, self.rts);
                let _ = xfer.accept();
            }
            req::SEND_BREAK => {
                // Ignore break signals (no hardware support).
                let _ = xfer.accept();
            }
            _ => {
                let _ = xfer.reject();
            }
        }
    }

    fn configure(&mut self) {
        self.configured = true;
    }

    fn deconfigure(&mut self) {
        self.configured = false;
        self.needs_zlp.set(false);
    }

    fn reset(&mut self) {
        self.configured = false;
        self.dtr = false;
        self.rts = false;
        self.needs_zlp.set(false);
    }

    /// Terminate a transfer that ended on a full-size packet.
    ///
    /// The host keeps a bulk IN transfer open until it sees a short packet, so
    /// a full packet on its own is not delivered to the application yet (Linux
    /// `cdc_acm`, for example, hands an URB over only once it is full).
    fn poll(&mut self) {
        if !self.needs_zlp.get() {
            return;
        }
        match self.bulk_in.write(&[]) {
            Ok(_) => self.needs_zlp.set(false),
            Err(UsbError::WouldBlock) => {}
            Err(_) => self.needs_zlp.set(false),
        }
    }
}