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
use libc::{c_int, timeval};
use std::{mem, ptr, sync::Arc, sync::Once, time::Duration};
#[cfg(unix)]
use std::os::unix::io::RawFd;
use crate::hotplug::{Hotplug, HotplugBuilder, Registration};
use crate::{device_handle::DeviceHandle, device_list::DeviceList, error};
use libusb1_sys::{constants::*, *};
#[cfg(windows)]
type Seconds = ::libc::c_long;
#[cfg(windows)]
type MicroSeconds = ::libc::c_long;
#[cfg(not(windows))]
type Seconds = ::libc::time_t;
#[cfg(not(windows))]
type MicroSeconds = ::libc::suseconds_t;
#[derive(Copy, Clone, Eq, PartialEq, Default)]
pub struct GlobalContext {}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Context {
context: Arc<ContextInner>,
}
#[derive(Debug, Eq, PartialEq)]
struct ContextInner {
inner: ptr::NonNull<libusb_context>,
}
impl Drop for ContextInner {
fn drop(&mut self) {
unsafe {
libusb_exit(self.inner.as_ptr());
}
}
}
unsafe impl Sync for Context {}
unsafe impl Send for Context {}
pub trait UsbContext: Clone + Sized + Send + Sync {
fn as_raw(&self) -> *mut libusb_context;
fn devices(&self) -> crate::Result<DeviceList<Self>> {
DeviceList::new_with_context(self.clone())
}
fn open_device_with_vid_pid(
&self,
vendor_id: u16,
product_id: u16,
) -> Option<DeviceHandle<Self>> {
let handle =
unsafe { libusb_open_device_with_vid_pid(self.as_raw(), vendor_id, product_id) };
let ptr = std::ptr::NonNull::new(handle)?;
Some(unsafe { DeviceHandle::from_libusb(self.clone(), ptr) })
}
#[cfg(unix)]
#[doc(alias = "libusb_wrap_sys_device")]
unsafe fn open_device_with_fd(&self, fd: RawFd) -> crate::Result<DeviceHandle<Self>> {
let mut handle = mem::MaybeUninit::<*mut libusb_device_handle>::uninit();
match libusb_wrap_sys_device(self.as_raw(), fd as _, handle.as_mut_ptr()) {
0 => {
let ptr =
std::ptr::NonNull::new(handle.assume_init()).ok_or(crate::Error::NoDevice)?;
Ok(DeviceHandle::from_libusb(self.clone(), ptr))
}
err => Err(error::from_libusb(err)),
}
}
fn set_log_level(&mut self, level: LogLevel) {
unsafe {
libusb_set_debug(self.as_raw(), level.as_c_int());
}
}
#[deprecated(since = "0.9.0", note = "Use HotplugBuilder")]
fn register_callback(
&self,
vendor_id: Option<u16>,
product_id: Option<u16>,
class: Option<u8>,
callback: Box<dyn Hotplug<Self>>,
) -> crate::Result<Registration<Self>> {
let mut builder = HotplugBuilder::new();
let mut builder = &mut builder;
if let Some(vendor_id) = vendor_id {
builder = builder.vendor_id(vendor_id)
}
if let Some(product_id) = product_id {
builder = builder.product_id(product_id)
}
if let Some(class) = class {
builder = builder.class(class)
}
builder.register(self, callback)
}
fn unregister_callback(&self, _reg: Registration<Self>) {}
fn handle_events(&self, timeout: Option<Duration>) -> crate::Result<()> {
let n = unsafe {
match timeout {
Some(t) => {
let tv = timeval {
tv_sec: t.as_secs() as Seconds,
tv_usec: t.subsec_nanos() as MicroSeconds / 1000,
};
libusb_handle_events_timeout_completed(self.as_raw(), &tv, ptr::null_mut())
}
None => libusb_handle_events_completed(self.as_raw(), ptr::null_mut()),
}
};
if n < 0 {
Err(error::from_libusb(n as c_int))
} else {
Ok(())
}
}
#[doc(alias = "libusb_interrupt_event_handler")]
fn interrupt_handle_events(&self) {
unsafe { libusb_interrupt_event_handler(self.as_raw()) }
}
fn next_timeout(&self) -> crate::Result<Option<Duration>> {
let mut tv = timeval {
tv_sec: 0,
tv_usec: 0,
};
let n = unsafe { libusb_get_next_timeout(self.as_raw(), &mut tv) };
if n < 0 {
Err(error::from_libusb(n as c_int))
} else if n == 0 {
Ok(None)
} else {
let duration = Duration::new(tv.tv_sec as _, (tv.tv_usec * 1000) as _);
Ok(Some(duration))
}
}
}
impl UsbContext for Context {
fn as_raw(&self) -> *mut libusb_context {
self.context.inner.as_ptr()
}
}
impl UsbContext for GlobalContext {
fn as_raw(&self) -> *mut libusb_context {
static mut USB_CONTEXT: *mut libusb_context = ptr::null_mut();
static ONCE: Once = Once::new();
ONCE.call_once(|| {
let mut context = mem::MaybeUninit::<*mut libusb_context>::uninit();
unsafe {
USB_CONTEXT = match libusb_init(context.as_mut_ptr()) {
0 => context.assume_init(),
err => panic!(
"Can't init Global usb context, error {:?}",
error::from_libusb(err)
),
}
};
});
unsafe { USB_CONTEXT }
}
}
impl Context {
pub fn new() -> crate::Result<Self> {
let mut context = mem::MaybeUninit::<*mut libusb_context>::uninit();
try_unsafe!(libusb_init(context.as_mut_ptr()));
Ok(Context {
context: unsafe {
Arc::new(ContextInner {
inner: ptr::NonNull::new_unchecked(context.assume_init()),
})
},
})
}
pub fn with_options(opts: &[crate::UsbOption]) -> crate::Result<Self> {
let mut this = Self::new()?;
for opt in opts {
opt.apply(&mut this)?;
}
Ok(this)
}
}
#[derive(Clone, Copy)]
pub enum LogLevel {
None,
Error,
Warning,
Info,
Debug,
}
impl LogLevel {
pub(crate) fn as_c_int(self) -> c_int {
match self {
LogLevel::None => LIBUSB_LOG_LEVEL_NONE,
LogLevel::Error => LIBUSB_LOG_LEVEL_ERROR,
LogLevel::Warning => LIBUSB_LOG_LEVEL_WARNING,
LogLevel::Info => LIBUSB_LOG_LEVEL_INFO,
LogLevel::Debug => LIBUSB_LOG_LEVEL_DEBUG,
}
}
}