Debian Codegraph @

usb1/_libusb1.py

raw symbols SCIP
1 # Copyright (C) 2010-2021 Vincent Pelletier <[email protected]>
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17 # pylint: disable=invalid-name, too-few-public-methods, too-many-arguments
18 # pylint: disable=missing-docstring, too-many-lines
19 """
20 Python ctypes bindings for libusb-1.0.
21
22 You should not need to import this if you use usb1 module.
23
24 Declares all constants, data structures and exported symbols.
25 Some are only available after calling loadLibrary.
26 """
27 from ctypes import (
28 Structure, LittleEndianStructure,
29 Union,
30 CFUNCTYPE, POINTER, addressof, sizeof, cast,
31 c_short, c_int, c_uint, c_long, c_longlong,
32 c_uint8, c_uint16, c_uint32,
33 c_void_p, c_char_p, py_object, pointer, c_char,
34 c_ssize_t, CDLL
35 )
36 import ctypes.util
37 import errno
38 import os.path
39 import platform
40 import sys
41 from threading import Lock
42
43 class Enum:
44 def __init__(self, member_dict, scope_dict=None):
45 if scope_dict is None:
46 # Affect caller's locals, not this module's.
47 # pylint: disable=protected-access
48 scope_dict = sys._getframe(1).f_locals
49 # pylint: enable=protected-access
50 forward_dict = {}
51 reverse_dict = {}
52 next_value = 0
53 for name, value in member_dict.items():
54 if value is None:
55 value = next_value
56 next_value += 1
57 forward_dict[name] = value
58 if value in reverse_dict:
59 raise ValueError(
60 'Multiple names for value '
61 f'{value!r}: {reverse_dict[value]!r}, {name!r}'
62 )
63 reverse_dict[value] = name
64 scope_dict[name] = value
65 self.forward_dict = forward_dict
66 self.reverse_dict = reverse_dict
67
68 def __call__(self, value):
69 return self.reverse_dict[value]
70
71 def get(self, value, default=None):
72 return self.reverse_dict.get(value, default)
73
74 def buffer_at(address, length):
75 """
76 Simular to ctypes.string_at, but zero-copy and requires an integer address.
77 """
78 return bytearray((c_char * length).from_address(address))
79
80 _desc_type_dict = {
81 'b': c_uint8,
82 'bcd': c_uint16,
83 'bm': c_uint8,
84 'dw': c_uint32,
85 'i': c_uint8,
86 'id': c_uint16,
87 'w': c_uint16,
88 }
89
90 def newStruct(field_name_list):
91 """
92 Create a ctype structure class based on USB standard field naming
93 (type-prefixed).
94 """
95 field_list = []
96 append = field_list.append
97 for field in field_name_list:
98 type_prefix = ''
99 for char in field:
100 if not char.islower():
101 break
102 type_prefix += char
103 append((field, _desc_type_dict[type_prefix]))
104 result = type('some_descriptor', (LittleEndianStructure, ), {})
105 # Not using type()'s 3rd param to initialise class, as per ctypes
106 # documentation:
107 # _pack_ must already be defined when _fields_ is assigned, otherwise it
108 # will have no effect.
109 # pylint: disable=protected-access
110 result._pack_ = 1
111 result._fields_ = field_list
112 # pylint: enable=protected-access
113 return result
114
115 def newDescriptor(field_name_list):
116 """
117 Create a USB descriptor ctype structure, ie starting with bLength and
118 bDescriptorType fields.
119
120 See newStruct().
121 """
122 return newStruct(['bLength', 'bDescriptorType'] + list(field_name_list))
123
124 # Stand-in for the function until libusb is loaded - if the current libusb
125 # version has this export.
126 def libusb_strerror(_unused_errcode):
127 return None
128
129 class USBError(Exception):
130 value = None
131
132 def __init__(self, value=None):
133 Exception.__init__(self)
134 if value is not None:
135 self.value = value
136
137 def __str__(self):
138 return f'{libusb_error.get(self.value, "Unknown error")} [{self.value}]'
139
140 def getMessage(self):
141 """
142 Get user-friendly message representing the current error, and based on
143 the current locale.
144
145 Returns str, or None.
146 If libusb has not been loaded yet, returns None.
147 """
148 # pylint: disable=assignment-from-none
149 message = libusb_strerror(self.value)
150 # pylint: enable=assignment-from-none
151 if message is not None:
152 message = message.decode('utf-8')
153 return message
154
155 c_uchar = c_uint8
156 c_int_p = POINTER(c_int)
157 intptr_t = {
158 sizeof(x): x
159 for x in (c_int, c_long, c_longlong)
160 }[sizeof(c_void_p)]
161
162 LITTLE_ENDIAN = sys.byteorder == 'little'
163
164 class timeval(Structure):
165 _fields_ = [('tv_sec', c_long),
166 ('tv_usec', c_long)]
167 timeval_p = POINTER(timeval)
168
169 if platform.system() == 'Windows':
170 LIBUSB_CALL_FUNCTYPE = ctypes.WINFUNCTYPE
171 else:
172 LIBUSB_CALL_FUNCTYPE = CFUNCTYPE
173
174 def __getLibrary():
175 my_dir = os.path.dirname(__file__)
176 system = platform.system()
177 # If this is a binary wheel, try to use an integrated libusb first.
178 # To use the libusb from the Python installation or the OS, install
179 # from sdist:
180 # > pip install --no-binary :all: libusb1
181 if system == 'Windows':
182 dll_loader = ctypes.WinDLL
183 libusb_list = [
184 os.path.join(my_dir, 'libusb-1.0.dll'),
185 'libusb-1.0.dll',
186 ]
187 find_library = None
188 else:
189 dll_loader = CDLL
190 if system == 'Darwin':
191 libusb_list = [
192 os.path.join(my_dir, 'libusb-1.0.dylib'),
193 'libusb-1.0.dylib',
194 # macport standard path
195 '/opt/local/lib/libusb-1.0.dylib',
196 # fink standard path
197 '/sw/lib/libusb-1.0.dylib',
198 # homebrew standard path for symlink (Apple M1 Silicon)
199 '/opt/homebrew/opt/libusb/lib/libusb-1.0.dylib',
200 ]
201 find_library = None
202 else:
203 # .so.0 should be the optimal suffix
204 # .so is for BBB, especially if libusb-1.0.so was bundled in some
205 # uses of this module.
206 libusb_list = [
207 os.path.join(my_dir, 'libusb-1.0.so.0'),
208 os.path.join(my_dir, 'libusb-1.0.so'),
209 'libusb-1.0.so.0',
210 'libusb-1.0.so',
211 ]
212 find_library = (
213 # libusb.so.2 on FreeBSD: load('libusb.so') would work fine, but...
214 # libusb.so.2debian on Debian GNU/kFreeBSD: here it wouldn't work.
215 'usb'
216 if 'FreeBSD' in system else
217 'usb-1.0'
218 )
219 for filename in libusb_list:
220 try:
221 return dll_loader(filename, use_errno=True, use_last_error=True)
222 except OSError:
223 pass
224 if find_library is not None:
225 filename = ctypes.util.find_library(find_library)
226 if filename is not None:
227 return dll_loader(filename, use_errno=True, use_last_error=True)
228 raise OSError(
229 errno.ENOENT,
230 'cannot find a suitable libusb-1.0',
231 libusb_list,
232 )
233
234 __load_lock = Lock()
235 __loaded = False
236
237 def loadLibrary(libusb=None):
238 """
239 Load C library.
240
241 libusb (ctypes.CDLL, ctypes.WinDLL, None)
242 If None, the C library will be searched for in several platform-
243 dependent paths.
244 Otherwise, this is the C library to use as libusb. This is to allow
245 customising library lookup logic.
246
247 Only the first call actually loads the library.
248
249 Returns True if any of the following is true:
250 - the library was loaded by this call
251 - libusb argument is None
252 - libusb argument is the same object that was initially loaded.
253 """
254 global __loaded # pylint: disable=global-statement
255 if not __loaded: # avoid touching the lock if we are already loaded
256 with __load_lock:
257 if not __loaded: # we were not loaded, check again under lock
258 __loadLibrary(libusb)
259 __loaded = True
260 return True
261 return libusb is None or globals()['libusb'] is libusb
262
263 def __loadLibrary(libusb): # pylint: disable=too-many-locals,too-many-branches,too-many-statements
264 # WARNING: every local in this function will be stored in
265 # globals . Treat this namespace the same as the module's.
266 if libusb is None:
267 libusb = __getLibrary()
268
269 _libusb_transfer_fields = [
270 ('dev_handle', libusb_device_handle_p),
271 ('flags', c_uint8),
272 ('endpoint', c_uchar),
273 ('type', c_uchar),
274 ('timeout', c_uint),
275 ('status', c_int), # enum libusb_transfer_status
276 ('length', c_int),
277 ('actual_length', c_int),
278 ('callback', libusb_transfer_cb_fn_p),
279 ('user_data', c_void_p),
280 ('buffer', c_void_p),
281 ('num_iso_packets', c_int),
282 ('iso_packet_desc', libusb_iso_packet_descriptor)
283 ]
284 if 'FreeBSD' in platform.system() and getattr(
285 libusb, 'libusb_get_string_descriptor', None
286 ) is None:
287 # Old FreeBSD version has a slight ABI incompatibility.
288 # Work around it unless libusb_get_string_descriptor is available, as it
289 # is only available on fixed versions.
290 assert _libusb_transfer_fields[2][0] == 'endpoint'
291 _libusb_transfer_fields[2] = ('endpoint', c_uint32)
292 assert _libusb_transfer_fields[11][0] == 'num_iso_packets'
293 _libusb_transfer_fields.insert(11, ('os_priv', c_void_p))
294
295 # pylint: disable=protected-access
296 libusb_transfer._fields_ = _libusb_transfer_fields
297 # pylint: enable=protected-access
298
299 #int libusb_init_context(libusb_context **ctx,
300 # const struct libusb_init_option options[], int num_options);
301 try:
302 libusb_init_context = libusb.libusb_init_context
303 except AttributeError:
304 # Note: libusb_init is deprecated, only retrieve it when
305 # libusb_init_context is absent.
306 #int libusb_init(libusb_context **ctx);
307 libusb_init = libusb.libusb_init
308 libusb_init.argtypes = [libusb_context_p_p]
309 def libusb_init_context(ctx, _unused_options, num_options):
310 if num_options:
311 raise ValueError(
312 'libusb_init_context is not available in the current '
313 'libusb version, initialisation options are not available',
314 )
315 return libusb_init(ctx)
316 else:
317 libusb_init_context.argtypes = [
318 libusb_context_p_p,
319 POINTER(libusb_init_option),
320 c_int,
321 ]
322
323 #void libusb_exit(libusb_context *ctx);
324 libusb_exit = libusb.libusb_exit
325 libusb_exit.argtypes = [libusb_context_p]
326 libusb_exit.restype = None
327 #void libusb_set_debug(libusb_context *ctx, int level);
328 libusb_set_debug = libusb.libusb_set_debug
329 libusb_set_debug.argtypes = [libusb_context_p, c_int]
330 libusb_set_debug.restype = None
331 #void libusb_set_log_cb(libusb_context *ctx, libusb_log_cb cb, int mode);
332 try:
333 libusb_set_log_cb = libusb.libusb_set_log_cb
334 except AttributeError:
335 def libusb_set_log_cb(ctx, cb, mode):
336 pass
337 else:
338 libusb_set_log_cb.argtypes = [libusb_context_p, libusb_log_cb_p, c_int]
339 libusb_set_log_cb.restype = None
340 #const struct libusb_version * libusb_get_version(void);
341 try:
342 libusb_get_version = libusb.libusb_get_version
343 except AttributeError:
344 _dummy_version = libusb_version(0, 0, 0, 0, b'', b'')
345 _dummy_version_p = pointer(_dummy_version)
346 def libusb_get_version():
347 return _dummy_version_p
348 else:
349 libusb_get_version.argtypes = []
350 libusb_get_version.restype = POINTER(libusb_version)
351 #int libusb_has_capability(uint32_t capability);
352 try:
353 libusb_has_capability = libusb.libusb_has_capability
354 except AttributeError:
355 def libusb_has_capability(_):
356 return 0
357 else:
358 libusb_has_capability.argtypes = [c_uint32]
359 libusb_has_capability.restype = c_int
360 try:
361 # Note: Should be equivalent to libusb_error.get (except libusb_error.get
362 # one raises on unknown values).
363 #char *libusb_error_name(int errcode);
364 libusb_error_name = libusb.libusb_error_name
365 except AttributeError:
366 # pylint: disable=unused-argument
367 def libusb_error_name(errcode):
368 return None
369 # pylint: enable=unused-argument
370 else:
371 libusb_error_name.argtypes = [c_int]
372 libusb_error_name.restype = c_char_p
373 #int libusb_setlocale(const char *locale);
374 try:
375 libusb_setlocale = libusb.libusb_setlocale
376 except AttributeError:
377 def libusb_setlocale(_unused_locale):
378 pass
379 else:
380 libusb_setlocale.argtypes = [c_char_p]
381 libusb_setlocale.restype = int
382 #const char *libusb_strerror(int errcode);
383 try:
384 # pylint: disable=redefined-outer-name
385 libusb_strerror = libusb.libusb_strerror
386 # pylint: enable=redefined-outer-name
387 except AttributeError:
388 pass
389 else:
390 libusb_strerror.argtypes = [c_int]
391 libusb_strerror.restype = c_char_p
392 #ssize_t libusb_get_device_list(libusb_context *ctx,
393 # libusb_device ***list);
394 libusb_get_device_list = libusb.libusb_get_device_list
395 libusb_get_device_list.argtypes = [libusb_context_p, libusb_device_p_p_p]
396 libusb_get_device_list.restype = c_ssize_t
397 #void libusb_free_device_list(libusb_device **list, int unref_devices);
398 libusb_free_device_list = libusb.libusb_free_device_list
399 libusb_free_device_list.argtypes = [libusb_device_p_p, c_int]
400 libusb_free_device_list.restype = None
401 #libusb_device *libusb_ref_device(libusb_device *dev);
402 libusb_ref_device = libusb.libusb_ref_device
403 libusb_ref_device.argtypes = [libusb_device_p]
404 libusb_ref_device.restype = libusb_device_p
405 #void libusb_unref_device(libusb_device *dev);
406 libusb_unref_device = libusb.libusb_unref_device
407 libusb_unref_device.argtypes = [libusb_device_p]
408 libusb_unref_device.restype = None
409
410 #int libusb_get_configuration(libusb_device_handle *dev, int *config);
411 libusb_get_configuration = libusb.libusb_get_configuration
412 libusb_get_configuration.argtypes = [libusb_device_handle_p, c_int_p]
413 #int libusb_get_device_descriptor(libusb_device *dev,
414 # struct libusb_device_descriptor *desc);
415 libusb_get_device_descriptor = libusb.libusb_get_device_descriptor
416 libusb_get_device_descriptor.argtypes = [
417 libusb_device_p, libusb_device_descriptor_p]
418 #int libusb_get_active_config_descriptor(libusb_device *dev,
419 # struct libusb_config_descriptor **config);
420 libusb_get_active_config_descriptor = libusb.libusb_get_active_config_descriptor
421 libusb_get_active_config_descriptor.argtypes = [
422 libusb_device_p, libusb_config_descriptor_p_p]
423 #int libusb_get_config_descriptor(libusb_device *dev, uint8_t config_index,
424 # struct libusb_config_descriptor **config);
425 libusb_get_config_descriptor = libusb.libusb_get_config_descriptor
426 libusb_get_config_descriptor.argtypes = [
427 libusb_device_p, c_uint8, libusb_config_descriptor_p_p]
428 #int libusb_get_config_descriptor_by_value(libusb_device *dev,
429 # uint8_t bConfigurationValue, struct libusb_config_descriptor **config);
430 libusb_get_config_descriptor_by_value = \
431 libusb.libusb_get_config_descriptor_by_value
432 libusb_get_config_descriptor_by_value.argtypes = [
433 libusb_device_p, c_uint8, libusb_config_descriptor_p_p]
434 #void libusb_free_config_descriptor(struct libusb_config_descriptor *config);
435 libusb_free_config_descriptor = libusb.libusb_free_config_descriptor
436 libusb_free_config_descriptor.argtypes = [libusb_config_descriptor_p]
437 libusb_free_config_descriptor.restype = None
438 #uint8_t libusb_get_bus_number(libusb_device *dev);
439 libusb_get_bus_number = libusb.libusb_get_bus_number
440 libusb_get_bus_number.argtypes = [libusb_device_p]
441 libusb_get_bus_number.restype = c_uint8
442 try:
443 #uint8_t libusb_get_port_number(libusb_device *dev);
444 libusb_get_port_number = libusb.libusb_get_port_number
445 except AttributeError:
446 pass
447 else:
448 libusb_get_port_number.argtypes = [libusb_device_p]
449 libusb_get_port_number.restype = c_uint8
450 try:
451 #int libusb_get_port_numbers(libusb_device *dev,
452 # uint8_t* port_numbers, int port_numbers_len);
453 libusb_get_port_numbers = libusb.libusb_get_port_numbers
454 except AttributeError:
455 pass
456 else:
457 libusb_get_port_numbers.argtypes = [
458 libusb_device_p, POINTER(c_uint8), c_int]
459 libusb_get_port_numbers.restype = c_int
460 # Missing: libusb_get_port_path (deprecated since 1.0.16)
461 try:
462 #libusb_device *libusb_get_parent(libusb_device *dev);
463 libusb_get_parent = libusb.libusb_get_parent
464 except AttributeError:
465 pass
466 else:
467 libusb_get_parent.argtypes = [libusb_device_p]
468 libusb_get_parent.restype = libusb_device_p
469 #uint8_t libusb_get_device_address(libusb_device *dev);
470 libusb_get_device_address = libusb.libusb_get_device_address
471 libusb_get_device_address.argtypes = [libusb_device_p]
472 libusb_get_device_address.restype = c_uint8
473 try:
474 #int libusb_get_device_speed(libusb_device *dev);
475 libusb_get_device_speed = libusb.libusb_get_device_speed
476 except AttributeError:
477 # Place holder
478 def libusb_get_device_speed(_):
479 # pylint: disable=undefined-variable
480 return LIBUSB_SPEED_UNKNOWN
481 # pylint: enable=undefined-variable
482 else:
483 libusb_get_device_speed.argtypes = [libusb_device_p]
484 #int libusb_get_max_packet_size(libusb_device *dev, unsigned char endpoint);
485 libusb_get_max_packet_size = libusb.libusb_get_max_packet_size
486 libusb_get_max_packet_size.argtypes = [libusb_device_p, c_uchar]
487 #int libusb_get_max_iso_packet_size(libusb_device *dev, unsigned char endpoint);
488 try:
489 libusb_get_max_iso_packet_size = libusb.libusb_get_max_iso_packet_size
490 except AttributeError:
491 # FreeBSD's reimplementation of the API [used to ]lack[s] this function.
492 # It has been added in r234193, but is lacking in default 9.x install as
493 # of this change. Provide a fallback to error-out only if actually used.
494 # pylint: disable=unused-argument
495 def libusb_get_max_iso_packet_size(_, __):
496 raise NotImplementedError
497 # pylint: enable=unused-argument
498 else:
499 libusb_get_max_iso_packet_size.argtypes = [libusb_device_p, c_uchar]
500
501 #int libusb_wrap_sys_device(libusb_context *ctx, intptr_t sys_dev,
502 # libusb_device_handle **dev_handle);
503 try:
504 libusb_wrap_sys_device = libusb.libusb_wrap_sys_device
505 except AttributeError:
506 # pylint: enable=unused-argument
507 def libusb_wrap_sys_device(_, __, ___):
508 raise NotImplementedError
509 # pylint: disable=unused-argument
510 else:
511 libusb_wrap_sys_device.restype = c_int
512 libusb_wrap_sys_device.argtypes = [
513 libusb_context_p,
514 intptr_t,
515 libusb_device_handle_p_p,
516 ]
517
518 #int libusb_open(libusb_device *dev, libusb_device_handle **handle);
519 libusb_open = libusb.libusb_open
520 libusb_open.argtypes = [libusb_device_p, libusb_device_handle_p_p]
521 #void libusb_close(libusb_device_handle *dev_handle);
522 libusb_close = libusb.libusb_close
523 libusb_close.argtypes = [libusb_device_handle_p]
524 libusb_close.restype = None
525 #libusb_device *libusb_get_device(libusb_device_handle *dev_handle);
526 libusb_get_device = libusb.libusb_get_device
527 libusb_get_device.argtypes = [libusb_device_handle_p]
528 libusb_get_device.restype = libusb_device_p
529
530 #int libusb_set_configuration(libusb_device_handle *dev, int configuration);
531 libusb_set_configuration = libusb.libusb_set_configuration
532 libusb_set_configuration.argtypes = [libusb_device_handle_p, c_int]
533 #int libusb_claim_interface(libusb_device_handle *dev, int iface);
534 libusb_claim_interface = libusb.libusb_claim_interface
535 libusb_claim_interface.argtypes = [libusb_device_handle_p, c_int]
536 #int libusb_release_interface(libusb_device_handle *dev, int iface);
537 libusb_release_interface = libusb.libusb_release_interface
538 libusb_release_interface.argtypes = [libusb_device_handle_p, c_int]
539
540 #libusb_device_handle *libusb_open_device_with_vid_pid(libusb_context *ctx,
541 # uint16_t vendor_id, uint16_t product_id);
542 libusb_open_device_with_vid_pid = libusb.libusb_open_device_with_vid_pid
543 libusb_open_device_with_vid_pid.argtypes = [
544 libusb_context_p, c_uint16, c_uint16]
545 libusb_open_device_with_vid_pid.restype = libusb_device_handle_p
546
547 #int libusb_set_interface_alt_setting(libusb_device_handle *dev,
548 # int interface_number, int alternate_setting);
549 libusb_set_interface_alt_setting = libusb.libusb_set_interface_alt_setting
550 libusb_set_interface_alt_setting.argtypes = [
551 libusb_device_handle_p, c_int, c_int]
552 #int libusb_clear_halt(libusb_device_handle *dev, unsigned char endpoint);
553 libusb_clear_halt = libusb.libusb_clear_halt
554 libusb_clear_halt.argtypes = [libusb_device_handle_p, c_uchar]
555 #int libusb_reset_device(libusb_device_handle *dev);
556 libusb_reset_device = libusb.libusb_reset_device
557 libusb_reset_device.argtypes = [libusb_device_handle_p]
558
559 #int libusb_kernel_driver_active(libusb_device_handle *dev, int interface);
560 libusb_kernel_driver_active = libusb.libusb_kernel_driver_active
561 libusb_kernel_driver_active.argtypes = [libusb_device_handle_p, c_int]
562 #int libusb_detach_kernel_driver(libusb_device_handle *dev, int interface);
563 libusb_detach_kernel_driver = libusb.libusb_detach_kernel_driver
564 libusb_detach_kernel_driver.argtypes = [libusb_device_handle_p, c_int]
565 #int libusb_attach_kernel_driver(libusb_device_handle *dev, int interface);
566 libusb_attach_kernel_driver = libusb.libusb_attach_kernel_driver
567 libusb_attach_kernel_driver.argtypes = [libusb_device_handle_p, c_int]
568 try:
569 #int libusb_set_auto_detach_kernel_driver(
570 # libusb_device_handle *dev, int enable);
571 libusb_set_auto_detach_kernel_driver = \
572 libusb.libusb_set_auto_detach_kernel_driver
573 except AttributeError:
574 pass
575 else:
576 libusb_set_auto_detach_kernel_driver.argtypes = [
577 libusb_device_handle_p, c_int]
578 libusb_set_auto_detach_kernel_driver.restype = c_int
579
580 #struct libusb_transfer *libusb_alloc_transfer(int iso_packets);
581 libusb_alloc_transfer = libusb.libusb_alloc_transfer
582 libusb_alloc_transfer.argtypes = [c_int]
583 libusb_alloc_transfer.restype = libusb_transfer_p
584 #int libusb_submit_transfer(struct libusb_transfer *transfer);
585 libusb_submit_transfer = libusb.libusb_submit_transfer
586 libusb_submit_transfer.argtypes = [libusb_transfer_p]
587 #int libusb_cancel_transfer(struct libusb_transfer *transfer);
588 libusb_cancel_transfer = libusb.libusb_cancel_transfer
589 libusb_cancel_transfer.argtypes = [libusb_transfer_p]
590 #void libusb_free_transfer(struct libusb_transfer *transfer);
591 libusb_free_transfer = libusb.libusb_free_transfer
592 libusb_free_transfer.argtypes = [libusb_transfer_p]
593 libusb_free_transfer.restype = None
594
595 # sync I/O
596
597 #int libusb_control_transfer(libusb_device_handle *dev_handle,
598 # uint8_t request_type, uint8_t request, uint16_t value, uint16_t index,
599 # unsigned char *data, uint16_t length, unsigned int timeout);
600 libusb_control_transfer = libusb.libusb_control_transfer
601 libusb_control_transfer.argtypes = [libusb_device_handle_p, c_uint8, c_uint8,
602 c_uint16, c_uint16, c_void_p, c_uint16,
603 c_uint]
604
605 #int libusb_bulk_transfer(libusb_device_handle *dev_handle,
606 # unsigned char endpoint, unsigned char *data, int length,
607 # int *actual_length, unsigned int timeout);
608 libusb_bulk_transfer = libusb.libusb_bulk_transfer
609 libusb_bulk_transfer.argtypes = [libusb_device_handle_p, c_uchar, c_void_p,
610 c_int, c_int_p, c_uint]
611
612 #int libusb_interrupt_transfer(libusb_device_handle *dev_handle,
613 # unsigned char endpoint, unsigned char *data, int length,
614 # int *actual_length, unsigned int timeout);
615 libusb_interrupt_transfer = libusb.libusb_interrupt_transfer
616 libusb_interrupt_transfer.argtypes = [libusb_device_handle_p, c_uchar,
617 c_void_p, c_int, c_int_p, c_uint]
618
619 #int libusb_get_string_descriptor_ascii(libusb_device_handle *dev,
620 # uint8_t index, unsigned char *data, int length);
621 libusb_get_string_descriptor_ascii = libusb.libusb_get_string_descriptor_ascii
622 libusb_get_string_descriptor_ascii.argtypes = [libusb_device_handle_p,
623 c_uint8, c_void_p, c_int]
624
625 # polling and timeouts
626
627 #int libusb_try_lock_events(libusb_context *ctx);
628 libusb_try_lock_events = libusb.libusb_try_lock_events
629 libusb_try_lock_events.argtypes = [libusb_context_p]
630 #void libusb_lock_events(libusb_context *ctx);
631 libusb_lock_events = libusb.libusb_lock_events
632 libusb_lock_events.argtypes = [libusb_context_p]
633 #void libusb_unlock_events(libusb_context *ctx);
634 libusb_unlock_events = libusb.libusb_unlock_events
635 libusb_unlock_events.argtypes = [libusb_context_p]
636 libusb_unlock_events.restype = None
637 #int libusb_event_handling_ok(libusb_context *ctx);
638 libusb_event_handling_ok = libusb.libusb_event_handling_ok
639 libusb_event_handling_ok.argtypes = [libusb_context_p]
640 #int libusb_event_handler_active(libusb_context *ctx);
641 libusb_event_handler_active = libusb.libusb_event_handler_active
642 libusb_event_handler_active.argtypes = [libusb_context_p]
643 #void libusb_lock_event_waiters(libusb_context *ctx);
644 libusb_lock_event_waiters = libusb.libusb_lock_event_waiters
645 libusb_lock_event_waiters.argtypes = [libusb_context_p]
646 libusb_lock_event_waiters.restype = None
647 #void libusb_unlock_event_waiters(libusb_context *ctx);
648 libusb_unlock_event_waiters = libusb.libusb_unlock_event_waiters
649 libusb_unlock_event_waiters.argtypes = []
650 libusb_unlock_event_waiters.restype = None
651 #int libusb_wait_for_event(libusb_context *ctx, struct timeval *tv);
652 libusb_wait_for_event = libusb.libusb_wait_for_event
653 libusb_wait_for_event.argtypes = [libusb_context_p, timeval_p]
654
655 #int libusb_handle_events_timeout(libusb_context *ctx, struct timeval *tv);
656 libusb_handle_events_timeout = libusb.libusb_handle_events_timeout
657 libusb_handle_events_timeout.argtypes = [libusb_context_p, timeval_p]
658 #int libusb_handle_events_timeout_completed(libusb_context *ctx,
659 # struct timeval *tv, int *completed);
660 try:
661 libusb_handle_events_timeout_completed = libusb.\
662 libusb_handle_events_timeout_completed
663 except AttributeError:
664 # No safe replacement possible.
665 pass
666 else:
667 libusb_handle_events_timeout_completed.argtypes = [
668 libusb_context_p, timeval_p, c_int_p]
669 #int libusb_handle_events(libusb_context *ctx);
670 libusb_handle_events = libusb.libusb_handle_events
671 libusb_handle_events.argtypes = [libusb_context_p]
672 #int libusb_handle_events_completed(libusb_context *ctx, int *completed);
673 try:
674 libusb_handle_events_completed = libusb.libusb_handle_events_completed
675 except AttributeError:
676 # No safe replacement possible.
677 pass
678 else:
679 libusb_handle_events_completed.argtypes = [libusb_context_p, c_int_p]
680 #int libusb_handle_events_locked(libusb_context *ctx, struct timeval *tv);
681 libusb_handle_events_locked = libusb.libusb_handle_events_locked
682 libusb_handle_events_locked.argtypes = [libusb_context_p, timeval_p]
683 #void libusb_interrupt_event_handler(libusb_context *ctx);
684 try:
685 libusb_interrupt_event_handler = libusb.libusb_interrupt_event_handler
686 except AttributeError:
687 def libusb_interrupt_event_handler(_):
688 raise NotImplementedError
689 else:
690 libusb_interrupt_event_handler.argtypes = [libusb_context_p]
691 #int libusb_get_next_timeout(libusb_context *ctx, struct timeval *tv);
692 libusb_get_next_timeout = libusb.libusb_get_next_timeout
693 libusb_get_next_timeout.argtypes = [libusb_context_p, timeval_p]
694
695 #const struct libusb_pollfd **libusb_get_pollfds(libusb_context *ctx);
696 libusb_get_pollfds = libusb.libusb_get_pollfds
697 libusb_get_pollfds.argtypes = [libusb_context_p]
698 libusb_get_pollfds.restype = libusb_pollfd_p_p
699 #void libusb_set_pollfd_notifiers(libusb_context *ctx,
700 # libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
701 # void *user_data);
702 libusb_set_pollfd_notifiers = libusb.libusb_set_pollfd_notifiers
703 libusb_set_pollfd_notifiers.argtypes = [libusb_context_p,
704 libusb_pollfd_added_cb_p,
705 libusb_pollfd_removed_cb_p, py_object]
706 libusb_set_pollfd_notifiers.restype = None
707 try:
708 #void libusb_get_pollfds(const struct libusb_pollfd **);
709 libusb_free_pollfds = libusb.libusb_free_pollfds
710 libusb_free_pollfds.argtypes = [libusb_pollfd_p_p]
711 libusb_free_pollfds.restype = None
712 except AttributeError:
713 # Not a safe replacement in general, but the versions of libusb that lack
714 # libusb_free_pollfds() only provide that function on *nix, where
715 # Python's free() and libusb's free() are ~always the same anyways.
716 libusb_free_pollfds = CDLL(None).free
717
718 #int libusb_hotplug_register_callback(libusb_context *ctx,
719 # libusb_hotplug_event events, libusb_hotplug_flag flags,
720 # int vendor_id, int product_id, int dev_class,
721 # libusb_hotplug_callback_fn cb_fn, void *user_data,
722 # libusb_hotplug_callback_handle *handle);
723 try:
724 libusb_hotplug_register_callback = libusb.libusb_hotplug_register_callback
725 except AttributeError:
726 pass
727 else:
728 libusb_hotplug_register_callback.argtypes = [
729 libusb_context_p,
730 c_int, c_int,
731 c_int, c_int, c_int,
732 libusb_hotplug_callback_fn_p, c_void_p,
733 POINTER(libusb_hotplug_callback_handle),
734 ]
735 libusb_hotplug_register_callback.restype = c_int
736
737 #void libusb_hotplug_deregister_callback(libusb_context *ctx,
738 # libusb_hotplug_callback_handle handle);
739 try:
740 libusb_hotplug_deregister_callback = \
741 libusb.libusb_hotplug_deregister_callback
742 except AttributeError:
743 pass
744 else:
745 libusb_hotplug_deregister_callback.argtypes = [
746 libusb_context_p,
747 libusb_hotplug_callback_handle,
748 ]
749 libusb_hotplug_deregister_callback.restype = None
750
751 # Note: no support possible for libusb_set_option as it uses a variadic
752
753 globals().update(locals())
754
755 # libusb.h
756 def bswap16(x):
757 return ((x & 0xff) << 8) | (x >> 8)
758
759 if LITTLE_ENDIAN:
760 def libusb_cpu_to_le16(x):
761 return x
762 def libusb_le16_to_cpu(x):
763 return x
764 else:
765 libusb_cpu_to_le16 = bswap16
766 libusb_le16_to_cpu = bswap16
767
768 # standard USB stuff
769
770 # Device and/or Interface Class codes
771 libusb_class_code = Enum({
772 # In the context of a device descriptor,
773 # this bDeviceClass value indicates that each interface specifies its
774 # own class information and all interfaces operate independently.
775 'LIBUSB_CLASS_PER_INTERFACE': 0,
776 # Audio class
777 'LIBUSB_CLASS_AUDIO': 1,
778 # Communications class
779 'LIBUSB_CLASS_COMM': 2,
780 # Human Interface Device class
781 'LIBUSB_CLASS_HID': 3,
782 # Physical
783 'LIBUSB_CLASS_PHYSICAL': 5,
784 # Printer class
785 'LIBUSB_CLASS_PRINTER': 7,
786 # Picture transfer protocol class
787 'LIBUSB_CLASS_PTP': 6,
788 # Mass storage class
789 'LIBUSB_CLASS_MASS_STORAGE': 8,
790 # Hub class
791 'LIBUSB_CLASS_HUB': 9,
792 # Data class
793 'LIBUSB_CLASS_DATA': 10,
794 # Smart Card
795 'LIBUSB_CLASS_SMART_CARD': 0x0b,
796 # Content Security
797 'LIBUSB_CLASS_CONTENT_SECURITY': 0x0d,
798 # Video
799 'LIBUSB_CLASS_VIDEO': 0x0e,
800 # Personal Healthcare
801 'LIBUSB_CLASS_PERSONAL_HEALTHCARE': 0x0f,
802 # Diagnostic Device
803 'LIBUSB_CLASS_DIAGNOSTIC_DEVICE': 0xdc,
804 # Wireless class
805 'LIBUSB_CLASS_WIRELESS': 0xe0,
806 # Application class
807 'LIBUSB_CLASS_APPLICATION': 0xfe,
808 # Class is vendor-specific
809 'LIBUSB_CLASS_VENDOR_SPEC': 0xff
810 })
811 # pylint: disable=undefined-variable
812 LIBUSB_CLASS_IMAGE = LIBUSB_CLASS_PTP
813 # pylint: enable=undefined-variable
814
815 # Descriptor types as defined by the USB specification.
816 libusb_descriptor_type = Enum({
817 # Device descriptor. See libusb_device_descriptor.
818 'LIBUSB_DT_DEVICE': 0x01,
819 # Configuration descriptor. See libusb_config_descriptor.
820 'LIBUSB_DT_CONFIG': 0x02,
821 # String descriptor
822 'LIBUSB_DT_STRING': 0x03,
823 # Interface descriptor. See libusb_interface_descriptor.
824 'LIBUSB_DT_INTERFACE': 0x04,
825 # Endpoint descriptor. See libusb_endpoint_descriptor.
826 'LIBUSB_DT_ENDPOINT': 0x05,
827 # HID descriptor
828 'LIBUSB_DT_HID': 0x21,
829 # HID report descriptor
830 'LIBUSB_DT_REPORT': 0x22,
831 # Physical descriptor
832 'LIBUSB_DT_PHYSICAL': 0x23,
833 # Hub descriptor
834 'LIBUSB_DT_HUB': 0x29,
835 })
836
837 # Descriptor sizes per descriptor type
838 LIBUSB_DT_DEVICE_SIZE = 18
839 LIBUSB_DT_CONFIG_SIZE = 9
840 LIBUSB_DT_INTERFACE_SIZE = 9
841 LIBUSB_DT_ENDPOINT_SIZE = 7
842 LIBUSB_DT_ENDPOINT_AUDIO_SIZE = 9 # Audio extension
843 LIBUSB_DT_HUB_NONVAR_SIZE = 7
844 LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE = 6
845 LIBUSB_DT_BOS_SIZE = 5
846 LIBUSB_DT_DEVICE_CAPABILITY_SIZE = 3
847 LIBUSB_DT_INTERFACE_ASSOCIATION_SIZE = 8
848
849 # BOS descriptor sizes
850 LIBUSB_BT_USB_2_0_EXTENSION_SIZE = 7
851 LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE = 10
852 LIBUSB_BT_SSPLUS_USB_DEVICE_CAPABILITY_SIZE = 12
853 LIBUSB_BT_CONTAINER_ID_SIZE = 20
854 LIBUSB_BT_PLATFORM_DESCRIPTOR_MIN_SIZE = 20
855
856 LIBUSB_DT_BOS_MAX_SIZE = (
857 LIBUSB_DT_BOS_SIZE +
858 LIBUSB_BT_USB_2_0_EXTENSION_SIZE +
859 LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE +
860 LIBUSB_BT_CONTAINER_ID_SIZE
861 )
862
863 LIBUSB_ENDPOINT_ADDRESS_MASK = 0x0f # in bEndpointAddress
864 LIBUSB_ENDPOINT_DIR_MASK = 0x80
865 # BBB
866 USB_ENDPOINT_ADDRESS_MASK = LIBUSB_ENDPOINT_ADDRESS_MASK
867 USB_ENDPOINT_DIR_MASK = LIBUSB_ENDPOINT_DIR_MASK
868
869 # Endpoint direction. Values for bit 7 of the endpoint address scheme.
870 libusb_endpoint_direction = Enum({
871 # In: device-to-host
872 'LIBUSB_ENDPOINT_IN': 0x80,
873 # Out: host-to-device
874 'LIBUSB_ENDPOINT_OUT': 0x00
875 })
876
877 LIBUSB_TRANSFER_TYPE_MASK = 0x03 # in bmAttributes
878
879 # Endpoint transfer type. Values for bits 0:1 of the endpoint attributes field.
880 libusb_transfer_type = Enum({
881 # Control endpoint
882 'LIBUSB_TRANSFER_TYPE_CONTROL': 0,
883 # Isochronous endpoint
884 'LIBUSB_TRANSFER_TYPE_ISOCHRONOUS': 1,
885 # Bulk endpoint
886 'LIBUSB_TRANSFER_TYPE_BULK': 2,
887 # Interrupt endpoint
888 'LIBUSB_TRANSFER_TYPE_INTERRUPT': 3,
889 })
890
891 # Standard requests, as defined in table 9-3 of the USB2 specifications
892 libusb_standard_request = Enum({
893 # Request status of the specific recipient
894 'LIBUSB_REQUEST_GET_STATUS': 0x00,
895 # Clear or disable a specific feature
896 'LIBUSB_REQUEST_CLEAR_FEATURE': 0x01,
897 # 0x02 is reserved
898 # Set or enable a specific feature
899 'LIBUSB_REQUEST_SET_FEATURE': 0x03,
900 # 0x04 is reserved
901 # Set device address for all future accesses
902 'LIBUSB_REQUEST_SET_ADDRESS': 0x05,
903 # Get the specified descriptor
904 'LIBUSB_REQUEST_GET_DESCRIPTOR': 0x06,
905 # Used to update existing descriptors or add new descriptors
906 'LIBUSB_REQUEST_SET_DESCRIPTOR': 0x07,
907 # Get the current device configuration value
908 'LIBUSB_REQUEST_GET_CONFIGURATION': 0x08,
909 # Set device configuration
910 'LIBUSB_REQUEST_SET_CONFIGURATION': 0x09,
911 # Return the selected alternate setting for the specified interface
912 'LIBUSB_REQUEST_GET_INTERFACE': 0x0a,
913 # Select an alternate interface for the specified interface
914 'LIBUSB_REQUEST_SET_INTERFACE': 0x0b,
915 # Set then report an endpoint's synchronization frame
916 'LIBUSB_REQUEST_SYNCH_FRAME': 0x0c,
917 })
918
919 # Request type bits of the bmRequestType field in control transfers.
920 libusb_request_type = Enum({
921 # Standard
922 'LIBUSB_REQUEST_TYPE_STANDARD': (0x00 << 5),
923 # Class
924 'LIBUSB_REQUEST_TYPE_CLASS': (0x01 << 5),
925 # Vendor
926 'LIBUSB_REQUEST_TYPE_VENDOR': (0x02 << 5),
927 # Reserved
928 'LIBUSB_REQUEST_TYPE_RESERVED': (0x03 << 5),
929 })
930
931 # BBB
932 # pylint: disable=undefined-variable
933 LIBUSB_TYPE_STANDARD = LIBUSB_REQUEST_TYPE_STANDARD
934 LIBUSB_TYPE_CLASS = LIBUSB_REQUEST_TYPE_CLASS
935 LIBUSB_TYPE_VENDOR = LIBUSB_REQUEST_TYPE_VENDOR
936 LIBUSB_TYPE_RESERVED = LIBUSB_REQUEST_TYPE_RESERVED
937 # pylint: enable=undefined-variable
938
939 # Recipient bits of the bmRequestType field in control transfers. Values 4
940 # through 31 are reserved.
941 libusb_request_recipient = Enum({
942 # Device
943 'LIBUSB_RECIPIENT_DEVICE': 0x00,
944 # Interface
945 'LIBUSB_RECIPIENT_INTERFACE': 0x01,
946 # Endpoint
947 'LIBUSB_RECIPIENT_ENDPOINT': 0x02,
948 # Other
949 'LIBUSB_RECIPIENT_OTHER': 0x03,
950 })
951
952 LIBUSB_ISO_SYNC_TYPE_MASK = 0x0c
953
954 # Synchronization type for isochronous endpoints. Values for bits 2:3 of the
955 # bmAttributes field in libusb_endpoint_descriptor.
956 libusb_iso_sync_type = Enum({
957 # No synchronization
958 'LIBUSB_ISO_SYNC_TYPE_NONE': 0,
959 # Asynchronous
960 'LIBUSB_ISO_SYNC_TYPE_ASYNC': 1,
961 # Adaptive
962 'LIBUSB_ISO_SYNC_TYPE_ADAPTIVE': 2,
963 # Synchronous
964 'LIBUSB_ISO_SYNC_TYPE_SYNC': 3,
965 })
966
967 LIBUSB_ISO_USAGE_TYPE_MASK = 0x30
968
969 # Usage type for isochronous endpoints. Values for bits 4:5 of the
970 # bmAttributes field in libusb_endpoint_descriptor.
971 libusb_iso_usage_type = Enum({
972 # Data endpoint
973 'LIBUSB_ISO_USAGE_TYPE_DATA': 0,
974 # Feedback endpoint
975 'LIBUSB_ISO_USAGE_TYPE_FEEDBACK': 1,
976 # Implicit feedback Data endpoint
977 'LIBUSB_ISO_USAGE_TYPE_IMPLICIT': 2,
978 })
979
980 # A structure representing the standard USB device descriptor. This
981 # descriptor is documented in section 9.6.1 of the USB 2.0 specification.
982 # All multiple-byte fields are represented in host-endian format.
983 class libusb_device_descriptor(Structure):
984 _fields_ = [
985 # Size of this descriptor (in bytes)
986 ('bLength', c_uint8),
987 # Descriptor type. Will have value LIBUSB_DT_DEVICE in this
988 # context.
989 ('bDescriptorType', c_uint8),
990 # USB specification release number in binary-coded decimal. A
991 # value of 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1,
992 # etc.
993 ('bcdUSB', c_uint16),
994 # USB-IF class code for the device. See libusb_class_code.
995 ('bDeviceClass', c_uint8),
996 # USB-IF subclass code for the device, qualified by the
997 # bDeviceClass value
998 ('bDeviceSubClass', c_uint8),
999 # USB-IF protocol code for the device, qualified by the
1000 # bDeviceClass and bDeviceSubClass values
1001 ('bDeviceProtocol', c_uint8),
1002 # Maximum packet size for endpoint 0
1003 ('bMaxPacketSize0', c_uint8),
1004 # USB-IF vendor ID
1005 ('idVendor', c_uint16),
1006 # USB-IF product ID
1007 ('idProduct', c_uint16),
1008 # Device release number in binary-coded decimal
1009 ('bcdDevice', c_uint16),
1010 # Index of string descriptor describing manufacturer
1011 ('iManufacturer', c_uint8),
1012 # Index of string descriptor describing product
1013 ('iProduct', c_uint8),
1014 # Index of string descriptor containing device serial number
1015 ('iSerialNumber', c_uint8),
1016 # Number of possible configurations
1017 ('bNumConfigurations', c_uint8)]
1018 libusb_device_descriptor_p = POINTER(libusb_device_descriptor)
1019
1020 class libusb_endpoint_descriptor(Structure):
1021 _fields_ = [
1022 ('bLength', c_uint8),
1023 ('bDescriptorType', c_uint8),
1024 ('bEndpointAddress', c_uint8),
1025 ('bmAttributes', c_uint8),
1026 ('wMaxPacketSize', c_uint16),
1027 ('bInterval', c_uint8),
1028 ('bRefresh', c_uint8),
1029 ('bSynchAddress', c_uint8),
1030 ('extra', c_void_p),
1031 ('extra_length', c_int)]
1032 libusb_endpoint_descriptor_p = POINTER(libusb_endpoint_descriptor)
1033
1034 class libusb_interface_descriptor(Structure):
1035 _fields_ = [
1036 ('bLength', c_uint8),
1037 ('bDescriptorType', c_uint8),
1038 ('bInterfaceNumber', c_uint8),
1039 ('bAlternateSetting', c_uint8),
1040 ('bNumEndpoints', c_uint8),
1041 ('bInterfaceClass', c_uint8),
1042 ('bInterfaceSubClass', c_uint8),
1043 ('bInterfaceProtocol', c_uint8),
1044 ('iInterface', c_uint8),
1045 ('endpoint', libusb_endpoint_descriptor_p),
1046 ('extra', c_void_p),
1047 ('extra_length', c_int)]
1048 libusb_interface_descriptor_p = POINTER(libusb_interface_descriptor)
1049
1050 class libusb_interface(Structure):
1051 _fields_ = [('altsetting', libusb_interface_descriptor_p),
1052 ('num_altsetting', c_int)]
1053 libusb_interface_p = POINTER(libusb_interface)
1054
1055 class libusb_config_descriptor(Structure):
1056 _fields_ = [
1057 ('bLength', c_uint8),
1058 ('bDescriptorType', c_uint8),
1059 ('wTotalLength', c_uint16),
1060 ('bNumInterfaces', c_uint8),
1061 ('bConfigurationValue', c_uint8),
1062 ('iConfiguration', c_uint8),
1063 ('bmAttributes', c_uint8),
1064 ('MaxPower', c_uint8),
1065 ('interface', libusb_interface_p),
1066 ('extra', c_void_p),
1067 ('extra_length', c_int)]
1068 libusb_config_descriptor_p = POINTER(libusb_config_descriptor)
1069 libusb_config_descriptor_p_p = POINTER(libusb_config_descriptor_p)
1070
1071 class libusb_control_setup(Structure):
1072 _pack_ = 1
1073 _fields_ = [
1074 ('bmRequestType', c_uint8),
1075 ('bRequest', c_uint8),
1076 ('wValue', c_uint16),
1077 ('wIndex', c_uint16),
1078 ('wLength', c_uint16)]
1079 libusb_control_setup_p = POINTER(libusb_control_setup)
1080
1081 LIBUSB_CONTROL_SETUP_SIZE = sizeof(libusb_control_setup)
1082
1083 # Structure representing a libusb session. The concept of individual libusb
1084 # sessions allows for your program to use two libraries (or dynamically
1085 # load two modules) which both independently use libusb. This will prevent
1086 # interference between the individual libusb users - for example
1087 # libusb_set_debug() will not affect the other user of the library, and
1088 # libusb_exit() will not destroy resources that the other user is still
1089 # using.
1090 #
1091 # Sessions are created by libusb_init() and destroyed through libusb_exit().
1092 # If your application is guaranteed to only ever include a single libusb
1093 # user (i.e. you), you do not have to worry about contexts: pass NULL in
1094 # every function call where a context is required. The default context
1095 # will be used.
1096 #
1097 # For more information, see \ref contexts.
1098 #class libusb_context(Structure):
1099 # pass
1100 #libusb_context_p = POINTER(libusb_context)
1101 libusb_context_p = c_void_p # Any pointer is fine
1102 libusb_context_p_p = POINTER(libusb_context_p)
1103
1104 # Structure representing a USB device detected on the system. This is an
1105 # opaque type for which you are only ever provided with a pointer, usually
1106 # originating from libusb_get_device_list().
1107 #
1108 # Certain operations can be performed on a device, but in order to do any
1109 # I/O you will have to first obtain a device handle using libusb_open().
1110 #
1111 # Devices are reference counted with libusb_device_ref() and
1112 # libusb_device_unref(), and are freed when the reference count reaches 0.
1113 # New devices presented by libusb_get_device_list() have a reference count of
1114 # 1, and libusb_free_device_list() can optionally decrease the reference count
1115 # on all devices in the list. libusb_open() adds another reference which is
1116 # later destroyed by libusb_close().
1117 #class libusb_device(Structure):
1118 # pass
1119 #libusb_device_p = POINTER(libusb_device)
1120 libusb_device_p = c_void_p # Any pointer is fine
1121 libusb_device_p_p = POINTER(libusb_device_p)
1122 libusb_device_p_p_p = POINTER(libusb_device_p_p)
1123
1124 # Structure representing a handle on a USB device. This is an opaque type for
1125 # which you are only ever provided with a pointer, usually originating from
1126 # libusb_open().
1127 #
1128 # A device handle is used to perform I/O and other operations. When finished
1129 # with a device handle, you should call libusb_close().
1130 class libusb_device_handle(Structure):
1131 pass
1132 libusb_device_handle_p = POINTER(libusb_device_handle)
1133 libusb_device_handle_p_p = POINTER(libusb_device_handle_p)
1134
1135 class libusb_version(Structure):
1136 _fields_ = [
1137 ('major', c_uint16),
1138 ('minor', c_uint16),
1139 ('micro', c_uint16),
1140 ('nano', c_uint16),
1141 ('rc', c_char_p),
1142 ('describe', c_char_p),
1143 ]
1144
1145 #typedef void (*libusb_log_cb)(libusb_context *ctx,
1146 # enum libusb_log_level level, const char *str);
1147 libusb_log_cb_p = LIBUSB_CALL_FUNCTYPE(None, libusb_context_p, c_int, c_char_p)
1148
1149 class libusb_init_option_value(Union):
1150 _fields_ = [
1151 ('ival', c_int),
1152 ('log_cbval', libusb_log_cb_p),
1153 ]
1154
1155 class libusb_init_option(Structure):
1156 _fields_ = [
1157 ('option', c_int),
1158 ('value', libusb_init_option_value),
1159 ]
1160
1161 libusb_speed = Enum({
1162 # The OS doesn't report or know the device speed.
1163 'LIBUSB_SPEED_UNKNOWN': 0,
1164 # The device is operating at low speed (1.5MBit/s).
1165 'LIBUSB_SPEED_LOW': 1,
1166 # The device is operating at full speed (12MBit/s).
1167 'LIBUSB_SPEED_FULL': 2,
1168 # The device is operating at high speed (480MBit/s).
1169 'LIBUSB_SPEED_HIGH': 3,
1170 # The device is operating at super speed (5000MBit/s).
1171 'LIBUSB_SPEED_SUPER': 4,
1172 # The device is operating at super speed plus (10000MBit/s).
1173 'LIBUSB_SPEED_SUPER_PLUS': 5,
1174 # The device is operating at super speed plus x2 (20000MBit/s).
1175 'LIBUSB_SPEED_SUPER_PLUS_X2': 6,
1176 })
1177
1178 libusb_supported_speed = Enum({
1179 # Low speed operation supported (1.5MBit/s).
1180 'LIBUSB_LOW_SPEED_OPERATION': 1,
1181 # Full speed operation supported (12MBit/s).
1182 'LIBUSB_FULL_SPEED_OPERATION': 2,
1183 # High speed operation supported (480MBit/s).
1184 'LIBUSB_HIGH_SPEED_OPERATION': 4,
1185 # Superspeed operation supported (5000MBit/s).
1186 'LIBUSB_5GBPS_OPERATION': 8,
1187 })
1188
1189 # Error codes. Most libusb functions return 0 on success or one of these
1190 # codes on failure.
1191 libusb_error = Enum({
1192 # Success (no error)
1193 'LIBUSB_SUCCESS': 0,
1194 # Input/output error
1195 'LIBUSB_ERROR_IO': -1,
1196 # Invalid parameter
1197 'LIBUSB_ERROR_INVALID_PARAM': -2,
1198 # Access denied (insufficient permissions)
1199 'LIBUSB_ERROR_ACCESS': -3,
1200 # No such device (it may have been disconnected)
1201 'LIBUSB_ERROR_NO_DEVICE': -4,
1202 # Entity not found
1203 'LIBUSB_ERROR_NOT_FOUND': -5,
1204 # Resource busy
1205 'LIBUSB_ERROR_BUSY': -6,
1206 # Operation timed out
1207 'LIBUSB_ERROR_TIMEOUT': -7,
1208 # Overflow
1209 'LIBUSB_ERROR_OVERFLOW': -8,
1210 # Pipe error
1211 'LIBUSB_ERROR_PIPE': -9,
1212 # System call interrupted (perhaps due to signal)
1213 'LIBUSB_ERROR_INTERRUPTED': -10,
1214 # Insufficient memory
1215 'LIBUSB_ERROR_NO_MEM': -11,
1216 # Operation not supported or unimplemented on this platform
1217 'LIBUSB_ERROR_NOT_SUPPORTED': -12,
1218 # Other error
1219 'LIBUSB_ERROR_OTHER': -99,
1220 })
1221
1222 # Transfer status codes
1223 libusb_transfer_status = Enum({
1224 # Transfer completed without error. Note that this does not indicate
1225 # that the entire amount of requested data was transferred.
1226 'LIBUSB_TRANSFER_COMPLETED': 0,
1227 # Transfer failed
1228 'LIBUSB_TRANSFER_ERROR': 1,
1229 # Transfer timed out
1230 'LIBUSB_TRANSFER_TIMED_OUT': 2,
1231 # Transfer was cancelled
1232 'LIBUSB_TRANSFER_CANCELLED': 3,
1233 # For bulk/interrupt endpoints: halt condition detected (endpoint
1234 # stalled). For control endpoints: control request not supported.
1235 'LIBUSB_TRANSFER_STALL': 4,
1236 # Device was disconnected
1237 'LIBUSB_TRANSFER_NO_DEVICE': 5,
1238 # Device sent more data than requested
1239 'LIBUSB_TRANSFER_OVERFLOW': 6,
1240 })
1241
1242 # libusb_transfer.flags values
1243 libusb_transfer_flags = Enum({
1244 # Report short frames as errors
1245 'LIBUSB_TRANSFER_SHORT_NOT_OK': 1 << 0,
1246 # Automatically free() transfer buffer during libusb_free_transfer()
1247 'LIBUSB_TRANSFER_FREE_BUFFER': 1 << 1,
1248 # Automatically call libusb_free_transfer() after callback returns.
1249 # If this flag is set, it is illegal to call libusb_free_transfer()
1250 # from your transfer callback, as this will result in a double-free
1251 # when this flag is acted upon.
1252 'LIBUSB_TRANSFER_FREE_TRANSFER': 1 << 2,
1253 # Terminate transfers that are a multiple of the endpoint's
1254 # wMaxPacketSize with an extra zero length packet.
1255 'LIBUSB_TRANSFER_ADD_ZERO_PACKET': 1 << 3,
1256 })
1257
1258 # Isochronous packet descriptor.
1259 class libusb_iso_packet_descriptor(Structure):
1260 _fields_ = [('length', c_uint),
1261 ('actual_length', c_uint),
1262 ('status', c_int)] # enum libusb_transfer_status
1263 libusb_iso_packet_descriptor_p = POINTER(libusb_iso_packet_descriptor)
1264
1265 class libusb_transfer(Structure):
1266 pass
1267 libusb_transfer_p = POINTER(libusb_transfer)
1268
1269 libusb_transfer_cb_fn_p = LIBUSB_CALL_FUNCTYPE(None, libusb_transfer_p)
1270
1271 libusb_capability = Enum({
1272 # The libusb_has_capability() API is available.
1273 'LIBUSB_CAP_HAS_CAPABILITY': 0x0000,
1274 # Hotplug support is available.
1275 'LIBUSB_CAP_HAS_HOTPLUG': 0x0001,
1276 # The library can access HID devices without requiring user intervention.
1277 'LIBUSB_CAP_HAS_HID_ACCESS': 0x0100,
1278 # The library supports detaching of the default USB driver.
1279 'LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER': 0x0101,
1280 })
1281
1282 libusb_log_level = Enum({
1283 'LIBUSB_LOG_LEVEL_NONE': 0,
1284 'LIBUSB_LOG_LEVEL_ERROR': 1,
1285 'LIBUSB_LOG_LEVEL_WARNING': 2,
1286 'LIBUSB_LOG_LEVEL_INFO': 3,
1287 'LIBUSB_LOG_LEVEL_DEBUG': 4,
1288 })
1289
1290 libusb_log = Enum({
1291 'LIBUSB_LOG_CB_GLOBAL': 1 << 0,
1292 'LIBUSB_LOG_CB_CONTEXT': 1 << 1,
1293 })
1294
1295 libusb_option = Enum({
1296 'LIBUSB_OPTION_LOG_LEVEL': 0,
1297 'LIBUSB_OPTION_USE_USBDK': 1,
1298 'LIBUSB_OPTION_NO_DEVICE_DISCOVERY': 2,
1299 'LIBUSB_OPTION_LOG_CB': 3,
1300 'LIBUSB_OPTION_MAX': 4,
1301 })
1302
1303 # Get the data section of a control transfer. This convenience function is here
1304 # to remind you that the data does not start until 8 bytes into the actual
1305 # buffer, as the setup packet comes first.
1306 #
1307 # Calling this function only makes sense from a transfer callback function,
1308 # or situations where you have already allocated a suitably sized buffer at
1309 # transfer->buffer.
1310 #
1311 # \param transfer a transfer
1312 # \returns pointer to the first byte of the data section
1313
1314 def libusb_control_transfer_get_data(transfer_p):
1315 transfer = transfer_p.contents
1316 return buffer_at(transfer.buffer, transfer.length)[
1317 LIBUSB_CONTROL_SETUP_SIZE:]
1318
1319 def libusb_control_transfer_get_setup(transfer_p):
1320 return cast(transfer_p.contents.buffer, libusb_control_setup_p)
1321
1322 def libusb_fill_control_setup(
1323 setup_p, bmRequestType, bRequest, wValue, wIndex, wLength):
1324 setup = cast(setup_p, libusb_control_setup_p).contents
1325 setup.bmRequestType = bmRequestType
1326 setup.bRequest = bRequest
1327 setup.wValue = libusb_cpu_to_le16(wValue)
1328 setup.wIndex = libusb_cpu_to_le16(wIndex)
1329 setup.wLength = libusb_cpu_to_le16(wLength)
1330
1331 # pylint: disable=redefined-builtin
1332 def libusb_fill_control_transfer(
1333 transfer_p, dev_handle, buffer, callback, user_data, timeout):
1334 transfer = transfer_p.contents
1335 transfer.dev_handle = dev_handle
1336 transfer.endpoint = 0
1337 # pylint: disable=undefined-variable
1338 transfer.type = LIBUSB_TRANSFER_TYPE_CONTROL
1339 # pylint: enable=undefined-variable
1340 transfer.timeout = timeout
1341 transfer.buffer = cast(buffer, c_void_p)
1342 if buffer is not None:
1343 setup = cast(buffer, libusb_control_setup_p).contents
1344 # pylint: disable=undefined-variable
1345 transfer.length = LIBUSB_CONTROL_SETUP_SIZE + \
1346 libusb_le16_to_cpu(setup.wLength)
1347 # pylint: enable=undefined-variable
1348 transfer.user_data = user_data
1349 transfer.callback = callback
1350 # pylint: enable=redefined-builtin
1351
1352 # pylint: disable=redefined-builtin
1353 def libusb_fill_bulk_transfer(
1354 transfer_p, dev_handle, endpoint, buffer, length,
1355 callback, user_data, timeout):
1356 transfer = transfer_p.contents
1357 transfer.dev_handle = dev_handle
1358 transfer.endpoint = endpoint
1359 # pylint: disable=undefined-variable
1360 transfer.type = LIBUSB_TRANSFER_TYPE_BULK
1361 # pylint: enable=undefined-variable
1362 transfer.timeout = timeout
1363 transfer.buffer = cast(buffer, c_void_p)
1364 transfer.length = length
1365 transfer.user_data = user_data
1366 transfer.callback = callback
1367 # pylint: enable=redefined-builtin
1368
1369 # pylint: disable=redefined-builtin
1370 def libusb_fill_interrupt_transfer(
1371 transfer_p, dev_handle, endpoint, buffer,
1372 length, callback, user_data, timeout):
1373 transfer = transfer_p.contents
1374 transfer.dev_handle = dev_handle
1375 transfer.endpoint = endpoint
1376 # pylint: disable=undefined-variable
1377 transfer.type = LIBUSB_TRANSFER_TYPE_INTERRUPT
1378 # pylint: enable=undefined-variable
1379 transfer.timeout = timeout
1380 transfer.buffer = cast(buffer, c_void_p)
1381 transfer.length = length
1382 transfer.user_data = user_data
1383 transfer.callback = callback
1384 # pylint: enable=redefined-builtin
1385
1386 # pylint: disable=redefined-builtin
1387 def libusb_fill_iso_transfer(
1388 transfer_p, dev_handle, endpoint, buffer, length,
1389 num_iso_packets, callback, user_data, timeout):
1390 transfer = transfer_p.contents
1391 transfer.dev_handle = dev_handle
1392 transfer.endpoint = endpoint
1393 # pylint: disable=undefined-variable
1394 transfer.type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
1395 # pylint: enable=undefined-variable
1396 transfer.timeout = timeout
1397 transfer.buffer = cast(buffer, c_void_p)
1398 transfer.length = length
1399 transfer.num_iso_packets = num_iso_packets
1400 transfer.user_data = user_data
1401 transfer.callback = callback
1402 # pylint: enable=redefined-builtin
1403
1404 def _get_iso_packet_list(transfer):
1405 list_type = libusb_iso_packet_descriptor * transfer.num_iso_packets
1406 return list_type.from_address(addressof(transfer.iso_packet_desc))
1407
1408 def get_iso_packet_list(transfer_p):
1409 """
1410 Python-specific helper extracting a list of iso packet descriptors,
1411 because it's not as straight-forward as in C.
1412 """
1413 return _get_iso_packet_list(transfer_p.contents)
1414
1415 def _get_iso_packet_buffer(transfer, offset, length):
1416 return buffer_at(transfer.buffer + offset, length)
1417
1418 def get_iso_packet_buffer_list(transfer_p):
1419 """
1420 Python-specific helper extracting a list of iso packet buffers.
1421 """
1422 transfer = transfer_p.contents
1423 offset = 0
1424 result = []
1425 append = result.append
1426 for iso_transfer in _get_iso_packet_list(transfer):
1427 length = iso_transfer.length
1428 append(_get_iso_packet_buffer(transfer, offset, length))
1429 offset += length
1430 return result
1431
1432 def get_extra(descriptor):
1433 """
1434 Python-specific helper to access "extra" field of descriptors,
1435 because it's not as straight-forward as in C.
1436 Returns a list, where each entry is an individual extra descriptor.
1437 """
1438 result = []
1439 extra_length = descriptor.extra_length
1440 if extra_length:
1441 extra = buffer_at(descriptor.extra, extra_length)
1442 append = result.append
1443 while extra:
1444 length = extra[0]
1445 if not 0 < length <= len(extra):
1446 raise ValueError(
1447 f'Extra descriptor {len(result)} is incomplete/invalid',
1448 )
1449 append(extra[:length])
1450 extra = extra[length:]
1451 return result
1452
1453 def libusb_set_iso_packet_lengths(transfer_p, length):
1454 transfer = transfer_p.contents
1455 for iso_packet_desc in _get_iso_packet_list(transfer):
1456 iso_packet_desc.length = length
1457
1458 def libusb_get_iso_packet_buffer(transfer_p, packet):
1459 transfer = transfer_p.contents
1460 offset = 0
1461 if packet >= transfer.num_iso_packets:
1462 return None
1463 iso_packet_desc_list = _get_iso_packet_list(transfer)
1464 for i in range(packet):
1465 offset += iso_packet_desc_list[i].length
1466 return _get_iso_packet_buffer(
1467 transfer, offset, iso_packet_desc_list[packet].length)
1468
1469 def libusb_get_iso_packet_buffer_simple(transfer_p, packet):
1470 transfer = transfer_p.contents
1471 if packet >= transfer.num_iso_packets:
1472 return None
1473 iso_length = transfer.iso_packet_desc.length
1474 return _get_iso_packet_buffer(transfer, iso_length * packet, iso_length)
1475
1476 # sync I/O
1477
1478 # pylint: disable=undefined-variable
1479 def libusb_get_descriptor(dev, desc_type, desc_index, data, length):
1480 return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1481 LIBUSB_REQUEST_GET_DESCRIPTOR,
1482 (desc_type << 8) | desc_index, 0, data,
1483 length, 1000)
1484 # pylint: enable=undefined-variable
1485
1486 # pylint: disable=undefined-variable
1487 def libusb_get_string_descriptor(dev, desc_index, langid, data, length):
1488 return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1489 LIBUSB_REQUEST_GET_DESCRIPTOR,
1490 (LIBUSB_DT_STRING << 8) | desc_index,
1491 langid, data, length, 1000)
1492 # pylint: enable=undefined-variable
1493
1494 # polling and timeouts
1495
1496 class libusb_pollfd(Structure):
1497 _fields_ = [
1498 ('fd', c_int),
1499 ('events', c_short),
1500 ]
1501 libusb_pollfd_p = POINTER(libusb_pollfd)
1502 libusb_pollfd_p_p = POINTER(libusb_pollfd_p)
1503
1504 libusb_pollfd_added_cb_p = LIBUSB_CALL_FUNCTYPE(None, c_int, c_short, py_object)
1505 libusb_pollfd_removed_cb_p = LIBUSB_CALL_FUNCTYPE(None, c_int, py_object)
1506
1507 #typedef int libusb_hotplug_callback_handle;
1508 libusb_hotplug_callback_handle = c_int
1509
1510 libusb_hotplug_flag = Enum({
1511 'LIBUSB_HOTPLUG_ENUMERATE': 1,
1512 })
1513
1514 libusb_hotplug_event = Enum({
1515 'LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED': 0x01,
1516 'LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT': 0x02,
1517 })
1518
1519 LIBUSB_HOTPLUG_NO_FLAGS = 0
1520 LIBUSB_HOTPLUG_MATCH_ANY = -1
1521
1522 #typedef int (*libusb_hotplug_callback_fn)(libusb_context *ctx,
1523 # libusb_device *device, libusb_hotplug_event event, void *user_data);
1524 libusb_hotplug_callback_fn_p = LIBUSB_CALL_FUNCTYPE(
1525 c_int, libusb_context_p, libusb_device_p, c_int, c_void_p)
1526
1527 # /libusb.h