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