1use crate::descriptor::{class_code, descriptor_type, hub};
27use crate::endpoint::Direction;
28use crate::host::controller::{DeviceAddress, HostController, HubRoute, Speed, Translator};
29use crate::host::device::Device;
30use crate::host::error::{HostError, HostResult};
31use crate::request::{Recipient, Request, RequestType, StandardRequest};
32
33const DESCRIPTOR_MAX: usize = 15;
36
37const POLL_MS: u32 = 5;
39
40const RESET_TIMEOUT_MS: u32 = 200;
42
43#[derive(Clone, Copy, PartialEq, Eq, Debug)]
47#[cfg_attr(feature = "defmt", derive(defmt::Format))]
48pub struct HubDescriptor {
49 pub ports: u8,
51 pub characteristics: u16,
53 pub power_on_delay_ms: u32,
55}
56
57impl HubDescriptor {
58 pub const LEN: usize = 9;
61
62 pub fn parse(bytes: &[u8]) -> HostResult<Self> {
64 if bytes.len() < Self::LEN || bytes[0] < Self::LEN as u8 || bytes[1] != descriptor_type::HUB
65 {
66 return Err(HostError::Malformed);
67 }
68 Ok(Self {
69 ports: bytes[2],
70 characteristics: u16::from_le_bytes([bytes[3], bytes[4]]),
71 power_on_delay_ms: u32::from(bytes[5]) * 2,
73 })
74 }
75
76 #[inline]
78 pub fn power_switching(&self) -> u16 {
79 self.characteristics & hub::characteristics::POWER_SWITCHING_MASK
80 }
81
82 #[inline]
84 pub fn tt_think_time(&self) -> u8 {
85 ((self.characteristics & hub::characteristics::TT_THINK_TIME_MASK)
86 >> hub::characteristics::TT_THINK_TIME_SHIFT) as u8
87 }
88}
89
90#[derive(Clone, Copy, PartialEq, Eq, Debug)]
94#[cfg_attr(feature = "defmt", derive(defmt::Format))]
95pub struct HubPortStatus {
96 pub status: u16,
98 pub change: u16,
100}
101
102impl HubPortStatus {
103 #[inline]
105 pub fn connected(&self) -> bool {
106 self.status & hub::port_status::CONNECTION != 0
107 }
108
109 #[inline]
111 pub fn enabled(&self) -> bool {
112 self.status & hub::port_status::ENABLE != 0
113 }
114
115 #[inline]
117 pub fn over_current(&self) -> bool {
118 self.status & hub::port_status::OVER_CURRENT != 0
119 }
120
121 #[inline]
126 pub fn speed(&self) -> Speed {
127 if self.status & hub::port_status::HIGH_SPEED != 0 {
128 Speed::High
129 } else if self.status & hub::port_status::LOW_SPEED != 0 {
130 Speed::Low
131 } else {
132 Speed::Full
133 }
134 }
135}
136
137pub struct Hub<'d, 'a, C: HostController> {
141 device: &'a Device<'d, C>,
142 descriptor: HubDescriptor,
143}
144
145impl<'d, 'a, C: HostController> Hub<'d, 'a, C> {
146 pub fn open(device: &'a Device<'d, C>) -> HostResult<Self> {
151 let class = device.descriptor().class;
152 let interface = device
155 .configuration()
156 .interfaces()
157 .any(|interface| interface.class() == class_code::HUB && interface.sub_class() == 0);
158 if class != class_code::HUB && !interface {
159 return Err(HostError::Protocol);
160 }
161
162 let value = device.configuration().value();
163 if value != 0 {
164 device.set_configuration(value)?;
165 }
166
167 let mut raw = [0u8; DESCRIPTOR_MAX];
168 let request = Request::custom(
169 Direction::In,
170 RequestType::Class,
171 Recipient::Device,
172 StandardRequest::GET_DESCRIPTOR,
173 (descriptor_type::HUB as u16) << 8,
174 0,
175 DESCRIPTOR_MAX as u16,
176 );
177 let length = device.control(&request, &mut raw)?;
178 let descriptor = HubDescriptor::parse(&raw[..length])?;
179
180 Ok(Self { device, descriptor })
181 }
182
183 #[inline]
185 pub fn device(&self) -> &'a Device<'d, C> {
186 self.device
187 }
188
189 #[inline]
191 pub fn descriptor(&self) -> &HubDescriptor {
192 &self.descriptor
193 }
194
195 #[inline]
197 pub fn ports(&self) -> u8 {
198 self.descriptor.ports
199 }
200
201 pub fn power_ports(&self) -> HostResult<()> {
208 for port in 1..=self.descriptor.ports {
209 let status = self.port_status(port)?;
210 if status.status & hub::port_status::POWER == 0 {
211 self.set_port_feature(port, hub::feature::PORT_POWER)?;
212 }
213 }
214 self.device
215 .controller()
216 .wait_millis(self.descriptor.power_on_delay_ms);
217 Ok(())
218 }
219
220 pub fn port_status(&self, port: u8) -> HostResult<HubPortStatus> {
222 self.check_port(port)?;
223 let request = Request::custom(
224 Direction::In,
225 RequestType::Class,
226 Recipient::Other,
227 StandardRequest::GET_STATUS,
228 0,
229 u16::from(port),
230 4,
231 );
232 let mut raw = [0u8; 4];
233 if self.device.control(&request, &mut raw)? < raw.len() {
234 return Err(HostError::Malformed);
235 }
236 Ok(HubPortStatus {
237 status: u16::from_le_bytes([raw[0], raw[1]]),
238 change: u16::from_le_bytes([raw[2], raw[3]]),
239 })
240 }
241
242 pub fn clear_port_change(&self, port: u8, change: u16) -> HostResult<()> {
248 for bit in 0..5u16 {
249 if change & (1 << bit) != 0 {
250 self.clear_port_feature(port, hub::feature::C_PORT_CONNECTION + bit)?;
251 }
252 }
253 Ok(())
254 }
255
256 pub fn wait_for_connection(&self, port: u8, timeout_ms: u32) -> HostResult<HubPortStatus> {
258 self.poll_until(port, timeout_ms, HubPortStatus::connected)
259 }
260
261 pub fn reset_port(&self, port: u8) -> HostResult<Speed> {
267 let status = self.port_status(port)?;
268 if !status.connected() {
269 return Err(HostError::Disconnected);
270 }
271 self.clear_port_change(port, status.change)?;
273
274 if status.enabled() {
277 self.clear_port_feature(port, hub::feature::PORT_ENABLE)?;
278 let status = self.poll_until(port, RESET_TIMEOUT_MS, |status| !status.enabled())?;
279 self.clear_port_change(port, status.change)?;
280 }
281
282 self.set_port_feature(port, hub::feature::PORT_RESET)?;
283 let status = self.poll_until(port, RESET_TIMEOUT_MS, |status| {
284 status.change & hub::port_change::RESET != 0
285 })?;
286 self.clear_port_change(port, status.change)?;
287
288 if !status.enabled() {
289 return Err(HostError::Disconnected);
290 }
291 Ok(status.speed())
292 }
293
294 pub fn enumerate_child(&self, port: u8, address: DeviceAddress) -> HostResult<Device<'d, C>> {
299 let status = self.port_status(port)?;
300 if !status.connected() || !status.enabled() {
301 return Err(HostError::Disconnected);
302 }
303 let speed = status.speed();
304 let route = self.child_route(port, speed);
305 Device::enumerate_downstream(self.device.controller(), address, speed, route)
306 }
307
308 fn child_route(&self, port: u8, speed: Speed) -> HubRoute {
309 let translator = match (self.device.speed(), speed) {
310 (Speed::High, Speed::High) => None,
312 (Speed::High, _) => Some(Translator {
315 hub: self.device.address(),
316 port,
317 }),
318 _ => self.device.route().and_then(|route| route.translator),
321 };
322 HubRoute {
323 hub: self.device.address(),
324 port,
325 translator,
326 }
327 }
328
329 fn poll_until(
330 &self,
331 port: u8,
332 timeout_ms: u32,
333 satisfied: impl Fn(&HubPortStatus) -> bool,
334 ) -> HostResult<HubPortStatus> {
335 let mut waited = 0;
336 loop {
337 let status = self.port_status(port)?;
338 if satisfied(&status) {
339 return Ok(status);
340 }
341 if waited >= timeout_ms {
342 return Err(HostError::Timeout);
343 }
344 self.device.controller().wait_millis(POLL_MS);
345 waited += POLL_MS;
346 }
347 }
348
349 fn set_port_feature(&self, port: u8, feature: u16) -> HostResult<()> {
350 self.port_request(StandardRequest::SET_FEATURE, feature, port)
351 }
352
353 fn clear_port_feature(&self, port: u8, feature: u16) -> HostResult<()> {
354 self.port_request(StandardRequest::CLEAR_FEATURE, feature, port)
355 }
356
357 fn port_request(&self, request: u8, feature: u16, port: u8) -> HostResult<()> {
358 self.check_port(port)?;
359 let request = Request::custom(
360 Direction::Out,
361 RequestType::Class,
362 Recipient::Other,
363 request,
364 feature,
365 u16::from(port),
366 0,
367 );
368 self.device.control(&request, &mut [])?;
369 Ok(())
370 }
371
372 fn check_port(&self, port: u8) -> HostResult<()> {
373 if port == 0 || port > self.descriptor.ports {
374 return Err(HostError::Protocol);
375 }
376 Ok(())
377 }
378}