cross_usb 0.4.1

A Rust USB library which works seamlessly across both native and WASM targets.
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//#![cfg_attr(debug_assertions, allow(dead_code, unused_imports))]
use wasm_bindgen::prelude::*;

use js_sys::{Array, Object, Promise, Uint8Array};
use wasm_bindgen_futures::JsFuture;
use web_sys::{
    UsbControlTransferParameters, UsbDevice as WasmUsbDevice, UsbDeviceRequestOptions,
    UsbInTransferResult, UsbOutTransferResult, UsbRecipient, UsbRequestType,
};

// Crate stuff
use crate::usb::{
    ControlIn, ControlOut, ControlType, UsbDeviceInfo, UsbDevice, UsbInterface, Recipient, Error,
};

#[wasm_bindgen]
#[derive(Debug)]
pub struct DeviceInfo {
    device: WasmUsbDevice,
}

#[wasm_bindgen]
#[derive(Debug)]
pub struct Device {
    device: WasmUsbDevice,
}

#[wasm_bindgen]
#[derive(Debug)]
pub struct Interface {
    device: WasmUsbDevice,
    _number: u8,
}

#[wasm_bindgen]
#[derive(PartialEq, Clone, Default)]
pub struct DeviceFilter {
    pub vendor_id: Option<u16>,
    pub product_id: Option<u16>,
    pub class: Option<u8>,
    pub subclass: Option<u8>,
    pub protocol: Option<u8>,
}

impl DeviceFilter {
    pub fn new(
        vendor_id: Option<u16>,
        product_id: Option<u16>,
        class: Option<u8>,
        subclass: Option<u8>,
        protocol: Option<u8>,
    ) -> Self {
        Self {
            vendor_id,
            product_id,
            class,
            subclass,
            protocol,
        }
    }
}

#[wasm_bindgen]
pub async fn get_device(device_filter: Vec<DeviceFilter>) -> Result<DeviceInfo, js_sys::Error> {
    let window = web_sys::window().unwrap();

    let navigator = window.navigator();
    let usb = navigator.usb();

    let device_list: Array = match JsFuture::from(Promise::resolve(&usb.get_devices())).await {
        Ok(list) => list.into(),
        Err(_) => Array::new(),
    };

    // Check if the device is already paired, if so, we don't need to request it again
    for js_device in device_list {
        let device: WasmUsbDevice = js_device.into();

        if device_filter.iter().any(|info| {
            let mut result = false;

            if info.vendor_id.is_some() {
                result = info.vendor_id.unwrap() == device.vendor_id();
            }

            if info.product_id.is_some() {
                result = info.product_id.unwrap() == device.product_id();
            }

            if info.class.is_some() {
                result = info.class.unwrap() == device.device_class();
            }

            if info.subclass.is_some() {
                result = info.subclass.unwrap() == device.device_subclass();
            }

            if info.protocol.is_some() {
                result = info.protocol.unwrap() == device.device_protocol();
            }

            result
        }) {
            let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
            return Ok(DeviceInfo { device });
        }
    }

    let arr = Array::new();
    for filter in device_filter {
        let js_filter = js_sys::Object::new();
        if let Some(vid) = filter.vendor_id {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("vendorId"),
                &JsValue::from(vid),
            )
            .unwrap();
        }
        if let Some(pid) = filter.product_id {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("productId"),
                &JsValue::from(pid),
            )
            .unwrap();
        }
        if let Some(class) = filter.class {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("classCode"),
                &JsValue::from(class),
            )
            .unwrap();
        }
        if let Some(subclass) = filter.subclass {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("subclassCode"),
                &JsValue::from(subclass),
            )
            .unwrap();
        }
        if let Some(pro) = filter.protocol {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("protocolCode"),
                &JsValue::from(pro),
            )
            .unwrap();
        }
        arr.push(&js_filter);
    }

    let filters = JsValue::from(&arr);
    let filters2 = UsbDeviceRequestOptions::new(&filters);

    let device: WasmUsbDevice = JsFuture::from(Promise::resolve(&usb.request_device(&filters2)))
        .await?
        .into();

    let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;

    Ok(DeviceInfo { device })
}

