Skip to main content

usb_stack/device/class/
cdc_acm.rs

1//! CDC ACM (USB Communication Device Class – Abstract Control Model).
2//!
3//! Creates a virtual serial port visible to the host operating system.
4//!
5//! # Example
6//!
7//! ```ignore
8//! use my_hal_usb::{UsbBusAllocator, UsbDeviceBuilder};
9//! use my_hal_usb::class::cdc_acm::CdcAcm;
10//! use my_hal_usb::MyBus;
11//!
12//! let alloc = UsbBusAllocator::new(MyBus::new(/* peripheral */));
13//! let mut serial = CdcAcm::new(&alloc);
14//! let mut dev = UsbDeviceBuilder::new(&alloc, 0x1234, 0x5678)
15//!     .product("CDC Serial")
16//!     .composite_with_iads()
17//!     .build();
18//!
19//! loop {
20//!     dev.poll(&mut [&mut serial]);
21//!     let mut buf = [0u8; 64];
22//!     if let Ok(n) = serial.read(&mut buf) {
23//!         let _ = serial.write(&buf[..n]);
24//!     }
25//! }
26//! ```
27
28use core::cell::Cell;
29
30use crate::descriptor::{cdc_descriptor, cdc_protocol, cdc_subclass, class_code};
31use crate::device::bus::{InterfaceNumber, UsbBus, UsbBusAllocator};
32use crate::device::class::UsbClass;
33use crate::device::control::{ControlIn, ControlOut};
34use crate::device::descriptor::DescriptorWriter;
35use crate::device::endpoint::{EndpointIn, EndpointOut};
36use crate::device::error::{UsbError, UsbResult};
37use crate::request::{Recipient, RequestType};
38
39// ─── CDC-ACM request codes ────────────────────────────────────────────────────
40
41mod req {
42    pub const SET_LINE_CODING: u8 = 0x20;
43    pub const GET_LINE_CODING: u8 = 0x21;
44    pub const SET_CONTROL_LINE_STATE: u8 = 0x22;
45    pub const SEND_BREAK: u8 = 0x23;
46}
47
48// ─── LineCoding ───────────────────────────────────────────────────────────────
49
50/// Serial port line-coding parameters (7-byte CDC structure).
51#[derive(Clone, Copy, Debug)]
52#[cfg_attr(feature = "defmt", derive(defmt::Format))]
53pub struct LineCoding {
54    /// Data terminal rate in bits per second.
55    pub baud_rate: u32,
56    /// Stop bits: 0 = 1 bit, 1 = 1.5 bits, 2 = 2 bits.
57    pub stop_bits: u8,
58    /// Parity: 0 = None, 1 = Odd, 2 = Even, 3 = Mark, 4 = Space.
59    pub parity: u8,
60    /// Data bits: 5, 6, 7, 8, or 16.
61    pub data_bits: u8,
62}
63
64impl Default for LineCoding {
65    fn default() -> Self {
66        Self {
67            baud_rate: 115_200,
68            stop_bits: 0,
69            parity: 0,
70            data_bits: 8,
71        }
72    }
73}
74
75impl LineCoding {
76    fn to_bytes(self) -> [u8; 7] {
77        let b = self.baud_rate.to_le_bytes();
78        [
79            b[0],
80            b[1],
81            b[2],
82            b[3],
83            self.stop_bits,
84            self.parity,
85            self.data_bits,
86        ]
87    }
88
89    fn from_bytes(b: &[u8]) -> Option<Self> {
90        if b.len() < 7 {
91            return None;
92        }
93        Some(Self {
94            baud_rate: u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
95            stop_bits: b[4],
96            parity: b[5],
97            data_bits: b[6],
98        })
99    }
100}
101
102// ─── CdcAcm ───────────────────────────────────────────────────────────────────
103
104/// CDC ACM virtual serial port class.
105///
106/// Construct with [`CdcAcm::new`], passing the [`UsbBusAllocator`].
107pub struct CdcAcm<'a, B: UsbBus> {
108    comm_if: InterfaceNumber,
109    data_if: InterfaceNumber,
110    int_in: EndpointIn<'a, B>,
111    bulk_in: EndpointIn<'a, B>,
112    bulk_out: EndpointOut<'a, B>,
113    line_coding: LineCoding,
114    dtr: bool,
115    rts: bool,
116    configured: bool,
117    /// The last packet queued was a full-size one, so the transfer still needs
118    /// its terminating zero-length packet (sent from [`UsbClass::poll`]).
119    needs_zlp: Cell<bool>,
120}
121
122impl<'a, B: UsbBus> CdcAcm<'a, B> {
123    /// Create a CDC ACM instance, allocating the required endpoints and interfaces.
124    ///
125    /// Bulk endpoints use the bus's [`UsbBus::MAX_PACKET_SIZE`] (64 bytes on
126    /// full-speed buses, 512 on high-speed ones).
127    pub fn new(alloc: &'a UsbBusAllocator<B>) -> Self {
128        let comm_if = alloc.interface();
129        let data_if = alloc.interface();
130        let int_in = alloc.interrupt(8, 16);
131        let bulk_size = B::MAX_PACKET_SIZE;
132        let bulk_in = alloc.bulk(bulk_size);
133        let bulk_out = alloc.bulk(bulk_size);
134        Self {
135            comm_if,
136            data_if,
137            int_in,
138            bulk_in,
139            bulk_out,
140            line_coding: LineCoding::default(),
141            dtr: false,
142            rts: false,
143            configured: false,
144            needs_zlp: Cell::new(false),
145        }
146    }
147
148    // ── Public API ────────────────────────────────────────────────────────────
149
150    /// Read received bytes from the host into `buf`.
151    ///
152    /// Returns the number of bytes read, or [`UsbError::WouldBlock`] when no
153    /// data is available.
154    pub fn read(&self, buf: &mut [u8]) -> UsbResult<usize> {
155        if !self.configured {
156            return Err(UsbError::InvalidState);
157        }
158        self.bulk_out.read(buf)
159    }
160
161    /// Write one packet to the host.
162    ///
163    /// Returns the number of bytes actually written, or [`UsbError::WouldBlock`]
164    /// when the previous packet has not yet been sent.
165    ///
166    /// A bulk transfer ends on a short packet. When `data` is exactly the
167    /// maximum packet size the class sends the terminating zero-length packet
168    /// itself, from the next [`UsbClass::poll`]; the caller does not have to.
169    pub fn write(&self, data: &[u8]) -> UsbResult<usize> {
170        if !self.configured {
171            return Err(UsbError::InvalidState);
172        }
173        let written = self.bulk_in.write(data)?;
174        self.needs_zlp.set(written == self.max_packet());
175        Ok(written)
176    }
177
178    /// Queue `data`, splitting it into endpoint-sized packets.
179    ///
180    /// While the endpoint is busy the call spins, spending one unit of `budget`
181    /// per attempt; the budget bounds the time spent waiting for a host that is
182    /// not collecting. Returns the number of bytes queued.
183    ///
184    /// As with [`write`](Self::write), a payload that ends on a full packet is
185    /// terminated with a zero-length packet from the next [`UsbClass::poll`];
186    /// an empty `data` queues nothing but that terminator, flushing a
187    /// previously queued full packet.
188    pub fn write_all(&self, data: &[u8], mut budget: u32) -> usize {
189        if !self.configured {
190            return 0;
191        }
192        let max_packet = self.max_packet();
193        let mut sent = 0;
194        while sent < data.len() {
195            let end = (sent + max_packet).min(data.len());
196            loop {
197                match self.bulk_in.write(&data[sent..end]) {
198                    Ok(_) => break,
199                    Err(UsbError::WouldBlock) if budget > 0 => {
200                        budget -= 1;
201                        core::hint::spin_loop();
202                    }
203                    Err(_) => return sent,
204                }
205            }
206            sent = end;
207        }
208        self.needs_zlp.set(sent % max_packet == 0);
209        sent
210    }
211
212    /// Maximum packet size of the bulk IN endpoint.
213    #[inline]
214    fn max_packet(&self) -> usize {
215        self.bulk_in.max_packet_size() as usize
216    }
217
218    /// The communication interface number.
219    #[inline]
220    pub fn communication_interface(&self) -> InterfaceNumber {
221        self.comm_if
222    }
223
224    /// The data interface number.
225    #[inline]
226    pub fn data_interface(&self) -> InterfaceNumber {
227        self.data_if
228    }
229
230    /// `true` if the host has opened the serial port (DTR set).
231    pub fn dtr(&self) -> bool {
232        self.dtr
233    }
234
235    /// `true` if the host has asserted RTS.
236    pub fn rts(&self) -> bool {
237        self.rts
238    }
239
240    /// `true` if the device is configured and the host has opened the serial port.
241    pub fn port_open(&self) -> bool {
242        self.configured && self.dtr
243    }
244
245    /// `true` if the device has been configured by the host.
246    pub fn configured(&self) -> bool {
247        self.configured
248    }
249
250    /// Returns the current line coding (baud rate, data bits, etc.).
251    pub fn line_coding(&self) -> LineCoding {
252        self.line_coding
253    }
254}
255
256// ─── UsbClass<B> implementation ───────────────────────────────────────────────
257
258impl<B: UsbBus> UsbClass<B> for CdcAcm<'_, B> {
259    fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
260        // ── IAD (Interface Association Descriptor) ────────────────────────────
261        w.iad(
262            self.comm_if,
263            2, // 2 interfaces
264            class_code::CDC,
265            cdc_subclass::ACM,
266            cdc_protocol::NONE,
267        )?;
268
269        // ── Communication Interface ───────────────────────────────────────────
270        w.interface(
271            self.comm_if,
272            1, // 1 endpoint (interrupt IN)
273            class_code::CDC,
274            cdc_subclass::ACM,
275            cdc_protocol::NONE,
276        )?;
277
278        // Header functional descriptor.
279        w.write(
280            cdc_descriptor::CS_INTERFACE,
281            &[cdc_descriptor::HEADER, 0x10, 0x01], // bcdCDC 1.10
282        )?;
283        // Call Management functional descriptor.
284        w.write(
285            cdc_descriptor::CS_INTERFACE,
286            &[
287                cdc_descriptor::CALL_MANAGEMENT,
288                0x00, // bmCapabilities: no call management
289                self.data_if.into(),
290            ],
291        )?;
292        // ACM functional descriptor.
293        w.write(
294            cdc_descriptor::CS_INTERFACE,
295            &[
296                cdc_descriptor::ABSTRACT_CONTROL_MANAGEMENT,
297                0x02, // bmCapabilities: supports SetLineCoding/GetLineCoding/SetControlLineState
298            ],
299        )?;
300        // Union functional descriptor.
301        w.write(
302            cdc_descriptor::CS_INTERFACE,
303            &[
304                cdc_descriptor::UNION,
305                self.comm_if.into(),
306                self.data_if.into(),
307            ],
308        )?;
309        // Interrupt IN endpoint.
310        w.endpoint(
311            self.int_in.address(),
312            self.int_in.ep_type(),
313            self.int_in.max_packet_size(),
314            self.int_in.interval(),
315        )?;
316
317        // ── Data Interface ────────────────────────────────────────────────────
318        w.interface(
319            self.data_if,
320            2, // 2 endpoints (bulk IN + OUT)
321            class_code::CDC_DATA,
322            0x00,
323            0x00,
324        )?;
325        w.endpoint(
326            self.bulk_out.address(),
327            self.bulk_out.ep_type(),
328            self.bulk_out.max_packet_size(),
329            0,
330        )?;
331        w.endpoint(
332            self.bulk_in.address(),
333            self.bulk_in.ep_type(),
334            self.bulk_in.max_packet_size(),
335            0,
336        )?;
337
338        Ok(())
339    }
340
341    fn control_in(&mut self, xfer: ControlIn<'_, B>) {
342        let req = xfer.request();
343
344        if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
345            return;
346        }
347        if req.index as u8 != u8::from(self.comm_if) {
348            return;
349        }
350
351        match req.request {
352            req::GET_LINE_CODING => {
353                let bytes = self.line_coding.to_bytes();
354                let _ = xfer.accept_with(&bytes);
355            }
356            _ => {
357                let _ = xfer.reject();
358            }
359        }
360    }
361
362    fn control_out(&mut self, xfer: ControlOut<'_, B>) {
363        let req = xfer.request();
364
365        if req.request_type != RequestType::Class || req.recipient != Recipient::Interface {
366            return;
367        }
368        if req.index as u8 != u8::from(self.comm_if) {
369            return;
370        }
371
372        match req.request {
373            req::SET_LINE_CODING => {
374                if let Some(lc) = LineCoding::from_bytes(xfer.data()) {
375                    self.line_coding = lc;
376                    #[cfg(feature = "defmt")]
377                    crate::log::debug!("CDC: SET_LINE_CODING baud={}", lc.baud_rate);
378                }
379                let _ = xfer.accept();
380            }
381            req::SET_CONTROL_LINE_STATE => {
382                let value = req.value;
383                self.dtr = value & 0x01 != 0;
384                self.rts = value & 0x02 != 0;
385                #[cfg(feature = "defmt")]
386                crate::log::debug!("CDC: control line state dtr={} rts={}", self.dtr, self.rts);
387                let _ = xfer.accept();
388            }
389            req::SEND_BREAK => {
390                // Ignore break signals (no hardware support).
391                let _ = xfer.accept();
392            }
393            _ => {
394                let _ = xfer.reject();
395            }
396        }
397    }
398
399    fn configure(&mut self) {
400        self.configured = true;
401    }
402
403    fn deconfigure(&mut self) {
404        self.configured = false;
405        self.needs_zlp.set(false);
406    }
407
408    fn reset(&mut self) {
409        self.configured = false;
410        self.dtr = false;
411        self.rts = false;
412        self.needs_zlp.set(false);
413    }
414
415    /// Terminate a transfer that ended on a full-size packet.
416    ///
417    /// The host keeps a bulk IN transfer open until it sees a short packet, so
418    /// a full packet on its own is not delivered to the application yet (Linux
419    /// `cdc_acm`, for example, hands an URB over only once it is full).
420    fn poll(&mut self) {
421        if !self.needs_zlp.get() {
422            return;
423        }
424        match self.bulk_in.write(&[]) {
425            Ok(_) => self.needs_zlp.set(false),
426            Err(UsbError::WouldBlock) => {}
427            Err(_) => self.needs_zlp.set(false),
428        }
429    }
430}