1use 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
39mod 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#[derive(Clone, Copy, Debug)]
52#[cfg_attr(feature = "defmt", derive(defmt::Format))]
53pub struct LineCoding {
54 pub baud_rate: u32,
56 pub stop_bits: u8,
58 pub parity: u8,
60 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
102pub 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 needs_zlp: Cell<bool>,
120}
121
122impl<'a, B: UsbBus> CdcAcm<'a, B> {
123 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 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 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 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 #[inline]
214 fn max_packet(&self) -> usize {
215 self.bulk_in.max_packet_size() as usize
216 }
217
218 #[inline]
220 pub fn communication_interface(&self) -> InterfaceNumber {
221 self.comm_if
222 }
223
224 #[inline]
226 pub fn data_interface(&self) -> InterfaceNumber {
227 self.data_if
228 }
229
230 pub fn dtr(&self) -> bool {
232 self.dtr
233 }
234
235 pub fn rts(&self) -> bool {
237 self.rts
238 }
239
240 pub fn port_open(&self) -> bool {
242 self.configured && self.dtr
243 }
244
245 pub fn configured(&self) -> bool {
247 self.configured
248 }
249
250 pub fn line_coding(&self) -> LineCoding {
252 self.line_coding
253 }
254}
255
256impl<B: UsbBus> UsbClass<B> for CdcAcm<'_, B> {
259 fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
260 w.iad(
262 self.comm_if,
263 2, class_code::CDC,
265 cdc_subclass::ACM,
266 cdc_protocol::NONE,
267 )?;
268
269 w.interface(
271 self.comm_if,
272 1, class_code::CDC,
274 cdc_subclass::ACM,
275 cdc_protocol::NONE,
276 )?;
277
278 w.write(
280 cdc_descriptor::CS_INTERFACE,
281 &[cdc_descriptor::HEADER, 0x10, 0x01], )?;
283 w.write(
285 cdc_descriptor::CS_INTERFACE,
286 &[
287 cdc_descriptor::CALL_MANAGEMENT,
288 0x00, self.data_if.into(),
290 ],
291 )?;
292 w.write(
294 cdc_descriptor::CS_INTERFACE,
295 &[
296 cdc_descriptor::ABSTRACT_CONTROL_MANAGEMENT,
297 0x02, ],
299 )?;
300 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 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 w.interface(
319 self.data_if,
320 2, 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 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 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}