summaryrefslogtreecommitdiff
path: root/embassy-usb
diff options
context:
space:
mode:
authoralexmoon <alex.r.moon@gmail.com>2022-04-13 13:09:08 -0400
committeralexmoon <alex.r.moon@gmail.com>2022-04-13 14:55:02 -0400
commitff7c6b350e2338a0b1e4327f4b2eb0435468f313 (patch)
tree1a045db7348d2562b9c8a19299467a30b62e501e /embassy-usb
parent1d875fab2dc9d765ebf9f4b37112581301f2ed7e (diff)
downloadembassy-ff7c6b350e2338a0b1e4327f4b2eb0435468f313.zip
Remove channel and make run future cancelable
Diffstat (limited to 'embassy-usb')
-rw-r--r--embassy-usb/src/builder.rs71
-rw-r--r--embassy-usb/src/lib.rs140
-rw-r--r--embassy-usb/src/util.rs33
3 files changed, 72 insertions, 172 deletions
diff --git a/embassy-usb/src/builder.rs b/embassy-usb/src/builder.rs
index 30d31ac7..48667205 100644
--- a/embassy-usb/src/builder.rs
+++ b/embassy-usb/src/builder.rs
@@ -1,9 +1,5 @@
-use embassy::blocking_mutex::raw::{NoopRawMutex, RawMutex};
-use embassy::channel::Channel;
use heapless::Vec;
-use crate::DeviceCommand;
-
use super::control::ControlHandler;
use super::descriptor::{BosWriter, DescriptorWriter};
use super::driver::{Driver, EndpointAllocError};
@@ -98,11 +94,6 @@ pub struct Config<'a> {
/// Default: 100mA
/// Max: 500mA
pub max_power: u16,
-
- /// Whether the USB bus should be enabled when built.
- ///
- /// Default: true
- pub start_enabled: bool,
}
impl<'a> Config<'a> {
@@ -122,18 +113,16 @@ impl<'a> Config<'a> {
supports_remote_wakeup: false,
composite_with_iads: false,
max_power: 100,
- start_enabled: true,
}
}
}
/// Used to build new [`UsbDevice`]s.
-pub struct UsbDeviceBuilder<'d, D: Driver<'d>, M: RawMutex> {
+pub struct UsbDeviceBuilder<'d, D: Driver<'d>> {
config: Config<'d>,
handler: Option<&'d dyn DeviceStateHandler>,
interfaces: Vec<(u8, &'d mut dyn ControlHandler), MAX_INTERFACE_COUNT>,
control_buf: &'d mut [u8],
- commands: Option<&'d Channel<M, DeviceCommand, 1>>,
driver: D,
next_interface_number: u8,
@@ -145,7 +134,7 @@ pub struct UsbDeviceBuilder<'d, D: Driver<'d>, M: RawMutex> {
pub bos_descriptor: BosWriter<'d>,
}
-impl<'d, D: Driver<'d>> UsbDeviceBuilder<'d, D, NoopRawMutex> {
+impl<'d, D: Driver<'d>> UsbDeviceBuilder<'d, D> {
/// Creates a builder for constructing a new [`UsbDevice`].
///
/// `control_buf` is a buffer used for USB control request data. It should be sized
@@ -160,57 +149,6 @@ impl<'d, D: Driver<'d>> UsbDeviceBuilder<'d, D, NoopRawMutex> {
control_buf: &'d mut [u8],
handler: Option<&'d dyn DeviceStateHandler>,
) -> Self {
- Self::new_inner(
- driver,
- config,
- device_descriptor_buf,
- config_descriptor_buf,
- bos_descriptor_buf,
- control_buf,
- handler,
- None,
- )
- }
-}
-
-impl<'d, D: Driver<'d>, M: RawMutex> UsbDeviceBuilder<'d, D, M> {
- /// Creates a builder for constructing a new [`UsbDevice`].
- ///
- /// `control_buf` is a buffer used for USB control request data. It should be sized
- /// large enough for the length of the largest control request (in or out)
- /// anticipated by any class added to the device.
- pub fn new_with_channel(
- driver: D,
- config: Config<'d>,
- device_descriptor_buf: &'d mut [u8],
- config_descriptor_buf: &'d mut [u8],
- bos_descriptor_buf: &'d mut [u8],
- control_buf: &'d mut [u8],
- handler: Option<&'d dyn DeviceStateHandler>,
- channel: &'d Channel<M, DeviceCommand, 1>,
- ) -> Self {
- Self::new_inner(
- driver,
- config,
- device_descriptor_buf,
- config_descriptor_buf,
- bos_descriptor_buf,
- control_buf,
- handler,
- Some(channel),
- )
- }
-
- fn new_inner(
- driver: D,
- config: Config<'d>,
- device_descriptor_buf: &'d mut [u8],
- config_descriptor_buf: &'d mut [u8],
- bos_descriptor_buf: &'d mut [u8],
- control_buf: &'d mut [u8],
- handler: Option<&'d dyn DeviceStateHandler>,
- channel: Option<&'d Channel<M, DeviceCommand, 1>>,
- ) -> Self {
// Magic values specified in USB-IF ECN on IADs.
if config.composite_with_iads
&& (config.device_class != 0xEF
@@ -243,8 +181,6 @@ impl<'d, D: Driver<'d>, M: RawMutex> UsbDeviceBuilder<'d, D, M> {
config,
interfaces: Vec::new(),
control_buf,
- commands: channel,
-
next_interface_number: 0,
next_string_index: 4,
@@ -255,7 +191,7 @@ impl<'d, D: Driver<'d>, M: RawMutex> UsbDeviceBuilder<'d, D, M> {
}
/// Creates the [`UsbDevice`] instance with the configuration in this builder.
- pub fn build(mut self) -> UsbDevice<'d, D, M> {
+ pub fn build(mut self) -> UsbDevice<'d, D> {
self.config_descriptor.end_configuration();
self.bos_descriptor.end_bos();
@@ -263,7 +199,6 @@ impl<'d, D: Driver<'d>, M: RawMutex> UsbDeviceBuilder<'d, D, M> {
self.driver,
self.config,
self.handler,
- self.commands,
self.device_descriptor.into_buf(),
self.config_descriptor.into_buf(),
self.bos_descriptor.writer.into_buf(),
diff --git a/embassy-usb/src/lib.rs b/embassy-usb/src/lib.rs
index 102ccbb3..ccea8bc7 100644
--- a/embassy-usb/src/lib.rs
+++ b/embassy-usb/src/lib.rs
@@ -10,19 +10,14 @@ pub mod control;
pub mod descriptor;
pub mod driver;
pub mod types;
-mod util;
-use driver::Unsupported;
-use embassy::blocking_mutex::raw::{NoopRawMutex, RawMutex};
-use embassy::channel::Channel;
-use embassy::util::{select3, Either3};
+use embassy::util::{select, Either};
use heapless::Vec;
use self::control::*;
use self::descriptor::*;
use self::driver::{Bus, Driver, Event};
use self::types::*;
-use self::util::*;
pub use self::builder::Config;
pub use self::builder::UsbDeviceBuilder;
@@ -47,6 +42,19 @@ pub enum UsbDeviceState {
Configured,
}
+#[derive(PartialEq, Eq, Copy, Clone, Debug)]
+#[cfg_attr(feature = "defmt", derive(defmt::Format))]
+pub enum RemoteWakeupError {
+ InvalidState,
+ Unsupported,
+}
+
+impl From<driver::Unsupported> for RemoteWakeupError {
+ fn from(_: driver::Unsupported) -> Self {
+ RemoteWakeupError::Unsupported
+ }
+}
+
/// The bConfiguration value for the not configured state.
pub const CONFIGURATION_NONE: u8 = 0;
@@ -58,16 +66,11 @@ pub const DEFAULT_ALTERNATE_SETTING: u8 = 0;
pub const MAX_INTERFACE_COUNT: usize = 4;
-#[derive(PartialEq, Eq, Copy, Clone, Debug)]
-#[cfg_attr(feature = "defmt", derive(defmt::Format))]
-pub enum DeviceCommand {
- Enable,
- Disable,
- RemoteWakeup,
-}
-
/// A handler trait for changes in the device state of the [UsbDevice].
pub trait DeviceStateHandler {
+ /// Called when the USB device has been enabled or disabled.
+ fn enabled(&self, _enabled: bool) {}
+
/// Called when the host resets the device.
fn reset(&self) {}
@@ -82,15 +85,11 @@ pub trait DeviceStateHandler {
/// Called when remote wakeup feature is enabled or disabled.
fn remote_wakeup_enabled(&self, _enabled: bool) {}
-
- /// Called when the USB device has been disabled.
- fn disabled(&self) {}
}
-pub struct UsbDevice<'d, D: Driver<'d>, M: RawMutex = NoopRawMutex> {
+pub struct UsbDevice<'d, D: Driver<'d>> {
bus: D::Bus,
handler: Option<&'d dyn DeviceStateHandler>,
- commands: Option<&'d Channel<M, DeviceCommand, 1>>,
control: ControlPipe<D::ControlPipe>,
config: Config<'d>,
@@ -101,6 +100,7 @@ pub struct UsbDevice<'d, D: Driver<'d>, M: RawMutex = NoopRawMutex> {
device_state: UsbDeviceState,
suspended: bool,
+ in_control_handler: bool,
remote_wakeup_enabled: bool,
self_powered: bool,
pending_address: u8,
@@ -108,18 +108,17 @@ pub struct UsbDevice<'d, D: Driver<'d>, M: RawMutex = NoopRawMutex> {
interfaces: Vec<(u8, &'d mut dyn ControlHandler), MAX_INTERFACE_COUNT>,
}
-impl<'d, D: Driver<'d>, M: RawMutex> UsbDevice<'d, D, M> {
+impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
pub(crate) fn build(
mut driver: D,
config: Config<'d>,
handler: Option<&'d dyn DeviceStateHandler>,
- commands: Option<&'d Channel<M, DeviceCommand, 1>>,
device_descriptor: &'d [u8],
config_descriptor: &'d [u8],
bos_descriptor: &'d [u8],
interfaces: Vec<(u8, &'d mut dyn ControlHandler), MAX_INTERFACE_COUNT>,
control_buf: &'d mut [u8],
- ) -> UsbDevice<'d, D, M> {
+ ) -> UsbDevice<'d, D> {
let control = driver
.alloc_control_pipe(config.max_packet_size_0 as u16)
.expect("failed to alloc control endpoint");
@@ -132,14 +131,14 @@ impl<'d, D: Driver<'d>, M: RawMutex> UsbDevice<'d, D, M> {
bus,
config,
handler,
- commands,
control: ControlPipe::new(control),
device_descriptor,
config_descriptor,
bos_descriptor,
control_buf,
- device_state: UsbDeviceState::Default,
+ device_state: UsbDeviceState::Disabled,
suspended: false,
+ in_control_handler: false,
remote_wakeup_enabled: false,
self_powered: false,
pending_address: 0,
@@ -148,19 +147,24 @@ impl<'d, D: Driver<'d>, M: RawMutex> UsbDevice<'d, D, M> {
}
pub async fn run(&mut self) -> ! {
- if self.config.start_enabled {
+ if self.device_state == UsbDeviceState::Disabled {
self.bus.enable().await;
- } else {
- self.wait_for_enable().await
+ self.device_state = UsbDeviceState::Default;
+
+ if let Some(h) = &self.handler {
+ h.enabled(true);
+ }
+ } else if self.in_control_handler {
+ warn!("usb: control request interrupted");
+ self.control.reject();
+ self.in_control_handler = false;
}
loop {
let control_fut = self.control.setup();
let bus_fut = self.bus.poll();
- let commands_fut = recv_or_wait(self.commands);
-
- match select3(bus_fut, control_fut, commands_fut).await {
- Either3::First(evt) => match evt {
+ match select(bus_fut, control_fut).await {
+ Either::First(evt) => match evt {
Event::Reset => {
trace!("usb: reset");
self.device_state = UsbDeviceState::Default;
@@ -191,54 +195,48 @@ impl<'d, D: Driver<'d>, M: RawMutex> UsbDevice<'d, D, M> {
}
}
},
- Either3::Second(req) => match req {
- Setup::DataIn(req, stage) => self.handle_control_in(req, stage).await,
- Setup::DataOut(req, stage) => self.handle_control_out(req, stage).await,
- },
- Either3::Third(cmd) => match cmd {
- DeviceCommand::Enable => warn!("usb: Enable command received while enabled."),
- DeviceCommand::Disable => {
- trace!("usb: disable");
- self.bus.disable().await;
- self.device_state = UsbDeviceState::Disabled;
- if let Some(h) = &self.handler {
- h.disabled();
- }
- self.wait_for_enable().await;
+ Either::Second(req) => {
+ self.in_control_handler = true;
+ match req {
+ Setup::DataIn(req, stage) => self.handle_control_in(req, stage).await,
+ Setup::DataOut(req, stage) => self.handle_control_out(req, stage).await,
}
- DeviceCommand::RemoteWakeup => {
- trace!("usb: remote wakeup");
- if self.suspended && self.remote_wakeup_enabled {
- match self.bus.remote_wakeup().await {
- Ok(()) => {
- self.suspended = false;
- if let Some(h) = &self.handler {
- h.suspended(false);
- }
- }
- Err(Unsupported) => warn!("Remote wakeup is unsupported!"),
- }
- } else {
- warn!("Remote wakeup requested when not enabled or not suspended.");
- }
- }
- },
+ self.in_control_handler = false;
+ }
}
}
}
- async fn wait_for_enable(&mut self) {
- loop {
- // When disabled just wait until we're told to re-enable
- match recv_or_wait(self.commands).await {
- DeviceCommand::Enable => break,
- cmd => warn!("usb: {:?} received while disabled", cmd),
+ pub async fn disable(&mut self) {
+ if self.device_state != UsbDeviceState::Disabled {
+ self.bus.disable().await;
+ self.device_state = UsbDeviceState::Disabled;
+ self.suspended = false;
+ self.remote_wakeup_enabled = false;
+ self.in_control_handler = false;
+
+ if let Some(h) = &self.handler {
+ h.enabled(false);
}
}
+ }
+
+ pub async fn remote_wakeup(&mut self) -> Result<(), RemoteWakeupError> {
+ if self.device_state == UsbDeviceState::Configured
+ && self.suspended
+ && self.remote_wakeup_enabled
+ {
+ self.bus.remote_wakeup().await?;
+ self.suspended = false;
- trace!("usb: enable");
- self.bus.enable().await;
- self.device_state = UsbDeviceState::Default;
+ if let Some(h) = &self.handler {
+ h.suspended(false);
+ }
+
+ Ok(())
+ } else {
+ Err(RemoteWakeupError::InvalidState)
+ }
}
async fn handle_control_out(&mut self, req: Request, stage: DataOutStage) {
diff --git a/embassy-usb/src/util.rs b/embassy-usb/src/util.rs
deleted file mode 100644
index 3f20262c..00000000
--- a/embassy-usb/src/util.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-use core::future::Future;
-use core::marker::PhantomData;
-use core::pin::Pin;
-use core::task::{Context, Poll};
-
-use embassy::blocking_mutex::raw::RawMutex;
-use embassy::channel::Channel;
-
-pub struct Pending<T> {
- _phantom: PhantomData<T>,
-}
-
-impl<T> Pending<T> {
- fn new() -> Self {
- Pending {
- _phantom: PhantomData,
- }
- }
-}
-
-impl<T> Future for Pending<T> {
- type Output = T;
- fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
- Poll::Pending
- }
-}
-
-pub async fn recv_or_wait<M: RawMutex, T, const N: usize>(ch: Option<&Channel<M, T, N>>) -> T {
- match ch {
- Some(ch) => ch.recv().await,
- None => Pending::new().await,
- }
-}