Skip to main content

usb_stack/
request.rs

1//! USB control requests.
2//!
3//! Both directions share one type: the device side parses the eight bytes it
4//! receives on endpoint 0, the host side builds them for the requests it sends.
5
6use crate::endpoint::{Direction, EndpointAddress};
7
8// ─── Request type & recipient ─────────────────────────────────────────────────
9
10/// `bmRequestType` bits 6:5 — who defined the request.
11#[derive(Clone, Copy, PartialEq, Eq, Debug)]
12#[cfg_attr(feature = "defmt", derive(defmt::Format))]
13pub enum RequestType {
14    /// USB 2.0 standard request.
15    Standard = 0,
16    /// Class-specific request.
17    Class = 1,
18    /// Vendor-specific request.
19    Vendor = 2,
20    /// Reserved encoding.
21    Reserved = 3,
22}
23
24impl From<u8> for RequestType {
25    fn from(v: u8) -> Self {
26        match (v >> 5) & 0x03 {
27            0 => RequestType::Standard,
28            1 => RequestType::Class,
29            2 => RequestType::Vendor,
30            _ => RequestType::Reserved,
31        }
32    }
33}
34
35/// `bmRequestType` bits 4:0 — who the request is addressed to.
36#[derive(Clone, Copy, PartialEq, Eq, Debug)]
37#[cfg_attr(feature = "defmt", derive(defmt::Format))]
38pub enum Recipient {
39    /// The device as a whole.
40    Device = 0,
41    /// A specific interface.
42    Interface = 1,
43    /// A specific endpoint.
44    Endpoint = 2,
45    /// Another device on the bus (hub class).
46    Other = 3,
47    /// Reserved encoding.
48    Reserved = 4,
49}
50
51impl From<u8> for Recipient {
52    fn from(v: u8) -> Self {
53        match v & 0x1f {
54            0 => Recipient::Device,
55            1 => Recipient::Interface,
56            2 => Recipient::Endpoint,
57            3 => Recipient::Other,
58            _ => Recipient::Reserved,
59        }
60    }
61}
62
63// ─── Standard request codes ───────────────────────────────────────────────────
64
65/// Standard USB request codes (`bRequest`).
66#[allow(non_snake_case)]
67#[allow(missing_docs)]
68pub mod StandardRequest {
69    pub const GET_STATUS: u8 = 0;
70    pub const CLEAR_FEATURE: u8 = 1;
71    pub const SET_FEATURE: u8 = 3;
72    pub const SET_ADDRESS: u8 = 5;
73    pub const GET_DESCRIPTOR: u8 = 6;
74    pub const SET_DESCRIPTOR: u8 = 7;
75    pub const GET_CONFIGURATION: u8 = 8;
76    pub const SET_CONFIGURATION: u8 = 9;
77    pub const GET_INTERFACE: u8 = 10;
78    pub const SET_INTERFACE: u8 = 11;
79    pub const SYNCH_FRAME: u8 = 12;
80}
81
82/// Standard feature selectors (`wValue`).
83#[allow(non_snake_case)]
84#[allow(missing_docs)]
85pub mod Feature {
86    pub const ENDPOINT_HALT: u16 = 0;
87    pub const DEVICE_REMOTE_WAKEUP: u16 = 1;
88    pub const TEST_MODE: u16 = 2;
89}
90
91// ─── Request ─────────────────────────────────────────────────────────────────
92
93/// A parsed USB SETUP packet.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95#[cfg_attr(feature = "defmt", derive(defmt::Format))]
96pub struct Request {
97    /// Transfer direction (from host's perspective).
98    pub direction: Direction,
99    /// Who defined this request.
100    pub request_type: RequestType,
101    /// Who the request is directed at.
102    pub recipient: Recipient,
103    /// Request code (`bRequest`).
104    pub request: u8,
105    /// Request-specific value (`wValue`).
106    pub value: u16,
107    /// Request-specific index (`wIndex`).
108    pub index: u16,
109    /// Number of bytes in the data stage (`wLength`).
110    pub length: u16,
111}
112
113impl Request {
114    /// Parse a SETUP packet from its 8-byte wire encoding.
115    ///
116    /// Returns `None` when fewer than eight bytes are available.
117    pub fn parse(buf: &[u8]) -> Option<Self> {
118        let buf: &[u8; 8] = buf.get(..8)?.try_into().ok()?;
119        let bm = buf[0];
120        let recipient_raw = bm & 0x1f;
121        Some(Self {
122            direction: Direction::from(bm),
123            request_type: RequestType::from(bm),
124            recipient: if recipient_raw <= 3 {
125                Recipient::from(bm)
126            } else {
127                Recipient::Reserved
128            },
129            request: buf[1],
130            value: u16::from_le_bytes([buf[2], buf[3]]),
131            index: u16::from_le_bytes([buf[4], buf[5]]),
132            length: u16::from_le_bytes([buf[6], buf[7]]),
133        })
134    }
135
136    /// Build a request from its fields.
137    pub const fn custom(
138        direction: Direction,
139        request_type: RequestType,
140        recipient: Recipient,
141        request: u8,
142        value: u16,
143        index: u16,
144        length: u16,
145    ) -> Self {
146        Self {
147            direction,
148            request_type,
149            recipient,
150            request,
151            value,
152            index,
153            length,
154        }
155    }
156
157    /// The wire encoding of the request.
158    pub const fn to_bytes(self) -> [u8; 8] {
159        let value = self.value.to_le_bytes();
160        let index = self.index.to_le_bytes();
161        let length = self.length.to_le_bytes();
162        [
163            self.direction as u8 | (self.request_type as u8) << 5 | self.recipient as u8,
164            self.request,
165            value[0],
166            value[1],
167            index[0],
168            index[1],
169            length[0],
170            length[1],
171        ]
172    }
173
174    /// A standard request to the device.
175    const fn standard(
176        direction: Direction,
177        request: u8,
178        value: u16,
179        index: u16,
180        length: u16,
181    ) -> Self {
182        Self::custom(
183            direction,
184            RequestType::Standard,
185            Recipient::Device,
186            request,
187            value,
188            index,
189            length,
190        )
191    }
192
193    /// `GET_DESCRIPTOR`, which always reads from the device.
194    pub const fn get_descriptor(kind: u8, index: u8, language: u16, length: u16) -> Self {
195        Self::standard(
196            Direction::In,
197            StandardRequest::GET_DESCRIPTOR,
198            ((kind as u16) << 8) | index as u16,
199            language,
200            length,
201        )
202    }
203
204    /// `SET_ADDRESS`.
205    pub const fn set_address(address: u8) -> Self {
206        Self::standard(
207            Direction::Out,
208            StandardRequest::SET_ADDRESS,
209            address as u16,
210            0,
211            0,
212        )
213    }
214
215    /// `SET_CONFIGURATION`.
216    pub const fn set_configuration(value: u8) -> Self {
217        Self::standard(
218            Direction::Out,
219            StandardRequest::SET_CONFIGURATION,
220            value as u16,
221            0,
222            0,
223        )
224    }
225
226    /// `SET_INTERFACE`.
227    pub const fn set_interface(interface: u8, alternate: u8) -> Self {
228        Self::custom(
229            Direction::Out,
230            RequestType::Standard,
231            Recipient::Interface,
232            StandardRequest::SET_INTERFACE,
233            alternate as u16,
234            interface as u16,
235            0,
236        )
237    }
238
239    /// `GET_STATUS`, which always returns two bytes.
240    pub const fn get_status(recipient: Recipient, index: u16) -> Self {
241        Self::custom(
242            Direction::In,
243            RequestType::Standard,
244            recipient,
245            StandardRequest::GET_STATUS,
246            0,
247            index,
248            2,
249        )
250    }
251
252    /// `CLEAR_FEATURE`.
253    pub const fn clear_feature(recipient: Recipient, feature: u16, index: u16) -> Self {
254        Self::custom(
255            Direction::Out,
256            RequestType::Standard,
257            recipient,
258            StandardRequest::CLEAR_FEATURE,
259            feature,
260            index,
261            0,
262        )
263    }
264
265    /// `SET_FEATURE`.
266    pub const fn set_feature(recipient: Recipient, feature: u16, index: u16) -> Self {
267        Self::custom(
268            Direction::Out,
269            RequestType::Standard,
270            recipient,
271            StandardRequest::SET_FEATURE,
272            feature,
273            index,
274            0,
275        )
276    }
277
278    /// `CLEAR_FEATURE(ENDPOINT_HALT)` for an endpoint.
279    pub const fn clear_halt(endpoint: u8) -> Self {
280        Self::clear_feature(Recipient::Endpoint, Feature::ENDPOINT_HALT, endpoint as u16)
281    }
282
283    /// Extract (descriptor_type, descriptor_index) from `wValue` as used in
284    /// GET_DESCRIPTOR requests.
285    #[inline]
286    pub fn descriptor_type_index(&self) -> (u8, u8) {
287        ((self.value >> 8) as u8, self.value as u8)
288    }
289
290    /// Extract the endpoint address from `wIndex` for endpoint-directed requests.
291    #[inline]
292    pub fn endpoint_address(&self) -> EndpointAddress {
293        EndpointAddress::from((self.index & 0x8f) as u8)
294    }
295}