use core::cell::{Cell, UnsafeCell};
use crate::device::endpoint::Endpoint;
use crate::device::error::{UsbError, UsbResult};
use crate::endpoint::{Direction, EndpointAddress, EndpointDir, EndpointType};
pub enum PollResult {
None,
Reset,
Data {
ep_out: u16,
ep_in_complete: u16,
ep_setup: u16,
},
Suspend,
Resume,
}
impl PollResult {
#[inline]
pub fn is_data(self) -> bool {
matches!(self, Self::Data { .. })
}
}
pub trait UsbBus: Sized {
fn alloc_ep(
&mut self,
dir: Direction,
addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet: u16,
interval: u8,
) -> UsbResult<EndpointAddress>;
fn enable(&mut self);
fn reset(&self);
fn set_device_address(&self, addr: u8);
fn poll(&self) -> PollResult;
fn write(&self, addr: EndpointAddress, buf: &[u8]) -> UsbResult<usize>;
fn read(&self, addr: EndpointAddress, buf: &mut [u8]) -> UsbResult<usize>;
fn set_stalled(&self, addr: EndpointAddress, stalled: bool);
fn is_stalled(&self, addr: EndpointAddress) -> bool;
fn suspend(&self);
fn resume(&self);
fn force_reset(&self) -> UsbResult<()> {
Err(UsbError::Unsupported)
}
const SET_ADDRESS_BEFORE_STATUS: bool = false;
const MAX_PACKET_SIZE: u16 = 64;
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct InterfaceNumber(pub(crate) u8);
impl InterfaceNumber {
#[inline]
pub const fn new(number: u8) -> Self {
Self(number)
}
}
impl From<InterfaceNumber> for u8 {
fn from(n: InterfaceNumber) -> u8 {
n.0
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct StringIndex(u8);
impl StringIndex {
pub(crate) fn new(index: u8) -> Self {
Self(index)
}
}
impl From<StringIndex> for u8 {
fn from(s: StringIndex) -> u8 {
s.0
}
}
pub struct UsbBusAllocator<B: UsbBus> {
bus: UnsafeCell<B>,
frozen: Cell<bool>,
next_interface: Cell<u8>,
next_string_index: Cell<u8>,
}
unsafe impl<B: UsbBus + Send> Send for UsbBusAllocator<B> {}
unsafe impl<B: UsbBus + Sync> Sync for UsbBusAllocator<B> {}
impl<B: UsbBus> UsbBusAllocator<B> {
pub fn new(bus: B) -> Self {
Self {
bus: UnsafeCell::new(bus),
frozen: Cell::new(false),
next_interface: Cell::new(0),
next_string_index: Cell::new(4),
}
}
pub fn alloc<D: EndpointDir>(
&self,
addr: Option<EndpointAddress>,
ep_type: EndpointType,
max_packet: u16,
interval: u8,
) -> UsbResult<Endpoint<'_, B, D>> {
assert!(
!self.frozen.get(),
"cannot allocate endpoints after UsbBusAllocator::freeze()"
);
let ep_addr = unsafe {
(*self.bus.get()).alloc_ep(D::DIRECTION, addr, ep_type, max_packet, interval)?
};
let bus: &B = unsafe { &*self.bus.get() };
Ok(Endpoint::new(bus, ep_addr, ep_type, max_packet, interval))
}
pub fn control<D: EndpointDir>(&self, max_packet: u16) -> Endpoint<'_, B, D> {
self.alloc(None, EndpointType::Control, max_packet, 0)
.expect("control endpoint allocation failed")
}
pub fn bulk<D: EndpointDir>(&self, max_packet: u16) -> Endpoint<'_, B, D> {
self.alloc(None, EndpointType::Bulk, max_packet, 0)
.expect("bulk endpoint allocation failed")
}
pub fn interrupt<D: EndpointDir>(&self, max_packet: u16, interval: u8) -> Endpoint<'_, B, D> {
self.alloc(None, EndpointType::Interrupt, max_packet, interval)
.expect("interrupt endpoint allocation failed")
}
pub fn isochronous<D: EndpointDir>(
&self,
synchronization: crate::endpoint::IsoSynchronization,
usage: crate::endpoint::IsoUsage,
max_packet: u16,
interval: u8,
) -> Endpoint<'_, B, D> {
self.alloc(
None,
EndpointType::Isochronous {
synchronization,
usage,
},
max_packet,
interval,
)
.expect("isochronous endpoint allocation failed")
}
pub fn interface(&self) -> InterfaceNumber {
assert!(
!self.frozen.get(),
"cannot allocate interfaces after freeze()"
);
let n = self.next_interface.get();
self.next_interface.set(n + 1);
InterfaceNumber(n)
}
pub fn string(&self) -> StringIndex {
assert!(!self.frozen.get(), "cannot allocate strings after freeze()");
let i = self.next_string_index.get();
self.next_string_index.set(i + 1);
StringIndex(i)
}
pub(crate) fn freeze(&self) -> &B {
if !self.frozen.get() {
self.frozen.set(true);
unsafe { (*self.bus.get()).enable() };
}
unsafe { &*self.bus.get() }
}
#[allow(dead_code)]
pub(crate) fn num_interfaces(&self) -> u8 {
self.next_interface.get()
}
}