Move USB to embassy-extras

This commit is contained in:
Thales Fragoso 2021-03-18 21:30:35 -03:00
parent 615bb33dcb
commit d4f35c1729
13 changed files with 83 additions and 190 deletions

View File

@ -17,3 +17,4 @@ embassy = { version = "0.1.0", path = "../embassy" }
defmt = { version = "0.2.0", optional = true }
log = { version = "0.4.11", optional = true }
cortex-m = "0.7.1"
usb-device = "0.2.7"

View File

@ -5,6 +5,7 @@ pub(crate) mod fmt;
pub mod peripheral;
pub mod ring_buffer;
pub mod usb;
/// Low power blocking wait loop using WFE/SEV.
pub fn low_power_wait_until(mut condition: impl FnMut() -> bool) {

View File

@ -6,41 +6,48 @@ use usb_device::bus::UsbBus;
use usb_device::class::UsbClass;
use usb_device::device::UsbDevice;
use crate::interrupt;
use crate::usb_serial::{ReadInterface, UsbSerial, WriteInterface};
use embassy_extras::peripheral::{PeripheralMutex, PeripheralState};
mod cdc_acm;
pub mod usb_serial;
pub struct State<'bus, B, T>
use crate::peripheral::{PeripheralMutex, PeripheralState};
use embassy::interrupt::Interrupt;
use usb_serial::{ReadInterface, UsbSerial, WriteInterface};
/// Marker trait to mark an interrupt to be used with the [`Usb`] abstraction.
pub unsafe trait USBInterrupt: Interrupt {}
pub(crate) struct State<'bus, B, T, I>
where
B: UsbBus,
T: ClassSet<B>,
I: USBInterrupt,
{
device: UsbDevice<'bus, B>,
pub(crate) classes: T,
_interrupt: PhantomData<I>,
}
pub struct Usb<'bus, B, T>
pub struct Usb<'bus, B, T, I>
where
B: UsbBus,
T: ClassSet<B>,
I: USBInterrupt,
{
// Don't you dare moving out `PeripheralMutex`
inner: RefCell<PeripheralMutex<State<'bus, B, T>>>,
inner: RefCell<PeripheralMutex<State<'bus, B, T, I>>>,
}
impl<'bus, B, T> Usb<'bus, B, T>
impl<'bus, B, T, I> Usb<'bus, B, T, I>
where
B: UsbBus,
T: ClassSet<B>,
I: USBInterrupt,
{
pub fn new<S: IntoClassSet<B, T>>(
device: UsbDevice<'bus, B>,
class_set: S,
irq: interrupt::OTG_FS,
) -> Self {
pub fn new<S: IntoClassSet<B, T>>(device: UsbDevice<'bus, B>, class_set: S, irq: I) -> Self {
let state = State {
device,
classes: class_set.into_class_set(),
_interrupt: PhantomData,
};
let mutex = PeripheralMutex::new(state, irq);
Self {
@ -58,16 +65,18 @@ where
}
}
impl<'bus, 'c, B, T> Usb<'bus, B, T>
impl<'bus, 'c, B, T, I> Usb<'bus, B, T, I>
where
B: UsbBus,
T: ClassSet<B> + SerialState<'bus, 'c, B, Index0>,
I: USBInterrupt,
{
/// Take a serial class that was passed as the first class in a tuple
pub fn take_serial_0<'a>(
self: Pin<&'a Self>,
) -> (
ReadInterface<'a, 'bus, 'c, Index0, B, T>,
WriteInterface<'a, 'bus, 'c, Index0, B, T>,
ReadInterface<'a, 'bus, 'c, Index0, B, T, I>,
WriteInterface<'a, 'bus, 'c, Index0, B, T, I>,
) {
let this = self.get_ref();
@ -86,16 +95,18 @@ where
}
}
impl<'bus, 'c, B, T> Usb<'bus, B, T>
impl<'bus, 'c, B, T, I> Usb<'bus, B, T, I>
where
B: UsbBus,
T: ClassSet<B> + SerialState<'bus, 'c, B, Index1>,
I: USBInterrupt,
{
/// Take a serial class that was passed as the second class in a tuple
pub fn take_serial_1<'a>(
self: Pin<&'a Self>,
) -> (
ReadInterface<'a, 'bus, 'c, Index1, B, T>,
WriteInterface<'a, 'bus, 'c, Index1, B, T>,
ReadInterface<'a, 'bus, 'c, Index1, B, T, I>,
WriteInterface<'a, 'bus, 'c, Index1, B, T, I>,
) {
let this = self.get_ref();
@ -114,12 +125,13 @@ where
}
}
impl<'bus, B, T> PeripheralState for State<'bus, B, T>
impl<'bus, B, T, I> PeripheralState for State<'bus, B, T, I>
where
B: UsbBus,
T: ClassSet<B>,
I: USBInterrupt,
{
type Interrupt = interrupt::OTG_FS;
type Interrupt = I;
fn on_interrupt(&mut self) {
self.classes.poll_all(&mut self.device);
}
@ -153,7 +165,10 @@ where
_bus: PhantomData<B>,
}
/// The first class into a [`ClassSet`]
pub struct Index0;
/// The second class into a [`ClassSet`]
pub struct Index1;
impl<B, C1> ClassSet<B> for ClassSet1<B, C1>
@ -205,6 +220,7 @@ where
}
}
/// Trait for a USB State that has a serial class inside
pub trait SerialState<'bus, 'a, B: UsbBus, I> {
fn get_serial(&mut self) -> &mut UsbSerial<'bus, 'a, B>;
}

