use crate::endpoint::{Direction, EndpointAddress};
use crate::error::{UsbError, UsbResult};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RequestType {
Standard = 0,
Class = 1,
Vendor = 2,
Reserved = 3,
}
impl From<u8> for RequestType {
fn from(v: u8) -> Self {
match (v >> 5) & 0x03 {
0 => RequestType::Standard,
1 => RequestType::Class,
2 => RequestType::Vendor,
_ => RequestType::Reserved,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Recipient {
Device = 0,
Interface = 1,
Endpoint = 2,
Other = 3,
Reserved = 4,
}
impl From<u8> for Recipient {
fn from(v: u8) -> Self {
match v & 0x1f {
0 => Recipient::Device,
1 => Recipient::Interface,
2 => Recipient::Endpoint,
3 => Recipient::Other,
_ => Recipient::Reserved,
}
}
}
#[allow(non_snake_case)]
#[allow(missing_docs)]
pub mod StandardRequest {
pub const GET_STATUS: u8 = 0;
pub const CLEAR_FEATURE: u8 = 1;
pub const SET_FEATURE: u8 = 3;
pub const SET_ADDRESS: u8 = 5;
pub const GET_DESCRIPTOR: u8 = 6;
pub const SET_DESCRIPTOR: u8 = 7;
pub const GET_CONFIGURATION: u8 = 8;
pub const SET_CONFIGURATION: u8 = 9;
pub const GET_INTERFACE: u8 = 10;
pub const SET_INTERFACE: u8 = 11;
pub const SYNCH_FRAME: u8 = 12;
}
#[allow(non_snake_case)]
#[allow(missing_docs)]
pub mod Feature {
pub const ENDPOINT_HALT: u16 = 0;
pub const DEVICE_REMOTE_WAKEUP: u16 = 1;
pub const TEST_MODE: u16 = 2;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Request {
pub direction: Direction,
pub request_type: RequestType,
pub recipient: Recipient,
pub request: u8,
pub value: u16,
pub index: u16,
pub length: u16,
}
impl Request {
pub fn parse(buf: &[u8]) -> UsbResult<Self> {
if buf.len() < 8 {
return Err(UsbError::ParseError);
}
let bm = buf[0];
let recipient_raw = bm & 0x1f;
Ok(Self {
direction: Direction::from(bm),
request_type: RequestType::from(bm),
recipient: if recipient_raw <= 3 {
Recipient::from(bm)
} else {
Recipient::Reserved
},
request: buf[1],
value: u16::from_le_bytes([buf[2], buf[3]]),
index: u16::from_le_bytes([buf[4], buf[5]]),
length: u16::from_le_bytes([buf[6], buf[7]]),
})
}
#[inline]
pub fn descriptor_type_index(&self) -> (u8, u8) {
((self.value >> 8) as u8, self.value as u8)
}
#[inline]
pub fn endpoint_address(&self) -> EndpointAddress {
EndpointAddress::from((self.index & 0x8f) as u8)
}
}