use core::cell::RefCell;
use usb_stack::descriptor::descriptor_type;
use usb_stack::endpoint::{EndpointAddress, EndpointType};
use usb_stack::host::class::hub::{Hub, HubDescriptor};
use usb_stack::host::{
AddressPool, Channel, DeviceAddress, EndpointConfig, Host, HostController, HostError,
HostResult, HubRoute, PortStatus, Speed, Toggle, Translator,
};
use usb_stack::request::{Recipient, Request, RequestType, StandardRequest};
const HUB_DEVICE_DESCRIPTOR: [u8; 18] = [
18,
descriptor_type::DEVICE,
0x00,
0x02,
0x09, 0x00,
0x00,
64,
0x34,
0x12,
0x01,
0x00,
0x00,
0x01,
0,
0,
0,
1,
];
const HUB_CONFIG_DESCRIPTOR: [u8; 25] = [
9,
descriptor_type::CONFIGURATION,
25,
0,
1,
1,
0,
0xa0,
50,
9,
descriptor_type::INTERFACE,
0,
0,
1,
0x09, 0,
0,
0,
7,
descriptor_type::ENDPOINT,
0x81,
0x03,
8,
0,
12,
];
const HUB_DESCRIPTOR: [u8; 9] = [9, descriptor_type::HUB, 2, 0x00, 0x00, 10, 0, 0, 0];
const KEYBOARD_DEVICE_DESCRIPTOR: [u8; 18] = [
18,
descriptor_type::DEVICE,
0x00,
0x02,
0x00,
0x00,
0x00,
64,
0x78,
0x56,
0x34,
0x12,
0x00,
0x01,
0,
0,
0,
1,
];
const KEYBOARD_CONFIG_DESCRIPTOR: [u8; 25] = [
9,
descriptor_type::CONFIGURATION,
25,
0,
1,
1,
0,
0xa0,
50,
9,
descriptor_type::INTERFACE,
0,
0,
1,
0x03, 1,
1,
0,
7,
descriptor_type::ENDPOINT,
0x81,
0x03,
8,
0,
10,
];
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Model {
Hub,
Keyboard,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Action {
Request {
request: u8,
request_type: RequestType,
recipient: Recipient,
value: u16,
index: u16,
},
Configure {
channel: usize,
device: u8,
speed: Speed,
route: Option<HubRoute>,
},
}
struct State {
actions: Vec<Action>,
channels: [Option<(u8, EndpointConfig)>; 4],
models: [Option<Model>; 128],
pending: Option<Model>,
response: Vec<u8>,
sent: usize,
powered: [bool; 3],
connected: [bool; 3],
enabled: [bool; 3],
low_speed: [bool; 3],
high_speed: [bool; 3],
change: [u16; 3],
root_speed: Speed,
}
pub struct MockHub {
state: RefCell<State>,
}
impl MockHub {
fn new(root_speed: Speed) -> Self {
let mut state = State {
actions: Vec::new(),
channels: [None; 4],
models: [None; 128],
pending: Some(Model::Hub),
response: Vec::new(),
sent: 0,
powered: [false; 3],
connected: [false; 3],
enabled: [false; 3],
low_speed: [false; 3],
high_speed: [false; 3],
change: [0; 3],
root_speed,
};
state.connected[1] = true;
state.connected[2] = false;
Self {
state: RefCell::new(state),
}
}
fn low_speed(&self, port: usize, low: bool) {
self.state.borrow_mut().low_speed[port] = low;
}
fn actions(&self) -> Vec<Action> {
self.state.borrow().actions.clone()
}
fn port_request_seen(&self, request: u8, feature: u16, port: u16) -> bool {
self.actions().iter().any(|action| {
matches!(
action,
Action::Request {
request: r,
request_type: RequestType::Class,
recipient: Recipient::Other,
value,
index,
..
} if *r == request && *value == feature && *index == port
)
})
}
fn last_configure(&self) -> Option<Action> {
self.actions()
.into_iter()
.rev()
.find(|action| matches!(action, Action::Configure { .. }))
}
}
impl HostController for MockHub {
fn port_status(&self) -> PortStatus {
PortStatus {
connected: true,
enabled: true,
speed: self.state.borrow().root_speed,
overcurrent: false,
}
}
fn reset_port(&self) -> HostResult<PortStatus> {
let mut state = self.state.borrow_mut();
state.pending = Some(Model::Hub);
Ok(PortStatus {
connected: true,
enabled: true,
speed: state.root_speed,
overcurrent: false,
})
}
fn alloc_channel(&self) -> HostResult<Channel> {
let state = self.state.borrow_mut();
match state.channels.iter().position(Option::is_none) {
Some(index) => Ok(Channel::new(index as u8)),
None => Err(HostError::NoChannel),
}
}
fn free_channel(&self, channel: Channel) {
self.state.borrow_mut().channels[channel.index()] = None;
}
fn configure(
&self,
channel: Channel,
device: DeviceAddress,
endpoint: &EndpointConfig,
) -> HostResult<()> {
let mut state = self.state.borrow_mut();
state.actions.push(Action::Configure {
channel: channel.index(),
device: device.raw(),
speed: endpoint.speed,
route: endpoint.route,
});
state.channels[channel.index()] = Some((device.raw(), *endpoint));
Ok(())
}
fn setup(&self, channel: Channel, packet: &[u8]) -> HostResult<()> {
let request = Request::parse(packet).expect("a SETUP packet is eight bytes");
let mut state = self.state.borrow_mut();
state.actions.push(Action::Request {
request: request.request,
request_type: request.request_type,
recipient: request.recipient,
value: request.value,
index: request.index,
});
let (address, _) = state.channels[channel.index()].ok_or(HostError::Protocol)?;
let model = if address == 0 {
state.pending
} else {
state.models[address as usize]
}
.ok_or(HostError::Timeout)?;
state.response.clear();
state.sent = 0;
if request.recipient == Recipient::Other {
if model != Model::Hub {
return Err(HostError::Stall);
}
return handle_port_request(&mut state, &request);
}
match request.request {
StandardRequest::GET_DESCRIPTOR => {
let kind = (request.value >> 8) as u8;
let data: &[u8] = match (model, kind) {
(Model::Hub, descriptor_type::DEVICE) => &HUB_DEVICE_DESCRIPTOR,
(Model::Hub, descriptor_type::CONFIGURATION) => &HUB_CONFIG_DESCRIPTOR,
(Model::Hub, descriptor_type::HUB) => &HUB_DESCRIPTOR,
(Model::Keyboard, descriptor_type::DEVICE) => &KEYBOARD_DEVICE_DESCRIPTOR,
(Model::Keyboard, descriptor_type::CONFIGURATION) => {
&KEYBOARD_CONFIG_DESCRIPTOR
}
_ => return Err(HostError::Stall),
};
let length = usize::from(request.length).min(data.len());
state.response.extend_from_slice(&data[..length]);
Ok(())
}
StandardRequest::SET_ADDRESS => {
let address = request.value as u8;
if address == 0 {
return Err(HostError::Protocol);
}
state.models[address as usize] = Some(model);
if state.pending == Some(model) {
state.pending = None;
}
Ok(())
}
StandardRequest::SET_CONFIGURATION => Ok(()),
_ if request.request_type == RequestType::Class => Ok(()),
_ => Err(HostError::Stall),
}
}
fn transfer_in(
&self,
channel: Channel,
_toggle: Toggle,
buffer: &mut [u8],
) -> HostResult<usize> {
let mut state = self.state.borrow_mut();
let (_, config) = state.channels[channel.index()].ok_or(HostError::Protocol)?;
if config.transfer != EndpointType::Control {
return Err(HostError::Timeout);
}
let remaining = state.response.len() - state.sent;
let length = remaining.min(buffer.len());
buffer[..length].copy_from_slice(&state.response[state.sent..state.sent + length]);
state.sent += length;
Ok(length)
}
fn transfer_out(&self, _channel: Channel, _toggle: Toggle, _data: &[u8]) -> HostResult<()> {
Ok(())
}
fn wait_millis(&self, _millis: u32) {}
}
fn handle_port_request(state: &mut State, request: &Request) -> HostResult<()> {
use usb_stack::descriptor::hub::{feature, port_change, port_status};
let port = request.index as usize;
if !(1..=2).contains(&port) {
return Err(HostError::Protocol);
}
match request.request {
StandardRequest::GET_STATUS => {
let mut status = 0u16;
if state.connected[port] {
status |= port_status::CONNECTION;
}
if state.enabled[port] {
status |= port_status::ENABLE;
}
if state.powered[port] {
status |= port_status::POWER;
}
if state.low_speed[port] {
status |= port_status::LOW_SPEED;
}
if state.high_speed[port] {
status |= port_status::HIGH_SPEED;
}
state.response.extend_from_slice(&status.to_le_bytes());
state
.response
.extend_from_slice(&state.change[port].to_le_bytes());
Ok(())
}
StandardRequest::SET_FEATURE => {
match request.value {
feature::PORT_POWER => state.powered[port] = true,
feature::PORT_RESET => {
if !state.connected[port] {
return Err(HostError::Protocol);
}
state.enabled[port] = true;
state.change[port] |= port_change::RESET;
state.pending = Some(Model::Keyboard);
}
_ => {}
}
Ok(())
}
StandardRequest::CLEAR_FEATURE => {
if request.value == feature::PORT_ENABLE {
state.enabled[port] = false;
state.change[port] |= port_change::ENABLE;
}
for bit in 0..5u16 {
if request.value == feature::C_PORT_CONNECTION + bit {
state.change[port] &= !(1 << bit);
}
}
Ok(())
}
_ => Err(HostError::Stall),
}
}
fn enumerate_hub(controller: &MockHub) -> usb_stack::host::Device<'_, MockHub> {
Host::new(controller)
.enumerate()
.expect("the hub enumerates")
}
#[test]
fn a_device_enumerates_behind_a_full_speed_hub() {
let controller = MockHub::new(Speed::Full);
let device = enumerate_hub(&controller);
assert_eq!(device.address().raw(), 1);
assert_eq!(device.speed(), Speed::Full);
assert_eq!(device.descriptor().class, 0x09);
assert_eq!(device.route(), None);
let hub = Hub::open(&device).expect("the hub opens");
assert_eq!(hub.ports(), 2);
assert_eq!(
hub.descriptor(),
&HubDescriptor {
ports: 2,
characteristics: 0,
power_on_delay_ms: 20,
}
);
assert_eq!(hub.descriptor().power_switching(), 0);
assert_eq!(hub.descriptor().tt_think_time(), 0);
hub.power_ports().expect("the ports power up");
assert!(controller.port_request_seen(
StandardRequest::SET_FEATURE,
usb_stack::descriptor::hub::feature::PORT_POWER,
1
));
assert!(controller.port_request_seen(
StandardRequest::SET_FEATURE,
usb_stack::descriptor::hub::feature::PORT_POWER,
2
));
assert_eq!(
hub.wait_for_connection(1, 100)
.expect("the keyboard is there")
.speed(),
Speed::Full
);
assert_eq!(hub.reset_port(1).expect("the port resets"), Speed::Full);
let status = hub.port_status(1).expect("the port answers");
assert_eq!(
status.change & usb_stack::descriptor::hub::port_change::RESET,
0
);
assert!(status.enabled());
let address = DeviceAddress::new(2);
let child = hub
.enumerate_child(1, address)
.expect("the keyboard enumerates");
assert_eq!(child.address(), address);
assert_eq!(child.speed(), Speed::Full);
assert_eq!(
child.route(),
Some(HubRoute {
hub: device.address(),
port: 1,
translator: None,
})
);
assert_eq!(child.descriptor().vendor_id, 0x5678);
let endpoint = usb_stack::host::EndpointDescriptor {
address: EndpointAddress::in_(1),
attributes: 0x03,
max_packet: 8,
interval: 10,
};
let pipe = child.open(&endpoint).expect("the pipe opens");
assert_eq!(pipe.max_packet(), 8);
match controller
.last_configure()
.expect("the channel was configured")
{
Action::Configure {
device,
speed,
route,
..
} => {
assert_eq!(device, address.raw());
assert_eq!(speed, Speed::Full);
assert_eq!(route, child.route());
}
other => panic!("unexpected action {other:?}"),
}
}
#[test]
fn a_low_speed_child_reports_its_speed() {
let controller = MockHub::new(Speed::Full);
controller.low_speed(1, true);
let device = enumerate_hub(&controller);
let hub = Hub::open(&device).expect("the hub opens");
hub.power_ports().expect("the ports power up");
assert_eq!(hub.reset_port(1).expect("the port resets"), Speed::Low);
let child = hub
.enumerate_child(1, DeviceAddress::new(2))
.expect("the keyboard enumerates");
assert_eq!(child.speed(), Speed::Low);
assert_eq!(
child.route(),
Some(HubRoute {
hub: device.address(),
port: 1,
translator: None,
})
);
}
#[test]
fn a_full_speed_child_of_a_high_speed_hub_gets_a_translator() {
let controller = MockHub::new(Speed::High);
let device = enumerate_hub(&controller);
let hub = Hub::open(&device).expect("the hub opens");
hub.power_ports().expect("the ports power up");
assert_eq!(hub.reset_port(1).expect("the port resets"), Speed::Full);
let child = hub
.enumerate_child(1, DeviceAddress::new(2))
.expect("the keyboard enumerates");
assert_eq!(child.speed(), Speed::Full);
assert_eq!(
child.route(),
Some(HubRoute {
hub: device.address(),
port: 1,
translator: Some(Translator {
hub: device.address(),
port: 1,
}),
})
);
}
#[test]
fn a_reset_disables_an_enabled_port_first() {
let controller = MockHub::new(Speed::Full);
let device = enumerate_hub(&controller);
let hub = Hub::open(&device).expect("the hub opens");
hub.power_ports().expect("the ports power up");
assert_eq!(hub.reset_port(1).expect("the port resets"), Speed::Full);
assert_eq!(
hub.reset_port(1).expect("the port resets again"),
Speed::Full
);
assert!(controller.port_request_seen(
StandardRequest::CLEAR_FEATURE,
usb_stack::descriptor::hub::feature::PORT_ENABLE,
1
));
}
#[test]
fn the_address_pool_skips_zero_and_hands_addresses_back() {
let mut pool = AddressPool::new();
assert_eq!(pool.take(), Some(DeviceAddress::FIRST));
assert_eq!(pool.take(), Some(DeviceAddress::new(2)));
assert!(pool.is_used(DeviceAddress::FIRST));
pool.release(DeviceAddress::FIRST);
assert!(!pool.is_used(DeviceAddress::FIRST));
assert_eq!(pool.take(), Some(DeviceAddress::FIRST));
}