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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
use core::convert::TryFrom;

use embedded_time::duration::Extensions;
use heapless::Vec;
use interchange::{Interchange, Requester};

use crate::{
    constants::*,
    pipe::Pipe,
    types::{packet::RawPacket, ClassRequest, Status},
};

use usb_device::class_prelude::*;
type Result<T> = core::result::Result<T, UsbError>;

pub struct Ccid<'bus, Bus, I, const N: usize>
where
    Bus: 'static + UsbBus,
    I: 'static + Interchange<REQUEST = Vec<u8, N>, RESPONSE = Vec<u8, N>>,
{
    interface_number: InterfaceNumber,
    string_index: StringIndex,
    read: EndpointOut<'bus, Bus>,
    // interrupt: EndpointIn<'static, Bus>,
    pipe: Pipe<'bus, Bus, I, N>,
}

impl<'bus, Bus, I, const N: usize> Ccid<'bus, Bus, I, N>
where
    Bus: 'static + UsbBus,
    I: 'static + Interchange<REQUEST = Vec<u8, N>, RESPONSE = Vec<u8, N>>,
{
    /// Class constructor.
    ///
    /// The optional card issuer's data may be of length at most 13 bytes,
    /// and allows personalizing the Answer-to-Reset, for instance by
    /// ASCII-encoding vendor or model information.
    pub fn new(
        allocator: &'bus UsbBusAllocator<Bus>,
        request_pipe: Requester<I>,
        card_issuers_data: Option<&[u8]>,
    ) -> Self {
        let read = allocator.bulk(PACKET_SIZE as _);
        let write = allocator.bulk(PACKET_SIZE as _);
        // TODO: Add interrupt endpoint, so PC/SC does not
        // constantly poll us with GetSlotStatus
        //
        // PROBLEM: We don't have enough endpoints on the peripheral :/
        // (USBHS should have one more)
        // let interrupt = allocator.interrupt(8 as _, 32);
        let pipe = Pipe::new(write, request_pipe, card_issuers_data);
        let interface_number = allocator.interface();
        let string_index = allocator.string();
        Self {
            interface_number,
            string_index,
            read,
            /* interrupt, */ pipe,
        }
    }

    /// Read response from application (if any) and start writing it to
    /// the USB bus.  Should be called before managing Bus.
    pub fn check_for_app_response(&mut self) {
        self.poll();
    }

    pub fn did_start_processing(&mut self) -> Status {
        if self.pipe.did_start_processing() {
            // We should send a wait extension later
            Status::ReceivedData(1_000.milliseconds())
        } else {
            Status::Idle
        }
    }

    pub fn send_wait_extension(&mut self) -> Status {
        if self.pipe.send_wait_extension() {
            // We should send another wait extension later
            Status::ReceivedData(1_000.milliseconds())
        } else {
            Status::Idle
        }
    }
}

impl<'bus, Bus, I, const N: usize> UsbClass<Bus> for Ccid<'bus, Bus, I, N>
where
    Bus: 'static + UsbBus,
    I: 'static + Interchange<REQUEST = Vec<u8, N>, RESPONSE = Vec<u8, N>>,
{
    fn get_configuration_descriptors(&self, writer: &mut DescriptorWriter) -> Result<()> {
        writer.interface_alt(
            self.interface_number,
            0,
            CLASS_CCID,
            SUBCLASS_NONE,
            TransferMode::Bulk as u8,
            Some(self.string_index),
        )?;
        writer.write(FUNCTIONAL_INTERFACE, &FUNCTIONAL_INTERFACE_DESCRIPTOR)?;
        writer.endpoint(&self.pipe.write).unwrap();
        writer.endpoint(&self.read).unwrap();
        // writer.endpoint(&self.interrupt).unwrap();
        Ok(())
    }

    fn get_string(&self, index: StringIndex, _lang_id: u16) -> Option<&str> {
        (self.string_index == index).then_some(FUNCTIONAL_INTERFACE_STRING)
    }

    #[inline(never)]
    fn poll(&mut self) {
        // info_now!("poll of ccid");
        self.pipe.poll_app();
        self.pipe.maybe_send_packet();
    }

    fn endpoint_in_complete(&mut self, addr: EndpointAddress) {
        if addr != self.pipe.write.address() {
            return;
        }

        self.pipe.maybe_send_packet();
    }

    fn endpoint_out(&mut self, addr: EndpointAddress) {
        if addr != self.read.address() {
            return;
        }

        // let maybe_packet = RawPacket::try_from(
        //     |packet| self.read.read(packet));

        let maybe_packet = {
            let mut packet = RawPacket::new();
            packet.resize_default(packet.capacity()).unwrap();
            let result = self.read.read(&mut packet);
            result.map(|count| {
                assert!(count <= packet.len());
                packet.truncate(count);
                packet
            })
        };

        // should we return an error message
        // if the raw packet is invalid?
        match maybe_packet {
            Ok(packet) => self.pipe.handle_packet(packet),
            Err(_err) => {
                error!("Failed to read packet: {:?}", _err);
            }
        }
    }

    fn control_in(&mut self, transfer: ControlIn<Bus>) {
        use usb_device::control::*;
        let Request {
            request_type,
            recipient,
            index,
            request,
            ..
        } = *transfer.request();
        if index != u8::from(self.interface_number) as u16 {
            return;
        }

        if (request_type, recipient) == (RequestType::Class, Recipient::Interface) {
            match ClassRequest::try_from(request) {
                Ok(request) => {
                    match request {
                        // not strictly needed, as our bNumClockSupported = 0
                        ClassRequest::GetClockFrequencies => {
                            transfer.accept_with(&CLOCK_FREQUENCY_KHZ).ok();
                        }

                        // not strictly needed, as our bNumDataRatesSupported = 0
                        ClassRequest::GetDataRates => {
                            transfer.accept_with_static(&DATA_RATE_BPS).ok();
                        }
                        _ => panic!("unexpected direction for {:?}", &request),
                    }
                }

                Err(()) => {
                    info_now!("unexpected request: {}", request);
                    transfer.reject().ok();
                }
            }
        }
    }

    fn control_out(&mut self, transfer: ControlOut<Bus>) {
        use usb_device::control::*;
        let Request {
            request_type,
            recipient,
            index,
            request,
            value,
            ..
        } = *transfer.request();
        if index as u8 != u8::from(self.interface_number) {
            return;
        }

        if (request_type, recipient) == (RequestType::Class, Recipient::Interface) {
            match ClassRequest::try_from(request) {
                Ok(request) => {
                    match request {
                        ClassRequest::Abort => {
                            // spec: "slot in low, seq in high byte"
                            let [slot, seq] = value.to_le_bytes();
                            self.pipe.expect_abort(slot, seq);
                            transfer.accept().ok();

                            // // old behaviour
                            // transfer.reject().ok();
                            // todo!();
                        }
                        _ => panic!("unexpected direction for {:?}", &request),
                    }
                }

                Err(()) => {
                    info_now!("unexpected request: {}", request);
                }
            }
        }
    }
}