View File

@ -9,19 +9,20 @@ use usb_device::bus::UsbBus;
use usb_device::class_prelude::*;
use usb_device::UsbError;
use crate::cdc_acm::CdcAcmClass;
use crate::usb::{ClassSet, SerialState, State};
use embassy_extras::peripheral::PeripheralMutex;
use embassy_extras::ring_buffer::RingBuffer;
use super::cdc_acm::CdcAcmClass;
use crate::peripheral::PeripheralMutex;
use crate::ring_buffer::RingBuffer;
use crate::usb::{ClassSet, SerialState, State, USBInterrupt};
pub struct ReadInterface<'a, 'bus, 'c, I, B, T>
pub struct ReadInterface<'a, 'bus, 'c, I, B, T, INT>
where
I: Unpin,
B: UsbBus,
T: SerialState<'bus, 'c, B, I> + ClassSet<B>,
INT: USBInterrupt,
{
// Don't you dare moving out `PeripheralMutex`
pub(crate) inner: &'a RefCell<PeripheralMutex<State<'bus, B, T>>>,
pub(crate) inner: &'a RefCell<PeripheralMutex<State<'bus, B, T, INT>>>,
pub(crate) _buf_lifetime: PhantomData<&'c T>,
pub(crate) _index: PhantomData<I>,
}
@ -30,23 +31,25 @@ where
///
/// This interface is buffered, meaning that after the write returns the bytes might not be fully
/// on the wire just yet
pub struct WriteInterface<'a, 'bus, 'c, I, B, T>
pub struct WriteInterface<'a, 'bus, 'c, I, B, T, INT>
where
I: Unpin,
B: UsbBus,
T: SerialState<'bus, 'c, B, I> + ClassSet<B>,
INT: USBInterrupt,
{
// Don't you dare moving out `PeripheralMutex`
pub(crate) inner: &'a RefCell<PeripheralMutex<State<'bus, B, T>>>,
pub(crate) inner: &'a RefCell<PeripheralMutex<State<'bus, B, T, INT>>>,
pub(crate) _buf_lifetime: PhantomData<&'c T>,
pub(crate) _index: PhantomData<I>,
}
impl<'a, 'bus, 'c, I, B, T> AsyncBufRead for ReadInterface<'a, 'bus, 'c, I, B, T>
impl<'a, 'bus, 'c, I, B, T, INT> AsyncBufRead for ReadInterface<'a, 'bus, 'c, I, B, T, INT>
where
I: Unpin,
B: UsbBus,
T: SerialState<'bus, 'c, B, I> + ClassSet<B>,
INT: USBInterrupt,
{
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
let this = self.get_mut();
@ -59,6 +62,8 @@ where
match serial.poll_fill_buf(cx) {
Poll::Ready(Ok(buf)) => {
let buf: &[u8] = buf;
// NOTE(unsafe) This part of the buffer won't be modified until the user calls
// consume, which will invalidate this ref
let buf: &[u8] = unsafe { core::mem::transmute(buf) };
Poll::Ready(Ok(buf))
}
@ -81,11 +86,12 @@ where
}
}
impl<'a, 'bus, 'c, I, B, T> AsyncWrite for WriteInterface<'a, 'bus, 'c, I, B, T>
impl<'a, 'bus, 'c, I, B, T, INT> AsyncWrite for WriteInterface<'a, 'bus, 'c, I, B, T, INT>
where
I: Unpin,
B: UsbBus,
T: SerialState<'bus, 'c, B, I> + ClassSet<B>,
INT: USBInterrupt,
{
fn poll_write(
self: Pin<&mut Self>,

View File

@ -35,6 +35,7 @@ stm32l0x3 = ["stm32l0xx-hal/stm32l0x3"]
[dependencies]
embassy = { version = "0.1.0", path = "../embassy" }
embassy-extras = {version = "0.1.0", path = "../embassy-extras" }
defmt = { version = "0.2.0", optional = true }
log = { version = "0.4.11", optional = true }

View File

@ -9,7 +9,7 @@ use crate::pac::NVIC_PRIO_BITS;
// Re-exports
pub use cortex_m::interrupt::{CriticalSection, Mutex};
pub use embassy::interrupt::{declare, take, Interrupt, InterruptExt};
pub use embassy::interrupt::{declare, take, Interrupt};
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]

View File

@ -33,3 +33,23 @@ pub use {stm32l0xx_hal as hal, stm32l0xx_hal::pac};
pub mod fmt;
pub mod interrupt;
#[cfg(any(
feature = "stm32f401",
feature = "stm32f405",
feature = "stm32f407",
feature = "stm32f411",
feature = "stm32f412",
feature = "stm32f413",
feature = "stm32f415",
feature = "stm32f417",
feature = "stm32f423",
feature = "stm32f427",
feature = "stm32f429",
feature = "stm32f437",
feature = "stm32f439",
feature = "stm32f446",
feature = "stm32f469",
feature = "stm32f479",
))]
unsafe impl embassy_extras::usb::USBInterrupt for interrupt::OTG_FS {}

