1use crate::descriptor::{descriptor_type, lang_id};
8use crate::endpoint::{Direction, EndpointAddress, EndpointType};
9use crate::host::controller::{
10 Channel, DeviceAddress, EndpointConfig, HostController, Speed, Toggle,
11};
12use crate::host::descriptor::{Configuration, DeviceDescriptor, EndpointDescriptor};
13use crate::host::error::{HostError, HostResult};
14use crate::host::pipe::Pipe;
15use crate::request::Request;
16
17const EP0_MIN_PACKET: u16 = 8;
19
20pub const CONFIG_MAX: usize = 256;
27
28const STRING_BUFFER: usize = 2 + 2 * 32;
30
31pub struct Device<'a, C: HostController> {
33 controller: &'a C,
34 control: Channel,
35 address: DeviceAddress,
36 speed: Speed,
37 max_packet0: u16,
38 descriptor: DeviceDescriptor,
39 raw_config: [u8; CONFIG_MAX],
40 config_length: usize,
41}
42
43impl<'a, C: HostController> Device<'a, C> {
44 pub(crate) fn enumerate(
46 controller: &'a C,
47 address: DeviceAddress,
48 speed: Speed,
49 ) -> HostResult<Self> {
50 let control = controller.alloc_channel()?;
51 let mut device = Self {
52 controller,
53 control,
54 address: DeviceAddress::ZERO,
55 speed,
56 max_packet0: EP0_MIN_PACKET,
57 descriptor: DeviceDescriptor::default(),
58 raw_config: [0; CONFIG_MAX],
59 config_length: 0,
60 };
61 device.configure_control()?;
62
63 let mut head = [0u8; EP0_MIN_PACKET as usize];
66 let request = Request::get_descriptor(descriptor_type::DEVICE, 0, 0, head.len() as u16);
67 if device.control(&request, &mut head)? < head.len() {
68 return Err(HostError::Malformed);
69 }
70 device.max_packet0 = match head[7] {
71 8 | 16 | 32 | 64 => head[7] as u16,
72 _ => return Err(HostError::Malformed),
73 };
74 device.configure_control()?;
75
76 device.control(&Request::set_address(address.raw()), &mut [])?;
79 device.address = address;
80 controller.wait_millis(2);
81 device.configure_control()?;
82
83 let mut raw = [0u8; DeviceDescriptor::LEN];
84 let request = Request::get_descriptor(descriptor_type::DEVICE, 0, 0, raw.len() as u16);
85 device.control(&request, &mut raw)?;
86 device.descriptor = DeviceDescriptor::parse(&raw)?;
87
88 let mut header = [0u8; Configuration::HEADER_LEN];
91 let request =
92 Request::get_descriptor(descriptor_type::CONFIGURATION, 0, 0, header.len() as u16);
93 device.control(&request, &mut header)?;
94 let total = u16::from_le_bytes([header[2], header[3]]) as usize;
95 if total < Configuration::HEADER_LEN {
96 return Err(HostError::Malformed);
97 }
98 if total > CONFIG_MAX {
99 return Err(HostError::Overflow);
100 }
101
102 let mut raw_config = [0u8; CONFIG_MAX];
103 let request = Request::get_descriptor(descriptor_type::CONFIGURATION, 0, 0, total as u16);
104 let length = device.control(&request, &mut raw_config[..total])?;
105 Configuration::parse(&raw_config[..length])?;
106 device.raw_config = raw_config;
107 device.config_length = length;
108
109 Ok(device)
110 }
111
112 #[inline]
114 pub fn address(&self) -> DeviceAddress {
115 self.address
116 }
117
118 #[inline]
120 pub fn speed(&self) -> Speed {
121 self.speed
122 }
123
124 #[inline]
126 pub fn descriptor(&self) -> &DeviceDescriptor {
127 &self.descriptor
128 }
129
130 #[inline]
133 pub fn configuration(&self) -> Configuration<'_> {
134 Configuration::validated(&self.raw_config[..self.config_length])
137 }
138
139 pub fn control(&self, request: &Request, buffer: &mut [u8]) -> HostResult<usize> {
145 if (buffer.len() as u16) < request.length {
146 return Err(HostError::Overflow);
147 }
148 control_transfer(
149 self.controller,
150 self.control,
151 self.max_packet0,
152 request,
153 buffer,
154 )
155 }
156
157 pub fn set_configuration(&self, value: u8) -> HostResult<()> {
161 self.control(&Request::set_configuration(value), &mut [])?;
162 Ok(())
163 }
164
165 pub fn read_string(&self, index: u8, out: &mut [u8]) -> HostResult<usize> {
171 if index == 0 {
172 return Err(HostError::Protocol);
173 }
174 let mut raw = [0u8; STRING_BUFFER];
175 let request = Request::get_descriptor(
176 descriptor_type::STRING,
177 index,
178 lang_id::EN_US,
179 STRING_BUFFER as u16,
180 );
181 let length = self.control(&request, &mut raw)?;
182
183 if length < 2 || raw[0] as usize > length || raw[1] != descriptor_type::STRING {
184 return Err(HostError::Malformed);
185 }
186 Ok(utf16le_to_utf8(&raw[2..raw[0] as usize], out))
187 }
188
189 pub fn open(&self, endpoint: &EndpointDescriptor) -> HostResult<Pipe<'a, C>> {
191 let config = EndpointConfig {
192 address: endpoint.address,
193 transfer: endpoint.transfer_type(),
194 max_packet: endpoint.max_packet,
195 interval: endpoint.interval,
196 };
197 let channel = self.controller.alloc_channel()?;
198 let result = self.controller.configure(channel, self.address, &config);
199 match result {
200 Ok(()) => Ok(Pipe::new(self.controller, channel, config)),
201 Err(error) => {
202 self.controller.free_channel(channel);
203 Err(error)
204 }
205 }
206 }
207
208 pub fn clear_halt(&self, pipe: &Pipe<'a, C>) -> HostResult<()> {
212 self.control(&Request::clear_halt(pipe.address().raw()), &mut [])?;
213 pipe.reset_toggle();
214 Ok(())
215 }
216
217 fn configure_control(&self) -> HostResult<()> {
218 let endpoint = EndpointConfig {
219 address: EndpointAddress::EP0_OUT,
220 transfer: EndpointType::Control,
221 max_packet: self.max_packet0,
222 interval: 0,
223 };
224 self.controller
225 .configure(self.control, self.address, &endpoint)
226 }
227}
228
229impl<C: HostController> Drop for Device<'_, C> {
230 fn drop(&mut self) {
231 self.controller.free_channel(self.control);
232 }
233}
234
235#[inline]
242fn data_stage_toggle(packet: usize) -> Toggle {
243 if packet.is_multiple_of(2) {
244 Toggle::Data1
245 } else {
246 Toggle::Data0
247 }
248}
249
250fn control_transfer<C: HostController>(
251 controller: &C,
252 channel: Channel,
253 max_packet0: u16,
254 request: &Request,
255 buffer: &mut [u8],
256) -> HostResult<usize> {
257 let max_packet = max_packet0.max(EP0_MIN_PACKET) as usize;
258 controller.setup(channel, &request.to_bytes())?;
259
260 if request.length == 0 {
261 controller.transfer_in(channel, Toggle::Data1, &mut [])?;
264 return Ok(0);
265 }
266
267 let length = request.length as usize;
268 let mut done = 0;
269
270 match request.direction {
271 Direction::In => {
272 while done < length {
273 let chunk = (length - done).min(max_packet);
274 let received = controller.transfer_in(
275 channel,
276 data_stage_toggle(done / max_packet),
277 &mut buffer[done..done + chunk],
278 )?;
279 done += received;
280 if received < chunk {
281 break;
282 }
283 }
284 controller.transfer_out(channel, Toggle::Data1, &[])?;
285 }
286 Direction::Out => {
287 while done < length {
288 let chunk = (length - done).min(max_packet);
289 controller.transfer_out(
290 channel,
291 data_stage_toggle(done / max_packet),
292 &buffer[done..done + chunk],
293 )?;
294 done += chunk;
295 }
296 controller.transfer_in(channel, Toggle::Data1, &mut [])?;
297 }
298 }
299 Ok(done)
300}
301
302fn utf16le_to_utf8(units: &[u8], out: &mut [u8]) -> usize {
306 let mut written = 0;
307 for pair in units.as_chunks::<2>().0 {
308 let code = u16::from_le_bytes([pair[0], pair[1]]);
311 let decoded = match code {
312 0x0000..=0x007f => [code as u8, 0, 0, 1],
313 0x0080..=0x07ff => [
314 0b1100_0000 | (code >> 6) as u8,
315 0b1000_0000 | (code & 0x3f) as u8,
316 0,
317 2,
318 ],
319 0x0800..=0xd7ff | 0xe000..=0xffff => [
320 0b1110_0000 | (code >> 12) as u8,
321 0b1000_0000 | ((code >> 6) & 0x3f) as u8,
322 0b1000_0000 | (code & 0x3f) as u8,
323 3,
324 ],
325 _ => [0b1111_1101, 0, 0, 1],
326 };
327 let length = decoded[3] as usize;
328 if written + length > out.len() {
329 break;
330 }
331 out[written..written + length].copy_from_slice(&decoded[..length]);
332 written += length;
333 }
334 written
335}