aboutsummaryrefslogtreecommitdiffstats
path: root/usbh/src/device.rs
blob: 3bb03044f7f6b0a6b347079955b0a1649a8a3256 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use core::convert::TryInto;

const MAX_DEVICES: usize = 16;
const MAX_ENDPOINTS: usize = 8;

pub struct DeviceTable {
    devices: [Option<Device>; MAX_DEVICES],
}
impl DeviceTable {
    pub fn new() -> Self {
        Self {
            devices: Default::default(),
        }
    }

    /// Return the device at address `addr`.
    pub fn device_for(&mut self, addr: u8) -> Option<&mut Device> {
        if let Some(ref mut d) = self.devices[addr as usize] {
            Some(d)
        } else {
            None
        }
    }

    /// Allocate a device with the next available address.
    pub fn next(&mut self) -> Option<&mut Device> {
        for i in 0..self.devices.len() {
            if self.devices[i].is_none() {
                let a = i.try_into().unwrap();
                let mut d: Device = Default::default();
                d.addr = a;
                self.devices[i] = Some(d);
                return self.device_for(a);
            }
        }
        None
    }

    /// Remove the device at address `addr`.
    pub fn remove(&mut self, addr: u8) -> Option<Device> {
        let v = core::mem::replace(&mut self.devices[addr as usize], None);
        v
    }
}

pub struct Device {
    addr: u8,
    max_packet_size: u8,
    endpoints: [Endpoint; MAX_ENDPOINTS],
}
impl Default for Device {
    fn default() -> Self {
        Self {
            addr: 0,
            max_packet_size: 8,
            endpoints: Default::default(),
        }
    }
}

pub struct Endpoint {
    num: u8,
    typ: EndpointType,
}
impl Default for Endpoint {
    fn default() -> Self {
        Self {
            num: 0,
            typ: EndpointType::Control,
        }
    }
}

enum EndpointType {
    Control,
    In,
    Out,
}