View File

@ -38,6 +38,7 @@ stm32f479 = ["stm32f4xx-hal/stm32f469", "embassy-stm32f4/stm32f469"]
embassy = { version = "0.1.0", path = "../embassy", features = ["defmt", "defmt-trace"] }
embassy-traits = { version = "0.1.0", path = "../embassy-traits", features = ["defmt"] }
embassy-stm32f4 = { version = "*", path = "../embassy-stm32f4" }
embassy-extras = {version = "0.1.0", path = "../embassy-extras" }
defmt = "0.2.0"
defmt-rtt = "0.2.0"

View File

@ -1,6 +1,8 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
#![feature(min_type_alias_impl_trait)]
#![feature(impl_trait_in_bindings)]
#[path = "../example_common.rs"]
mod example_common;
@ -9,12 +11,12 @@ use example_common::*;
use cortex_m_rt::entry;
use defmt::panic;
use embassy::executor::{task, Executor};
use embassy::interrupt::InterruptExt;
use embassy::io::{AsyncBufReadExt, AsyncWriteExt};
use embassy::time::{Duration, Timer};
use embassy::util::Forever;
use embassy_stm32f4::interrupt::InterruptExt;
use embassy_stm32f4::usb::Usb;
use embassy_stm32f4::usb_serial::UsbSerial;
use embassy_extras::usb::usb_serial::UsbSerial;
use embassy_extras::usb::Usb;
use embassy_stm32f4::{interrupt, pac, rtc};
use futures::future::{select, Either};
use futures::pin_mut;
@ -43,6 +45,7 @@ async fn run1(bus: &'static mut UsbBusAllocator<UsbBus<USB>>) {
let usb = Usb::new(device, serial, irq);
pin_mut!(usb);
usb.as_mut().start();
let (mut read_interface, mut write_interface) = usb.as_ref().take_serial_0();

View File

@ -1,148 +0,0 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
#[path = "../example_common.rs"]
mod example_common;
use example_common::*;
use cortex_m_rt::entry;
use defmt::panic;
use embassy::executor::{task, Executor};
use embassy::io::{AsyncBufReadExt, AsyncWriteExt};
use embassy::util::Forever;
use embassy_stm32f4::interrupt::InterruptExt;
use embassy_stm32f4::usb::Usb;
use embassy_stm32f4::usb_serial::UsbSerial;
use embassy_stm32f4::{interrupt, pac};
use futures::future::{select, Either};
use futures::pin_mut;
use stm32f4xx_hal::otg_fs::{UsbBus, USB};
use stm32f4xx_hal::prelude::*;
use usb_device::bus::UsbBusAllocator;
use usb_device::prelude::*;
#[task]
async fn run1(bus: &'static mut UsbBusAllocator<UsbBus<USB>>) {
info!("Async task");
let mut read_buf1 = [0u8; 128];
let mut write_buf1 = [0u8; 128];
let serial1 = UsbSerial::new(bus, &mut read_buf1, &mut write_buf1);
let mut read_buf2 = [0u8; 128];
let mut write_buf2 = [0u8; 128];
let serial2 = UsbSerial::new(bus, &mut read_buf2, &mut write_buf2);
let device = UsbDeviceBuilder::new(bus, UsbVidPid(0x16c0, 0x27dd))
.manufacturer("Fake company")
.product("Serial port")
.serial_number("TEST")
//.device_class(0x02)
.build();
let irq = interrupt::take!(OTG_FS);
irq.set_priority(interrupt::Priority::Level3);
let usb = Usb::new(device, (serial1, serial2), irq);
pin_mut!(usb);
let (mut read_interface1, mut write_interface1) = usb.as_ref().take_serial_0();
let (mut read_interface2, mut write_interface2) = usb.as_ref().take_serial_1();
let mut buf1 = [0u8; 64];
let mut buf2 = [0u8; 64];
loop {
let mut n1 = 0;
let mut n2 = 0;
let left = {
let read_line1 = async {
loop {
let byte = unwrap!(read_interface1.read_byte().await);
unwrap!(write_interface1.write_byte(byte).await);
buf1[n1] = byte;
n1 += 1;
if byte == b'\n' || byte == b'\r' || n1 == buf1.len() {
break;
}
}
};
pin_mut!(read_line1);
let read_line2 = async {
loop {
let byte = unwrap!(read_interface2.read_byte().await);
unwrap!(write_interface2.write_byte(byte).await);
buf2[n2] = byte;
n2 += 1;
if byte == b'\n' || byte == b'\r' || n2 == buf2.len() {
break;
}
}
};
pin_mut!(read_line2);
match select(read_line1, read_line2).await {
Either::Left(_) => true,
Either::Right(_) => false,
}
};
if left {
unwrap!(write_interface2.write_all(b"\r\n").await);
unwrap!(write_interface2.write_all(&buf1[..n1]).await);
} else {
unwrap!(write_interface1.write_all(b"\r\n").await);
unwrap!(write_interface1.write_all(&buf2[..n2]).await);
}
}
}
static EXECUTOR: Forever<Executor> = Forever::new();
static USB_BUS: Forever<UsbBusAllocator<UsbBus<USB>>> = Forever::new();
#[entry]
fn main() -> ! {
static mut EP_MEMORY: [u32; 1024] = [0; 1024];
info!("Hello World!");
let p = unwrap!(pac::Peripherals::take());
p.RCC.ahb1enr.modify(|_, w| w.dma1en().enabled());
let rcc = p.RCC.constrain();
let clocks = rcc
.cfgr
.use_hse(25.mhz())
.sysclk(48.mhz())
.require_pll48clk()
.freeze();
p.DBGMCU.cr.modify(|_, w| {
w.dbg_sleep().set_bit();
w.dbg_standby().set_bit();
w.dbg_stop().set_bit()
});
let executor = EXECUTOR.put(Executor::new());
let gpioa = p.GPIOA.split();
let usb = USB {
usb_global: p.OTG_FS_GLOBAL,
usb_device: p.OTG_FS_DEVICE,
usb_pwrclk: p.OTG_FS_PWRCLK,
pin_dm: gpioa.pa11.into_alternate_af10(),
pin_dp: gpioa.pa12.into_alternate_af10(),
hclk: clocks.hclk(),
};
// Rust analyzer isn't recognizing the static ref magic `cortex-m` does
#[allow(unused_unsafe)]
let usb_bus = USB_BUS.put(UsbBus::new(usb, unsafe { EP_MEMORY }));
executor.run(move |spawner| {
unwrap!(spawner.spawn(run1(usb_bus)));
});
}

View File

@ -32,7 +32,6 @@ stm32f479 = ["stm32f4xx-hal/stm32f469", "embassy-stm32/stm32f479"]
[dependencies]
embassy = { version = "0.1.0", path = "../embassy" }
embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32" }
embassy-extras = {version = "0.1.0", path = "../embassy-extras" }
defmt = { version = "0.2.0", optional = true }
log = { version = "0.4.11", optional = true }
@ -43,4 +42,3 @@ embedded-dma = { version = "0.1.2" }
stm32f4xx-hal = { version = "0.8.3", features = ["rt", "can"], git = "https://github.com/stm32-rs/stm32f4xx-hal.git"}
bxcan = "0.5.0"
nb = "*"
usb-device = "0.2.7"

View File

@ -316,9 +316,3 @@ pub mod exti;
pub mod qei;
pub mod rtc;
pub mod serial;
pub mod usb;
pub mod usb_serial;
pub(crate) mod cdc_acm;
pub use cortex_m_rt::interrupt;