#[wasm_bindgen]
pub async fn get_device_list(device_filter: Vec<DeviceFilter>) -> Result<Vec<DeviceInfo>, js_sys::Error> {
    let window = web_sys::window().unwrap();

    let navigator = window.navigator();
    let usb = navigator.usb();

    let device_list: Array = match JsFuture::from(Promise::resolve(&usb.get_devices())).await {
        Ok(list) => list.into(),
        Err(_) => Array::new(),
    };

    let mut devices = Vec::new();
    // Check if the device is already paired, if so, we don't need to request it again
    for js_device in device_list {
        let device: WasmUsbDevice = js_device.into();

        if device_filter.iter().any(|info| {
            let mut result = false;

            if info.vendor_id.is_some() {
                result = info.vendor_id.unwrap() == device.vendor_id();
            }

            if info.product_id.is_some() {
                result = info.product_id.unwrap() == device.product_id();
            }

            if info.class.is_some() {
                result = info.class.unwrap() == device.device_class();
            }

            if info.subclass.is_some() {
                result = info.subclass.unwrap() == device.device_subclass();
            }

            if info.protocol.is_some() {
                result = info.protocol.unwrap() == device.device_protocol();
            }

            result
        }) {
            let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;
            devices.push(DeviceInfo { device });
        }
    }

    let arr = Array::new();
    for filter in device_filter {
        let js_filter = js_sys::Object::new();
        if let Some(vid) = filter.vendor_id {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("vendorId"),
                &JsValue::from(vid),
            )
            .unwrap();
        }
        if let Some(pid) = filter.product_id {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("productId"),
                &JsValue::from(pid),
            )
            .unwrap();
        }
        if let Some(class) = filter.class {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("classCode"),
                &JsValue::from(class),
            )
            .unwrap();
        }
        if let Some(subclass) = filter.subclass {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("subclassCode"),
                &JsValue::from(subclass),
            )
            .unwrap();
        }
        if let Some(pro) = filter.protocol {
            js_sys::Reflect::set(
                &js_filter,
                &JsValue::from_str("protocolCode"),
                &JsValue::from(pro),
            )
            .unwrap();
        }
        arr.push(&js_filter);
    }

    let filters = JsValue::from(&arr);
    let filters2 = UsbDeviceRequestOptions::new(&filters);

    let device: WasmUsbDevice = JsFuture::from(Promise::resolve(&usb.request_device(&filters2)))
        .await?
        .into();

    let _open_promise = JsFuture::from(Promise::resolve(&device.open())).await?;

    devices.push(DeviceInfo { device });

    return Ok(devices);
}

impl UsbDeviceInfo for DeviceInfo {
    type Device = Device;

    async fn open(self) -> Result<Self::Device, Error> {
        Ok(Self::Device {
            device: self.device,
        })
    }

    async fn product_id(&self) -> u16 {
        self.device.product_id()
    }

    async fn vendor_id(&self) -> u16 {
        self.device.vendor_id()
    }

    async fn class(&self) -> u8 {
        self.device.device_class()
    }

    async fn subclass(&self) -> u8 {
        self.device.device_subclass()
    }

    async fn manufacturer_string(&self) -> Option<String> {
        self.device.manufacturer_name()
    }

    async fn product_string(&self) -> Option<String> {
        self.device.product_name()
    }
}

impl UsbDevice for Device {
    type Interface = Interface;

    async fn open_interface(&self, number: u8) -> Result<Interface, Error> {
        let dev_promise =
            JsFuture::from(Promise::resolve(&self.device.claim_interface(number))).await;

        // Wait for the interface to be claimed
        let _device: WasmUsbDevice = match dev_promise {
            Ok(dev) => dev.into(),
            Err(err) => {
                return Err(Error::CommunicationError(
                    err.as_string().unwrap_or_default(),
                ));
            }
        };

        Ok(Interface {
            device: self.device.clone(),
            _number: number,
        })
    }

    async fn detach_and_open_interface(&self, number: u8) -> Result<Self::Interface, Error> {
        self.open_interface(number).await
    }

    async fn reset(&self) -> Result<(), Error> {
        let result = JsFuture::from(Promise::resolve(&self.device.reset())).await;

        match result {
            Ok(_) => Ok(()),
            Err(err) => Err(Error::CommunicationError(
                err.as_string().unwrap_or_default(),
            )),
        }
    }

    async fn forget(&self) -> Result<(), Error> {
        let result = JsFuture::from(Promise::resolve(&self.device.forget())).await;

        match result {
            Ok(_) => Ok(()),
            Err(err) => Err(Error::CommunicationError(
                err.as_string().unwrap_or_default(),
            )),
        }
    }

    async fn vendor_id(&self) -> u16 {
        self.device.vendor_id()
    }

    async fn product_id(&self) -> u16 {
        self.device.product_id()
    }

    async fn class(&self) -> u8 {
        self.device.device_class()
    }

    async fn subclass(&self) -> u8 {
        self.device.device_subclass()
    }

    async fn manufacturer_string(&self) -> Option<String> {
        self.device.manufacturer_name()
    }

    async fn product_string(&self) -> Option<String> {
        self.device.product_name()
    }
}

