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
//! A cross platform Rust library that returns the vendor and product IDs of
//! currently connected USB devices
//!
//! [![Actions Status](https://github.com/timfish/usb-enumeration/workflows/Build/badge.svg)](https://github.com/timfish/usb-enumeration/actions)
//!
//! # Example
//! ```no_run
//! let devices = usb_enumeration::enumerate(None, None);
//!
//! println!("{:#?}", devices);
//!
//! // Outputs:
//! // [
//! //   UsbDevice {
//! //       id: "USB\\VID_0CE9&PID_1220\\0000000004BE",
//! //       vendor_id: 3305,
//! //       product_id: 4640,
//! //       description: Some(
//! //           "PicoScope 4000 series PC Oscilloscope",
//! //       ),
//! //   },
//! //   UsbDevice {
//! //       id: "USB\\VID_046D&PID_C52B\\5&17411534&0&11",
//! //       vendor_id: 1133,
//! //       product_id: 50475,
//! //       description: Some(
//! //           "USB Composite Device",
//! //       ),
//! //   },
//! //   UsbDevice {
//! //       id: "USB\\VID_046D&PID_C52B&MI_00\\6&12D311A2&0&0000",
//! //       vendor_id: 1133,
//! //       product_id: 50475,
//! //       description: Some(
//! //           "Logitech USB Input Device",
//! //       ),
//! //   },
//! //     etc...
//! // ]
//! ```
//! You can also subscribe to events using the `Observer`:
//! ```no_run
//! use usb_enumeration::{Observer, Event};
//!
//! let sub = Observer::new()
//!     .with_poll_interval(2)
//!     .with_vendor_id(0x1234)
//!     .with_product_id(0x5678)
//!     .subscribe();
//!
//! // when sub is dropped, the background thread will close
//!
//! for event in sub.rx_event.iter() {
//!     match event {
//!         Event::Initial(d) => println!("Initial devices: {:?}", d),
//!         Event::Connect(d) => println!("Connected device: {:?}", d),
//!         Event::Disconnect(d) => println!("Disconnected device: {:?}", d),
//!     }   
//! }
//! ```

#![cfg_attr(feature = "strict", deny(warnings))]

mod common;
pub use common::UsbDevice;
use crossbeam::channel::{bounded, unbounded, Receiver, Sender};
use std::{collections::HashSet, thread, time::Duration};

#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
use crate::windows::*;

#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
use crate::macos::*;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
use crate::linux::*;

/// # Enumerates connected USB devices
///
/// * `vendor_id` - Optional USB Vendor ID to filter
/// * `product_id` - Optional USB Product ID to filter
///
/// ```no_run
/// let devices = usb_enumeration::enumerate(None, None);
/// ```
/// You can also optionally filter by vendor or product ID:
/// ```no_run
/// let devices = usb_enumeration::enumerate(Some(0x1234), None);
/// ```
pub fn enumerate(vendor_id: Option<u16>, product_id: Option<u16>) -> Vec<UsbDevice> {
    enumerate_platform(vendor_id, product_id)
}

/// Events send from the Observer
#[derive(Debug, Clone)]
pub enum Event {
    /// Initial list of devices when polling starts
    Initial(Vec<UsbDevice>),
    /// A device that has just been connected
    Connect(UsbDevice),
    /// A device that has just disconnected
    Disconnect(UsbDevice),
}

#[derive(Clone)]
pub struct Subscription {
    pub rx_event: Receiver<Event>,
    // When this gets dropped, the channel will become disconnected and the
    // background thread will close
    tx_close: Sender<()>,
}

#[derive(Debug, Clone)]
pub struct Observer {
    poll_interval: u32,
    vendor_id: Option<u16>,
    product_id: Option<u16>,
}

impl Default for Observer {
    fn default() -> Self {
        Observer::new()
    }
}

impl Observer {
    /// Create a new Observer with the poll interval specified in seconds
    pub fn new() -> Self {
        Observer {
            poll_interval: 1,
            vendor_id: None,
            product_id: None,
        }
    }

    pub fn with_poll_interval(mut self, seconds: u32) -> Self {
        self.poll_interval = seconds;
        self
    }

    /// Filter results by USB Vendor ID
    pub fn with_vendor_id(mut self, vendor_id: u16) -> Self {
        self.vendor_id = Some(vendor_id);
        self
    }

    /// Filter results by USB Product ID
    pub fn with_product_id(mut self, product_id: u16) -> Self {
        self.product_id = Some(product_id);
        self
    }

    /// Start the background thread and poll for device changes
    pub fn subscribe(&self) -> Subscription {
        let (tx_event, rx_event) = unbounded();
        let (tx_close, rx_close) = bounded::<()>(0);

        thread::Builder::new()
            .name("USB Enumeration Thread".to_string())
            .spawn({
                let this = self.clone();
                move || {
                    let device_list = enumerate(this.vendor_id, this.product_id);

                    // Send initially connected devices
                    if tx_event.send(Event::Initial(device_list.clone())).is_err() {
                        return;
                    }

                    let mut device_list: HashSet<UsbDevice> = device_list.into_iter().collect();
                    let mut wait_seconds = this.poll_interval as f32;

                    loop {
                        while wait_seconds > 0.0 {
                            // Check whether the subscription has been disposed
                            if let Err(crossbeam::channel::RecvTimeoutError::Disconnected) =
                                rx_close.recv_timeout(Duration::from_millis(250))
                            {
                                return;
                            }

                            wait_seconds -= 0.25;
                        }

                        wait_seconds = this.poll_interval as f32;

                        let next_devices: HashSet<UsbDevice> =
                            enumerate(this.vendor_id, this.product_id)
                                .into_iter()
                                .collect();

                        // Send Disconnect for missing devices
                        for device in &device_list {
                            if !next_devices.contains(&device)
                                && tx_event.send(Event::Disconnect(device.clone())).is_err()
                            {
                                return;
                            }
                        }

                        // Send Connect for new devices
                        for device in &next_devices {
                            if !device_list.contains(&device)
                                && tx_event.send(Event::Connect(device.clone())).is_err()
                            {
                                return;
                            }
                        }

                        device_list = next_devices;
                    }
                }
            })
            .expect("Could not spawn background thread");

        Subscription { rx_event, tx_close }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_enumerate() {
        let devices = enumerate(None, None);
        println!("Enumerated devices: {:#?}", devices);
        assert!(!devices.is_empty());
    }

    #[test]
    fn test_subscribe() {
        let subscription = Observer::new().subscribe();
        let mut iter = subscription.rx_event.iter();

        let initial = iter.next().expect("Should get an Event");
        assert!(matches!(initial, Event::Initial(_)));

        println!("Connect a USB device");

        let connect_event = iter.next().expect("Should get an Event");
        let connect_device = if let Event::Connect(device) = connect_event {
            device
        } else {
            panic!("Expected Event::Connect. Actual: {:?}", connect_event);
        };

        println!("Disconnect that same device");

        let disconnect_event = iter.next().expect("Should get an Event");
        let disconnect_device = if let Event::Disconnect(device) = disconnect_event {
            device
        } else {
            panic!("Expected Event::Disconnect. Actual: {:?}", disconnect_event);
        };

        assert_eq!(connect_device, disconnect_device);
    }
}