erpc_rust 0.1.3

Rust implementation of eRPC (Embedded RPC) protocol
Documentation
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use async_trait::async_trait;
use futures::{
    channel::oneshot,
    future::{select, Either},
    pin_mut,
};
use futures_timer::Delay;
use rusb::{Direction, TransferType, UsbContext};
use std::{
    sync::mpsc,
    thread,
    time::{Duration, Instant},
};

use crate::{error::TransportError, ErpcResult};

use super::FramedTransport;

const MAX_CHUNK_SIZE: usize = 512;
const VENDOR_SPECIFIC_CLASS: u8 = 0xff;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UsbDirection {
    In,
    Out,
}

impl UsbDirection {
    fn from_rusb(direction: Direction) -> Self {
        match direction {
            Direction::In => Self::In,
            Direction::Out => Self::Out,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UsbTransferType {
    Bulk,
    Other,
}

impl UsbTransferType {
    fn from_rusb(transfer_type: TransferType) -> Self {
        match transfer_type {
            TransferType::Bulk => Self::Bulk,
            _ => Self::Other,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EndpointAddress {
    pub address: u8,
    pub direction: UsbDirection,
    pub transfer_type: UsbTransferType,
}

impl EndpointAddress {
    pub fn bulk_in(address: u8) -> Self {
        Self {
            address,
            direction: UsbDirection::In,
            transfer_type: UsbTransferType::Bulk,
        }
    }

    pub fn bulk_out(address: u8) -> Self {
        Self {
            address,
            direction: UsbDirection::Out,
            transfer_type: UsbTransferType::Bulk,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterfaceCandidate {
    pub interface_number: u8,
    pub alternate_setting: u8,
    pub class_code: u8,
    pub endpoints: Vec<EndpointAddress>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectedInterface {
    pub interface_number: u8,
    pub alternate_setting: u8,
    pub endpoint_in: u8,
    pub endpoint_out: u8,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionError {
    VendorInterfaceNotFound,
    MissingBulkPair,
}

impl std::fmt::Display for SelectionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SelectionError::VendorInterfaceNotFound => write!(f, "Vendor interface not found"),
            SelectionError::MissingBulkPair => {
                write!(f, "Missing bulk IN/OUT endpoints for vendor interface")
            }
        }
    }
}

pub fn select_interface_and_endpoints(
    candidates: &[InterfaceCandidate],
) -> Result<SelectedInterface, SelectionError> {
    let mut saw_vendor_interface = false;

    for candidate in candidates {
        if candidate.class_code != VENDOR_SPECIFIC_CLASS {
            continue;
        }

        saw_vendor_interface = true;

        let endpoint_in = candidate
            .endpoints
            .iter()
            .find(|endpoint| {
                endpoint.transfer_type == UsbTransferType::Bulk
                    && endpoint.direction == UsbDirection::In
            })
            .map(|endpoint| endpoint.address);
        let endpoint_out = candidate
            .endpoints
            .iter()
            .find(|endpoint| {
                endpoint.transfer_type == UsbTransferType::Bulk
                    && endpoint.direction == UsbDirection::Out
            })
            .map(|endpoint| endpoint.address);

        if let (Some(endpoint_in), Some(endpoint_out)) = (endpoint_in, endpoint_out) {
            return Ok(SelectedInterface {
                interface_number: candidate.interface_number,
                alternate_setting: candidate.alternate_setting,
                endpoint_in,
                endpoint_out,
            });
        }
    }

    if saw_vendor_interface {
        Err(SelectionError::MissingBulkPair)
    } else {
        Err(SelectionError::VendorInterfaceNotFound)
    }
}

enum WorkerCommand {
    Send {
        data: Vec<u8>,
        timeout: Duration,
        reply: oneshot::Sender<ErpcResult<()>>,
    },
    Receive {
        length: usize,
        timeout: Duration,
        reply: oneshot::Sender<ErpcResult<Vec<u8>>>,
    },
    Close {
        reply: oneshot::Sender<ErpcResult<()>>,
    },
}

struct WorkerState {
    handle: rusb::DeviceHandle<rusb::Context>,
    endpoint_out: u8,
    endpoint_in: u8,
    interface_number: u8,
    read_buffer: Vec<u8>,
}

impl WorkerState {
    fn send(&mut self, data: &[u8], timeout: Duration) -> ErpcResult<()> {
        let start_time = Instant::now();

        for chunk in data.chunks(MAX_CHUNK_SIZE) {
            let remaining_timeout = timeout.saturating_sub(start_time.elapsed());
            if remaining_timeout.is_zero() {
                return Err(TransportError::Timeout.into());
            }

            let written = self
                .handle
                .write_bulk(self.endpoint_out, chunk, remaining_timeout)
                .map_err(|e| TransportError::SendFailed(e.to_string()))?;

            if written != chunk.len() {
                return Err(
                    TransportError::SendFailed("partial USB bulk write".to_string()).into(),
                );
            }
        }

        Ok(())
    }

    fn receive(&mut self, length: usize, timeout: Duration) -> ErpcResult<Vec<u8>> {
        if self.read_buffer.len() < length {
            let start_time = Instant::now();

            while self.read_buffer.len() < length {
                let remaining_timeout = timeout.saturating_sub(start_time.elapsed());
                if remaining_timeout.is_zero() {
                    return Err(TransportError::Timeout.into());
                }

                let mut temp_buf = [0u8; MAX_CHUNK_SIZE];
                let read_count = self
                    .handle
                    .read_bulk(self.endpoint_in, &mut temp_buf, remaining_timeout)
                    .map_err(|e| TransportError::ReceiveFailed(e.to_string()))?;

                if read_count > 0 {
                    self.read_buffer.extend_from_slice(&temp_buf[..read_count]);
                }

                if read_count < MAX_CHUNK_SIZE {
                    break;
                }
            }
        }

        let available_data = self.read_buffer.len().min(length);
        Ok(self.read_buffer.drain(..available_data).collect())
    }

    fn close(mut self) -> ErpcResult<()> {
        self.handle
            .release_interface(self.interface_number)
            .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;
        Ok(())
    }
}

fn spawn_worker(state: WorkerState) -> mpsc::Sender<WorkerCommand> {
    let (tx, rx) = mpsc::channel::<WorkerCommand>();

    thread::spawn(move || {
        let mut state = state;

        while let Ok(command) = rx.recv() {
            match command {
                WorkerCommand::Send {
                    data,
                    timeout,
                    reply,
                } => {
                    let _ = reply.send(state.send(&data, timeout));
                }
                WorkerCommand::Receive {
                    length,
                    timeout,
                    reply,
                } => {
                    let _ = reply.send(state.receive(length, timeout));
                }
                WorkerCommand::Close { reply } => {
                    let result = state.close();
                    let _ = reply.send(result);
                    return;
                }
            }
        }

        let _ = state.close();
    });

    tx
}

/// USB transport kept under the historical `rusb` module name for API compatibility.
///
/// Blocking USB I/O is isolated inside a worker thread so the async API does not block the caller's executor thread.
pub struct RusbTransport {
    worker_tx: Option<mpsc::Sender<WorkerCommand>>,
    timeout: Duration,
    connected: bool,
}

impl RusbTransport {
    pub async fn connect(vendor_id: u16, product_id: u16) -> ErpcResult<Self> {
        let context =
            rusb::Context::new().map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;
        let devices = context
            .devices()
            .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;

        for device in devices.iter() {
            let descriptor = device
                .device_descriptor()
                .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;

            if descriptor.vendor_id() != vendor_id || descriptor.product_id() != product_id {
                continue;
            }

            let config = device
                .config_descriptor(0)
                .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;
            let candidates = config
                .interfaces()
                .flat_map(|interface| interface.descriptors())
                .map(|descriptor| InterfaceCandidate {
                    interface_number: descriptor.interface_number(),
                    alternate_setting: descriptor.setting_number(),
                    class_code: descriptor.class_code(),
                    endpoints: descriptor
                        .endpoint_descriptors()
                        .map(|endpoint| EndpointAddress {
                            address: endpoint.address(),
                            direction: UsbDirection::from_rusb(endpoint.direction()),
                            transfer_type: UsbTransferType::from_rusb(endpoint.transfer_type()),
                        })
                        .collect(),
                })
                .collect::<Vec<_>>();

            let selected = select_interface_and_endpoints(&candidates)
                .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;

            let handle = device
                .open()
                .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;

            #[cfg(not(target_os = "windows"))]
            handle
                .set_auto_detach_kernel_driver(true)
                .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;
            #[cfg(target_os = "windows")]
            {
                if let Err(e) = handle.set_auto_detach_kernel_driver(true) {
                    if e != rusb::Error::NotSupported {
                        return Err(TransportError::ConnectionFailed(e.to_string()).into());
                    }
                }
            }

            handle
                .claim_interface(selected.interface_number)
                .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;

            if selected.alternate_setting != 0 {
                handle
                    .set_alternate_setting(selected.interface_number, selected.alternate_setting)
                    .map_err(|e| TransportError::ConnectionFailed(e.to_string()))?;
            }

            let worker_tx = spawn_worker(WorkerState {
                handle,
                endpoint_out: selected.endpoint_out,
                endpoint_in: selected.endpoint_in,
                interface_number: selected.interface_number,
                read_buffer: Vec::new(),
            });

            return Ok(Self {
                worker_tx: Some(worker_tx),
                timeout: Duration::from_millis(600),
                connected: true,
            });
        }

        Err(TransportError::ConnectionFailed("Device not found".to_string()).into())
    }

    fn worker_tx(&self) -> ErpcResult<mpsc::Sender<WorkerCommand>> {
        self.worker_tx
            .as_ref()
            .cloned()
            .ok_or_else(|| TransportError::Closed.into())
    }
}

async fn await_reply<T>(receiver: oneshot::Receiver<ErpcResult<T>>, timeout: Duration) -> ErpcResult<T> {
    let reply = receiver;
    let delay = Delay::new(timeout);
    pin_mut!(reply);
    pin_mut!(delay);

    match select(reply, delay).await {
        Either::Left((result, _)) => {
            result.map_err(|_| crate::ErpcError::from(TransportError::Closed))?
        }
        Either::Right((_, _)) => Err(TransportError::Timeout.into()),
    }
}

#[async_trait]
impl FramedTransport for RusbTransport {
    async fn base_send(&mut self, data: &[u8]) -> ErpcResult<()> {
        if !self.connected {
            return Err(TransportError::Closed.into());
        }

        let worker_tx = self.worker_tx()?;
        let (reply_tx, reply_rx) = oneshot::channel();
        worker_tx
            .send(WorkerCommand::Send {
                data: data.to_vec(),
                timeout: self.timeout,
                reply: reply_tx,
            })
            .map_err(|_| TransportError::Closed)?;

        await_reply(reply_rx, self.timeout + self.timeout).await
    }

    async fn base_receive(&mut self, length: usize) -> ErpcResult<Vec<u8>> {
        if !self.connected {
            return Err(TransportError::Closed.into());
        }

        let worker_tx = self.worker_tx()?;
        let (reply_tx, reply_rx) = oneshot::channel();
        worker_tx
            .send(WorkerCommand::Receive {
                length,
                timeout: self.timeout,
                reply: reply_tx,
            })
            .map_err(|_| TransportError::Closed)?;

        await_reply(reply_rx, self.timeout + self.timeout).await
    }

    fn is_connected(&self) -> bool {
        self.connected
    }

    async fn close(&mut self) -> ErpcResult<()> {
        if !self.connected {
            return Ok(());
        }

        self.connected = false;

        if let Some(worker_tx) = self.worker_tx.take() {
            let (reply_tx, reply_rx) = oneshot::channel();
            worker_tx
                .send(WorkerCommand::Close { reply: reply_tx })
                .map_err(|_| TransportError::Closed)?;
            await_reply(reply_rx, self.timeout + self.timeout).await?;
        }

        Ok(())
    }

    fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }
}