From 2ce435dc341c0238392df5dab5db9b80db167117 Mon Sep 17 00:00:00 2001 From: alexmoon Date: Sat, 2 Apr 2022 16:35:03 -0400 Subject: Add basic device state handling for endpoints. --- examples/nrf/src/bin/usb_serial.rs | 46 ++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 7 deletions(-) (limited to 'examples') diff --git a/examples/nrf/src/bin/usb_serial.rs b/examples/nrf/src/bin/usb_serial.rs index cd681c5ce..9437e835f 100644 --- a/examples/nrf/src/bin/usb_serial.rs +++ b/examples/nrf/src/bin/usb_serial.rs @@ -4,12 +4,13 @@ #![feature(type_alias_impl_trait)] use core::mem; -use defmt::*; +use defmt::{info, panic}; use embassy::executor::Spawner; use embassy_nrf::interrupt; use embassy_nrf::pac; -use embassy_nrf::usb::Driver; +use embassy_nrf::usb::{Driver, Instance}; use embassy_nrf::Peripherals; +use embassy_usb::driver::{ReadError, WriteError}; use embassy_usb::{Config, UsbDeviceBuilder}; use embassy_usb_serial::{CdcAcmClass, State}; use futures::future::join; @@ -66,12 +67,11 @@ async fn main(_spawner: Spawner, p: Peripherals) { // Do stuff with the class! let echo_fut = async { - let mut buf = [0; 64]; loop { - let n = class.read_packet(&mut buf).await.unwrap(); - let data = &buf[..n]; - info!("data: {:x}", data); - class.write_packet(data).await.unwrap(); + class.wait_connection().await; + info!("Connected"); + let _ = echo(&mut class).await; + info!("Disconnected"); } }; @@ -79,3 +79,35 @@ async fn main(_spawner: Spawner, p: Peripherals) { // If we had made everything `'static` above instead, we could do this using separate tasks instead. join(usb_fut, echo_fut).await; } + +struct Disconnected {} + +impl From for Disconnected { + fn from(val: ReadError) -> Self { + match val { + ReadError::BufferOverflow => panic!("Buffer overflow"), + ReadError::Disabled => Disconnected {}, + } + } +} + +impl From for Disconnected { + fn from(val: WriteError) -> Self { + match val { + WriteError::BufferOverflow => panic!("Buffer overflow"), + WriteError::Disabled => Disconnected {}, + } + } +} + +async fn echo<'d, T: Instance + 'd>( + class: &mut CdcAcmClass<'d, Driver<'d, T>>, +) -> Result<(), Disconnected> { + let mut buf = [0; 64]; + loop { + let n = class.read_packet(&mut buf).await?; + let data = &buf[..n]; + info!("data: {:x}", data); + class.write_packet(data).await?; + } +} -- cgit