Skip to main content

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