impl<'a> UsbInterface<'a> for Interface {
    async fn control_in(&self, data: crate::usb::ControlIn) -> Result<Vec<u8>, Error> {
        let length = data.length;
        let params: UsbControlTransferParameters = data.into();

        let promise = Promise::resolve(&self.device.control_transfer_in(&params, length));
        let result = JsFuture::from(promise).await;

        let transfer_result: UsbInTransferResult = match result {
            Ok(res) => res.into(),
            Err(_) => return Err(Error::TransferError),
        };

        let data = match transfer_result.data() {
            Some(res) => res.buffer(),
            None => return Err(Error::TransferError),
        };

        let array = Uint8Array::new(&data);

        Ok(array.to_vec())
    }

    async fn control_out(&self, data: crate::usb::ControlOut<'a>) -> Result<usize, Error> {
        let array = Uint8Array::from(data.data);
        let array_obj = Object::try_from(&array).unwrap();
        let params: UsbControlTransferParameters = data.into();

        let result: UsbOutTransferResult = match JsFuture::from(Promise::resolve(
            &self
                .device
                .control_transfer_out_with_buffer_source(&params, array_obj)
                .map_err(|j| Error::CommunicationError(j.as_string().unwrap_or_default()))?
                .into(),
        ))
        .await
        {
            Ok(res) => res.into(),
            Err(_) => return Err(Error::TransferError),
        };

        Ok(result.bytes_written() as usize)
    }

    async fn bulk_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, Error> {
        let promise = Promise::resolve(&self.device.transfer_in(endpoint, length as u32));

        let result = JsFuture::from(promise).await;

        let transfer_result: UsbInTransferResult = match result {
            Ok(res) => res.into(),
            Err(_) => return Err(Error::TransferError),
        };

        let data = match transfer_result.data() {
            Some(res) => res.buffer(),
            None => return Err(Error::TransferError),
        };

        let array = Uint8Array::new(&data);

        Ok(array.to_vec())
    }

    async fn bulk_out(&self, endpoint: u8, data: &[u8]) -> Result<usize, Error> {
        let array = Uint8Array::from(data);
        let array_obj = Object::try_from(&array).unwrap();

        let promise = Promise::resolve(
            &self
                .device
                .transfer_out_with_buffer_source(endpoint, array_obj)
                .map_err(|j| Error::CommunicationError(j.as_string().unwrap_or_default()))?
                .into(),
        );

        let result = JsFuture::from(promise).await;

        let transfer_result: UsbOutTransferResult = match result {
            Ok(res) => res.into(),
            Err(_) => return Err(Error::TransferError),
        };

        Ok(transfer_result.bytes_written() as usize)
    }

    /*
    async fn interrupt_in(&self, endpoint: u8, length: usize) -> Result<Vec<u8>, UsbError> {
        let promise = Promise::resolve(&self.device.transfer_in(endpoint, length as u32));

        let result = JsFuture::from(promise).await;

        let transfer_result: UsbInTransferResult = match result {
            Ok(res) => res.into(),
            Err(_) => return Err(UsbError::TransferError),
        };

        if transfer_result.

        let data = match transfer_result.data() {
            Some(res) => res.buffer(),
            None => return Err(UsbError::TransferError),
        };

        let array = Uint8Array::new(&data);

        Ok(array.to_vec())
    }

    async fn interrupt_out(&self, endpoint: u8, buf: Vec<u8>) -> Result<usize, UsbError> {
        todo!()
    }
    */
}

impl From<ControlIn> for UsbControlTransferParameters {
    fn from(value: ControlIn) -> Self {
        UsbControlTransferParameters::new(
            value.index,
            value.recipient.into(),
            value.request,
            value.control_type.into(),
            value.value,
        )
    }
}

impl From<ControlOut<'_>> for UsbControlTransferParameters {
    fn from(value: ControlOut) -> Self {
        UsbControlTransferParameters::new(
            value.index,
            value.recipient.into(),
            value.request,
            value.control_type.into(),
            value.value,
        )
    }
}

impl From<Recipient> for UsbRecipient {
    fn from(value: Recipient) -> Self {
        match value {
            Recipient::Device => UsbRecipient::Device,
            Recipient::Interface => UsbRecipient::Interface,
            Recipient::Endpoint => UsbRecipient::Endpoint,
            Recipient::Other => UsbRecipient::Other,
        }
    }
}

impl From<ControlType> for UsbRequestType {
    fn from(value: ControlType) -> Self {
        match value {
            ControlType::Standard => UsbRequestType::Standard,
            ControlType::Class => UsbRequestType::Class,
            ControlType::Vendor => UsbRequestType::Vendor,
        }
    }
}