Debian Codegraph @

usb1/__init__.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-many-locals, too-many-arguments
18 # pylint: disable=too-many-public-methods, too-many-instance-attributes
19 # pylint: disable=missing-docstring, too-many-lines
20 """
21 Pythonic wrapper for libusb-1.0.
22
23 The first thing you must do is to get an "USB context". To do so, create an
24 USBContext instance.
25 Then, you can use it to browse available USB devices and open the one you want
26 to talk to.
27 At this point, you should have a USBDeviceHandle instance (as returned by
28 USBContext or USBDevice instances), and you can start exchanging with the
29 device.
30
31 Features:
32 - Basic device settings (configuration & interface selection, ...)
33 - String descriptor lookups (ASCII & unicode), and list supported language
34 codes
35 - Synchronous I/O (control, bulk, interrupt)
36 - Asynchronous I/O (control, bulk, interrupt, isochronous)
37 Note: Isochronous support is not well tested.
38 See USBPoller, USBTransfer and USBTransferHelper.
39
40 All LIBUSB_* constants are available in this module, without the LIBUSB_
41 prefix - with one exception: LIBUSB_5GBPS_OPERATION is available as
42 SUPER_SPEED_OPERATION, so it is a valid python identifier.
43
44 All LIBUSB_ERROR_* constants are available in this module as exception classes,
45 subclassing USBError.
46 """
47
48 import collections
49 import contextlib
50 from ctypes import byref, c_int, sizeof, POINTER, \
51 cast, c_uint8, c_uint16, c_ubyte, c_void_p, cdll, addressof, \
52 c_char
53 from ctypes.util import find_library
54 import functools
55 import inspect
56 import itertools
57 import sys
58 import threading
59 import warnings
60 import weakref
61 from . import _libusb1 as libusb1
62 from . import _version
63 __version__ = _version.get_versions()['version']
64 # pylint: disable=wrong-import-order,ungrouped-imports
65 if sys.platform == 'win32':
66 from ctypes import get_last_error as get_errno
67 else:
68 from ctypes import get_errno
69 # pylint: enable=wrong-import-order,ungrouped-imports
70
71 __all__ = [
72 'USBContext', 'USBDeviceHandle', 'USBDevice', 'hasCapability',
73 'USBPoller', 'USBTransfer', 'USBTransferHelper', 'EVENT_CALLBACK_SET',
74 'USBEndpoint', 'USBInterfaceSetting', 'USBInterface',
75 'USBConfiguration', 'DoomedTransferError', 'getVersion', 'USBError',
76 'setLogCallback', 'setLocale',
77 'loadLibrary',
78 ]
79 # Bind libusb1 constants and libusb1.USBError to this module, so user does not
80 # have to import two modules.
81 USBError = libusb1.USBError
82 STATUS_TO_EXCEPTION_DICT = {}
83 def __bindConstants():
84 global_dict = globals()
85 PREFIX = 'LIBUSB_'
86 for name, value in libusb1.__dict__.items():
87 if name.startswith(PREFIX):
88 name = name[len(PREFIX):]
89 # Gah.
90 if name == '5GBPS_OPERATION':
91 name = 'SUPER_SPEED_OPERATION'
92 assert name not in global_dict
93 global_dict[name] = value
94 __all__.append(name)
95 # Finer-grained exceptions.
96 for name, value in libusb1.libusb_error.forward_dict.items():
97 if value:
98 assert name.startswith(PREFIX + 'ERROR_'), name
99 if name == 'LIBUSB_ERROR_IO':
100 name = 'ErrorIO'
101 else:
102 name = ''.join(x.capitalize() for x in name.split('_')[1:])
103 name = 'USB' + name
104 assert name not in global_dict, name
105 assert value not in STATUS_TO_EXCEPTION_DICT
106 STATUS_TO_EXCEPTION_DICT[value] = global_dict[name] = type(
107 name,
108 (USBError, ),
109 {'value': value},
110 )
111 __all__.append(name)
112 __bindConstants()
113 del __bindConstants
114
115 def raiseUSBError(
116 value,
117 # Avoid globals lookup on call to work during interpreter shutdown.
118 __STATUS_TO_EXCEPTION_DICT=STATUS_TO_EXCEPTION_DICT,
119 __USBError=USBError,
120 ): # pylint: disable=dangerous-default-value
121 raise __STATUS_TO_EXCEPTION_DICT.get(value, __USBError)(value)
122
123 def mayRaiseUSBError(
124 value,
125 # Avoid globals lookup on call to work during interpreter shutdown.
126 __raiseUSBError=raiseUSBError,
127 ):
128 if value < 0:
129 __raiseUSBError(value)
130 return value
131
132 Version = collections.namedtuple(
133 'Version',
134 ['major', 'minor', 'micro', 'nano', 'rc', 'describe'],
135 )
136
137 # pylint: disable=undefined-variable
138 CONTROL_SETUP = b'\x00' * CONTROL_SETUP_SIZE
139 # pylint: enable=undefined-variable
140
141 # Default string length
142 # From a comment in libusb-1.0: "Some devices choke on size > 255"
143 STRING_LENGTH = 255
144
145 # As of v3 of USB specs, there cannot be more than 7 hubs from controller to
146 # device.
147 PATH_MAX_DEPTH = 7
148
149 EVENT_CALLBACK_SET = frozenset((
150 # pylint: disable=undefined-variable
151 TRANSFER_COMPLETED,
152 TRANSFER_ERROR,
153 TRANSFER_TIMED_OUT,
154 TRANSFER_CANCELLED,
155 TRANSFER_STALL,
156 TRANSFER_NO_DEVICE,
157 TRANSFER_OVERFLOW,
158 # pylint: enable=undefined-variable
159 ))
160
161 def DEFAULT_ASYNC_TRANSFER_ERROR_CALLBACK(_):
162 return False
163
164 def create_binary_buffer(init_or_size):
165 """
166 ctypes.create_string_buffer variant which does not add a trailing null
167 when init_or_size is not a size.
168 """
169 # As per ctypes.create_string_buffer:
170 # - int is a length
171 # - bytes is an initialiser
172 if isinstance(init_or_size, int):
173 init_or_size = bytearray(init_or_size)
174 return create_initialised_buffer(init_or_size)
175
176 class _LibUSB1Finalizer: # pylint: disable=too-few-public-methods
177 """
178 Create, and keep track of, finalizer objects.
179 Allows outstanding finalizers to be triggered, typically so C resources
180 owned by the objects associated with those finalizers are freed before
181 another one they depend (and owned by the instance of this class) on may
182 be freed.
183 """
184 def __init__(self):
185 self._finalizer_dict = {}
186 self.__finalizer_id_generator = itertools.count()
187 self.__finalizer_id_generator_lock = threading.Lock()
188
189 @staticmethod
190 def __finalize(handle, pop, func, kw):
191 try:
192 func(**kw)
193 finally:
194 pop(handle)
195
196 def _getFinalizer(self, obj, func, **kw):
197 """
198 Creates and adds to _finalizer_dict a finalizer which will trigger
199 after obj becomes unreachable and before it is garbage-collected.
200 When it triggers, func(**kw) is called and the finalizer is removed
201 from _finalizer_dict.
202
203 Returns the created finalizer object.
204 """
205 with self.__finalizer_id_generator_lock:
206 handle = next(self.__finalizer_id_generator)
207 finalizer_dict = self._finalizer_dict
208 finalizer_dict[handle] = finalizer = weakref.finalize(
209 obj,
210 functools.partial(
211 self.__finalize, # Note: static method
212 handle=handle,
213 pop=finalizer_dict.pop,
214 func=func,
215 kw=kw,
216 ),
217 )
218 return finalizer
219
220 def create_initialised_buffer(init):
221 # raises if init is an integer - this is intentional
222 string_type = c_char * len(init)
223 try:
224 # zero-copy if init is a writable buffer
225 return string_type.from_buffer(init), init
226 # cpython (3.5, 3.9) raises TypeError, pypy 5.4.1 raises ValueError
227 except (TypeError, ValueError):
228 # create our own writable buffer
229 init = bytearray(init)
230 return string_type.from_buffer(init), init
231
232 class DoomedTransferError(Exception):
233 """Exception raised when altering/submitting a doomed transfer."""
234
235 class USBTransfer:
236 """
237 USB asynchronous transfer control & data.
238
239 All modification methods will raise if called on a submitted transfer.
240 Methods noted as "should not be called on a submitted transfer" will not
241 prevent you from reading, but returned value is unspecified.
242
243 Note on user_data: because of pypy's current ctype restrictions, user_data
244 is not provided to C level, but is managed purely in python. It should
245 change nothing for you, unless you are looking at underlying C transfer
246 structure - which you should never have to.
247 """
248 __transfer = None
249 __initialized = False
250 __submitted_dict = {}
251 __callback = None
252 # Just to silence pylint watnings, this attribute gets overridden after
253 # class definition.
254 __ctypesCallbackWrapper = None
255 __doomed = False
256 __user_data = None
257 __transfer_buffer = None
258 __transfer_py_buffer = None
259
260 def __init__(
261 self,
262 context,
263 handle,
264 iso_packets,
265 before_submit,
266 after_completion,
267 getFinalizer,
268 short_is_error,
269 add_zero_packet,
270 ):
271 """
272 You should not instanciate this class directly.
273 Call "getTransfer" method on an USBDeviceHandle instance to get
274 instances of this class.
275 """
276 if iso_packets < 0:
277 raise ValueError(
278 'Cannot request a negative number of iso packets.'
279 )
280 self.__handle = handle
281 self.__before_submit = before_submit
282 self.__after_completion = after_completion
283 self.__num_iso_packets = iso_packets
284 transfer = libusb1.libusb_alloc_transfer(iso_packets)
285 if not transfer:
286 # pylint: disable=undefined-variable
287 raise USBErrorNoMem
288 # pylint: enable=undefined-variable
289 self.__transfer = transfer
290 self.setShortIsError(short_is_error)
291 self.setAddZeroPacket(add_zero_packet)
292 self.__close = getFinalizer(
293 self,
294 self.__close, # Note: class method
295 transfer=transfer,
296 context=context,
297 libusb_free_transfer=libusb1.libusb_free_transfer,
298 libusb_cancel_transfer=libusb1.libusb_cancel_transfer,
299 )
300
301 def close(self):
302 """
303 Break reference cycles to allow instance to be garbage-collected.
304 Raises if called on a submitted transfer.
305 """
306 if self.isSubmitted():
307 raise ValueError('Cannot close a submitted transfer')
308 self.doom()
309 self.__initialized = False
310 # Break possible external reference cycles
311 self.__callback = None
312 self.__user_data = None
313 # For some reason, overwriting callback is not enough to remove this
314 # reference cycle - though sometimes it works:
315 # self -> self.__dict__ -> libusb_transfer -> dict[x] -> dict[x] ->
316 # CThunkObject -> __callbackWrapper -> self
317 # So free transfer altogether.
318 self.__close()
319 self.__transfer = None
320 # pylint: disable=unused-private-member
321 self.__transfer_buffer = None
322 # pylint: enable=unused-private-member
323 # Break USBDeviceHandle reference cycle
324 self.__before_submit = None
325 self.__after_completion = None
326
327 @classmethod
328 def __close( # pylint: disable=method-hidden
329 cls,
330 transfer,
331 context,
332 libusb_free_transfer,
333 libusb_cancel_transfer,
334
335 # pylint: disable=undefined-variable
336 USBErrorInterrupted_=USBErrorInterrupted,
337 # pylint: enable=undefined-variable
338 ):
339 isSubmitted = cls.__isSubmitted
340 # Unlikely to be true if we are triggered by object destruction
341 # (cls.__submitted_dict is precisely here to prevent collection of
342 # submitted transfers).
343 # And if we are called by the user, then they should have the ability
344 # to cancel the transfer cleanly before closing it.
345 if isSubmitted(transfer):
346 libusb_cancel_transfer(transfer)
347 while isSubmitted(transfer):
348 try:
349 context.handleEvents()
350 except USBErrorInterrupted_:
351 pass
352 libusb_free_transfer(transfer)
353
354 def doom(self):
355 """
356 Prevent transfer from being submitted again.
357 """
358 self.__doomed = True
359
360 @classmethod
361 # pylint: disable=unused-private-member
362 def __callbackWrapper(cls, transfer_p):
363 # pylint: enable=unused-private-member
364 """
365 Makes it possible for user-provided callback to alter transfer when
366 fired (ie, mark transfer as not submitted upon call).
367 """
368 # pylint: disable=protected-access
369 self = cls.__submitted_dict.pop(addressof(transfer_p.contents))
370 self.__after_completion(self)
371 callback = self.__callback
372 if callback is not None:
373 callback(self)
374 if self.__doomed:
375 self.close()
376 # pylint: enable=protected-access
377
378 def setCallback(self, callback):
379 """
380 Change transfer's callback.
381 """
382 self.__callback = callback
383
384 def getCallback(self):
385 """
386 Get currently set callback.
387 """
388 return self.__callback
389
390 def setControl(
391 self, request_type, request, value, index, buffer_or_len,
392 callback=None, user_data=None, timeout=0):
393 """
394 Setup transfer for control use.
395
396 request_type, request, value, index
397 See USBDeviceHandle.controlWrite.
398 request_type defines transfer direction (see
399 ENDPOINT_OUT and ENDPOINT_IN)).
400 buffer_or_len
401 Either bytes (when sending data), or expected data length (when
402 receiving data).
403 callback
404 Callback function to be invoked on transfer completion.
405 Called with transfer as parameter, return value ignored.
406 user_data
407 User data to pass to callback function.
408 timeout
409 Transfer timeout in milliseconds. 0 to disable.
410 """
411 if self.isSubmitted():
412 raise ValueError('Cannot alter a submitted transfer')
413 if self.__doomed:
414 raise DoomedTransferError('Cannot reuse a doomed transfer')
415 if isinstance(buffer_or_len, int):
416 length = buffer_or_len
417 # pylint: disable=undefined-variable
418 string_buffer, transfer_py_buffer = create_binary_buffer(
419 length + CONTROL_SETUP_SIZE,
420 )
421 # pylint: enable=undefined-variable
422 else:
423 length = len(buffer_or_len)
424 string_buffer, transfer_py_buffer = create_binary_buffer(
425 CONTROL_SETUP + buffer_or_len,
426 )
427 self.__initialized = False
428 # pylint: disable=unused-private-member
429 self.__transfer_buffer = string_buffer
430 # pylint: enable=unused-private-member
431 # pylint: disable=undefined-variable
432 self.__transfer_py_buffer = memoryview(
433 transfer_py_buffer,
434 )[CONTROL_SETUP_SIZE:]
435 # pylint: enable=undefined-variable
436 self.__user_data = user_data
437 libusb1.libusb_fill_control_setup(
438 string_buffer, request_type, request, value, index, length)
439 libusb1.libusb_fill_control_transfer(
440 self.__transfer, self.__handle, string_buffer,
441 self.__ctypesCallbackWrapper, None, timeout)
442 self.__callback = callback
443 self.__initialized = True
444
445 def setBulk(
446 self, endpoint, buffer_or_len, callback=None, user_data=None,
447 timeout=0):
448 """
449 Setup transfer for bulk use.
450
451 endpoint
452 Endpoint to submit transfer to. Defines transfer direction (see
453 ENDPOINT_OUT and ENDPOINT_IN)).
454 buffer_or_len
455 Either bytes (when sending data), or expected data length (when
456 receiving data)
457 To avoid memory copies, use an object implementing the writeable
458 buffer interface (ex: bytearray).
459 callback
460 Callback function to be invoked on transfer completion.
461 Called with transfer as parameter, return value ignored.
462 user_data
463 User data to pass to callback function.
464 timeout
465 Transfer timeout in milliseconds. 0 to disable.
466 """
467 if self.isSubmitted():
468 raise ValueError('Cannot alter a submitted transfer')
469 if self.__doomed:
470 raise DoomedTransferError('Cannot reuse a doomed transfer')
471 string_buffer, self.__transfer_py_buffer = create_binary_buffer(
472 buffer_or_len
473 )
474 self.__initialized = False
475 # pylint: disable=unused-private-member
476 self.__transfer_buffer = string_buffer
477 # pylint: enable=unused-private-member
478 self.__user_data = user_data
479 libusb1.libusb_fill_bulk_transfer(
480 self.__transfer, self.__handle, endpoint, string_buffer,
481 sizeof(string_buffer), self.__ctypesCallbackWrapper, None, timeout)
482 self.__callback = callback
483 self.__initialized = True
484
485 def setInterrupt(
486 self, endpoint, buffer_or_len, callback=None, user_data=None,
487 timeout=0):
488 """
489 Setup transfer for interrupt use.
490
491 endpoint
492 Endpoint to submit transfer to. Defines transfer direction (see
493 ENDPOINT_OUT and ENDPOINT_IN)).
494 buffer_or_len
495 Either bytes (when sending data), or expected data length (when
496 receiving data)
497 To avoid memory copies, use an object implementing the writeable
498 buffer interface (ex: bytearray).
499 callback
500 Callback function to be invoked on transfer completion.
501 Called with transfer as parameter, return value ignored.
502 user_data
503 User data to pass to callback function.
504 timeout
505 Transfer timeout in milliseconds. 0 to disable.
506 """
507 if self.isSubmitted():
508 raise ValueError('Cannot alter a submitted transfer')
509 if self.__doomed:
510 raise DoomedTransferError('Cannot reuse a doomed transfer')
511 string_buffer, self.__transfer_py_buffer = create_binary_buffer(
512 buffer_or_len
513 )
514 self.__initialized = False
515 # pylint: disable=unused-private-member
516 self.__transfer_buffer = string_buffer
517 # pylint: enable=unused-private-member
518 self.__user_data = user_data
519 libusb1.libusb_fill_interrupt_transfer(
520 self.__transfer, self.__handle, endpoint, string_buffer,
521 sizeof(string_buffer), self.__ctypesCallbackWrapper, None, timeout)
522 self.__callback = callback
523 self.__initialized = True
524
525 def setIsochronous(
526 self, endpoint, buffer_or_len, callback=None,
527 user_data=None, timeout=0, iso_transfer_length_list=None):
528 """
529 Setup transfer for isochronous use.
530
531 endpoint
532 Endpoint to submit transfer to. Defines transfer direction (see
533 ENDPOINT_OUT and ENDPOINT_IN)).
534 buffer_or_len
535 Either bytes (when sending data), or expected data length (when
536 receiving data)
537 To avoid memory copies, use an object implementing the writeable
538 buffer interface (ex: bytearray).
539 callback
540 Callback function to be invoked on transfer completion.
541 Called with transfer as parameter, return value ignored.
542 user_data
543 User data to pass to callback function.
544 timeout
545 Transfer timeout in milliseconds. 0 to disable.
546 iso_transfer_length_list
547 List of individual transfer sizes. If not provided, buffer_or_len
548 will be divided evenly among available transfers if possible, and
549 raise ValueError otherwise.
550 """
551 if self.isSubmitted():
552 raise ValueError('Cannot alter a submitted transfer')
553 num_iso_packets = self.__num_iso_packets
554 if num_iso_packets == 0:
555 raise TypeError(
556 'This transfer canot be used for isochronous I/O. '
557 'You must get another one with a non-zero iso_packets '
558 'parameter.'
559 )
560 if self.__doomed:
561 raise DoomedTransferError('Cannot reuse a doomed transfer')
562 string_buffer, transfer_py_buffer = create_binary_buffer(buffer_or_len)
563 buffer_length = sizeof(string_buffer)
564 if iso_transfer_length_list is None:
565 iso_length, remainder = divmod(buffer_length, num_iso_packets)
566 if remainder:
567 raise ValueError(
568 f'Buffer size {buffer_length} cannot be evenly distributed '
569 f'among {num_iso_packets} transfers',
570 )
571 iso_transfer_length_list = [iso_length] * num_iso_packets
572 configured_iso_packets = len(iso_transfer_length_list)
573 if configured_iso_packets > num_iso_packets:
574 raise ValueError(
575 f'Too many ISO transfer lengths ({configured_iso_packets}), '
576 f'there are only {num_iso_packets} ISO transfers available',
577 )
578 if sum(iso_transfer_length_list) > buffer_length:
579 raise ValueError(
580 f'ISO transfers too long ({sum(iso_transfer_length_list)}), '
581 f'there are only {buffer_length} bytes available',
582 )
583 transfer_p = self.__transfer
584 self.__initialized = False
585 # pylint: disable=unused-private-member
586 self.__transfer_buffer = string_buffer
587 # pylint: enable=unused-private-member
588 self.__transfer_py_buffer = transfer_py_buffer
589 self.__user_data = user_data
590 libusb1.libusb_fill_iso_transfer(
591 transfer_p, self.__handle, endpoint, string_buffer, buffer_length,
592 configured_iso_packets, self.__ctypesCallbackWrapper, None,
593 timeout)
594 for length, iso_packet_desc in zip(
595 iso_transfer_length_list,
596 libusb1.get_iso_packet_list(transfer_p)):
597 if length <= 0:
598 raise ValueError(
599 'Negative/null length transfers are not possible.'
600 )
601 iso_packet_desc.length = length
602 self.__callback = callback
603 self.__initialized = True
604
605 def getType(self):
606 """
607 Get transfer type.
608
609 Returns one of:
610 TRANSFER_TYPE_CONTROL
611 TRANSFER_TYPE_ISOCHRONOUS
612 TRANSFER_TYPE_BULK
613 TRANSFER_TYPE_INTERRUPT
614 """
615 return self.__transfer.contents.type
616
617 def getEndpoint(self):
618 """
619 Get endpoint.
620 """
621 return self.__transfer.contents.endpoint
622
623 def getStatus(self):
624 """
625 Get transfer status.
626 Should not be called on a submitted transfer.
627 """
628 return self.__transfer.contents.status
629
630 def getActualLength(self):
631 """
632 Get actually transfered data length.
633 Should not be called on a submitted transfer.
634 """
635 return self.__transfer.contents.actual_length
636
637 def getBuffer(self):
638 """
639 Get data buffer content.
640 Should not be called on a submitted transfer.
641 """
642 return self.__transfer_py_buffer
643
644 def getUserData(self):
645 """
646 Retrieve user data provided on setup.
647 """
648 return self.__user_data
649
650 def setUserData(self, user_data):
651 """
652 Change user data.
653 """
654 self.__user_data = user_data
655
656 def getISOBufferList(self):
657 """
658 Get individual ISO transfer's buffer.
659 Returns a list with one item per ISO transfer, with their
660 individually-configured sizes.
661 Returned list is consistent with getISOSetupList return value.
662 Should not be called on a submitted transfer.
663
664 See also iterISO.
665 """
666 transfer_p = self.__transfer
667 transfer = transfer_p.contents
668 # pylint: disable=undefined-variable
669 if transfer.type != TRANSFER_TYPE_ISOCHRONOUS:
670 # pylint: enable=undefined-variable
671 raise TypeError(
672 'This method cannot be called on non-iso transfers.'
673 )
674 return libusb1.get_iso_packet_buffer_list(transfer_p)
675
676 def getISOSetupList(self):
677 """
678 Get individual ISO transfer's setup.
679 Returns a list of dicts, each containing an individual ISO transfer
680 parameters:
681 - length
682 - actual_length
683 - status
684 (see libusb1's API documentation for their signification)
685 Returned list is consistent with getISOBufferList return value.
686 Should not be called on a submitted transfer (except for 'length'
687 values).
688 """
689 transfer_p = self.__transfer
690 transfer = transfer_p.contents
691 # pylint: disable=undefined-variable
692 if transfer.type != TRANSFER_TYPE_ISOCHRONOUS:
693 # pylint: enable=undefined-variable
694 raise TypeError(
695 'This method cannot be called on non-iso transfers.'
696 )
697 return [
698 {
699 'length': x.length,
700 'actual_length': x.actual_length,
701 'status': x.status,
702 }
703 for x in libusb1.get_iso_packet_list(transfer_p)
704 ]
705
706 def iterISO(self):
707 """
708 Generator yielding (status, buffer) for each isochornous transfer.
709 buffer is truncated to actual_length.
710 This is more efficient than calling both getISOBufferList and
711 getISOSetupList when receiving data.
712 Should not be called on a submitted transfer.
713 """
714 transfer_p = self.__transfer
715 transfer = transfer_p.contents
716 # pylint: disable=undefined-variable
717 if transfer.type != TRANSFER_TYPE_ISOCHRONOUS:
718 # pylint: enable=undefined-variable
719 raise TypeError(
720 'This method cannot be called on non-iso transfers.'
721 )
722 buffer_position = transfer.buffer
723 for iso_transfer in libusb1.get_iso_packet_list(transfer_p):
724 yield (
725 iso_transfer.status,
726 libusb1.buffer_at(buffer_position, iso_transfer.actual_length),
727 )
728 buffer_position += iso_transfer.length
729
730 def setBuffer(self, buffer_or_len):
731 """
732 Replace buffer with a new one.
733 Allows resizing read buffer and replacing data sent.
734 Note: resizing is not allowed for isochronous buffer (use
735 setIsochronous).
736 Note: disallowed on control transfers (use setControl).
737 """
738 if self.isSubmitted():
739 raise ValueError('Cannot alter a submitted transfer')
740 transfer = self.__transfer.contents
741 # pylint: disable=undefined-variable
742 if transfer.type == TRANSFER_TYPE_CONTROL:
743 # pylint: enable=undefined-variable
744 raise ValueError(
745 'To alter control transfer buffer, use setControl'
746 )
747 buff, transfer_py_buffer = create_binary_buffer(buffer_or_len)
748 # pylint: disable=undefined-variable
749 if transfer.type == TRANSFER_TYPE_ISOCHRONOUS and \
750 sizeof(buff) != transfer.length:
751 # pylint: enable=undefined-variable
752 raise ValueError(
753 'To alter isochronous transfer buffer length, use '
754 'setIsochronous'
755 )
756 # pylint: disable=unused-private-member
757 self.__transfer_buffer = buff
758 # pylint: enable=unused-private-member
759 self.__transfer_py_buffer = transfer_py_buffer
760 transfer.buffer = cast(buff, c_void_p)
761 transfer.length = sizeof(buff)
762
763 def isShortAnError(self):
764 """
765 Returns whether the LIBUSB_TRANSFER_SHORT_NOT_OK flag is set on this
766 transfer.
767 """
768 return bool(self.__transfer.contents.flags & libusb1.LIBUSB_TRANSFER_SHORT_NOT_OK)
769
770 def setShortIsError(self, state):
771 """
772 state (bool)
773 When true, LIBUSB_TRANSFER_SHORT_NOT_OK flag is set on this
774 transfer.
775 Otherwise, it is cleared.
776 """
777 if state:
778 self.__transfer.contents.flags |= libusb1.LIBUSB_TRANSFER_SHORT_NOT_OK
779 else:
780 self.__transfer.contents.flags &= ~libusb1.LIBUSB_TRANSFER_SHORT_NOT_OK
781
782 def isZeroPacketAdded(self):
783 """
784 Returns whether the LIBUSB_TRANSFER_ADD_ZERO_PACKET flag is set on this
785 transfer.
786 """
787 return bool(self.__transfer.contents.flags & libusb1.LIBUSB_TRANSFER_ADD_ZERO_PACKET)
788
789 def setAddZeroPacket(self, state):
790 """
791 state (bool)
792 When true, LIBUSB_TRANSFER_ADD_ZERO_PACKET flag is set on this
793 transfer.
794 Otherwise, it is cleared.
795 """
796 if state:
797 self.__transfer.contents.flags |= libusb1.LIBUSB_TRANSFER_ADD_ZERO_PACKET
798 else:
799 self.__transfer.contents.flags &= ~libusb1.LIBUSB_TRANSFER_ADD_ZERO_PACKET
800
801 def isSubmitted(self):
802 """
803 Tells if this transfer is submitted and still pending.
804 """
805 transfer = self.__transfer
806 return transfer is not None and self.__isSubmitted(transfer)
807
808 @classmethod
809 def __isSubmitted(cls, transfer):
810 return addressof(transfer.contents) in cls.__submitted_dict
811
812 def submit(self):
813 """
814 Submit transfer for asynchronous handling.
815 """
816 if self.isSubmitted():
817 raise ValueError('Cannot submit a submitted transfer')
818 if not self.__initialized:
819 raise ValueError(
820 'Cannot submit a transfer until it has been initialized'
821 )
822 if self.__doomed:
823 raise DoomedTransferError('Cannot submit doomed transfer')
824 self.__before_submit(self)
825 transfer = self.__transfer
826 assert transfer is not None
827 self.__submitted_dict[addressof(transfer.contents)] = self
828 result = libusb1.libusb_submit_transfer(transfer)
829 if result:
830 self.__after_completion(self)
831 self.__submitted_dict.pop(addressof(transfer.contents))
832 raiseUSBError(result)
833
834 def cancel(self):
835 """
836 Cancel transfer.
837 Note: cancellation happens asynchronously, so you must wait for
838 TRANSFER_CANCELLED.
839 """
840 if not self.isSubmitted():
841 # XXX: Workaround for a bug reported on libusb 1.0.8: calling
842 # libusb_cancel_transfer on a non-submitted transfer might
843 # trigger a segfault.
844 raise USBErrorNotFound # pylint: disable=undefined-variable
845 mayRaiseUSBError(libusb1.libusb_cancel_transfer(self.__transfer))
846
847 # XXX: This is very unsightly, but I do not see another way of declaring within
848 # class body both the class method and its ctypes function pointer.
849 # pylint: disable=protected-access,no-member
850 USBTransfer._USBTransfer__ctypesCallbackWrapper = libusb1.libusb_transfer_cb_fn_p(
851 USBTransfer._USBTransfer__callbackWrapper,
852 )
853 # pylint: enable=protected-access,no-member
854
855 class USBTransferHelper:
856 """
857 Simplifies subscribing to the same transfer over and over, and callback
858 handling:
859 - no need to read event status to execute apropriate code, just setup
860 different functions for each status code
861 - just return True instead of calling submit
862 - no need to check if transfer is doomed before submitting it again,
863 DoomedTransferError is caught.
864
865 Callbacks used in this class must follow the callback API described in
866 USBTransfer, and are expected to return a boolean:
867 - True if transfer is to be submitted again (to receive/send more data)
868 - False otherwise
869
870 Note: as per libusb1 specifications, isochronous transfer global state
871 might be TRANSFER_COMPLETED although some individual packets might
872 have an error status. You can check individual packet status by calling
873 getISOSetupList on transfer object in your callback.
874 """
875 def __init__(self, transfer=None):
876 """
877 Create a transfer callback dispatcher.
878
879 transfer parameter is deprecated. If provided, it will be equivalent
880 to:
881 helper = USBTransferHelper()
882 transfer.setCallback(helper)
883 and also allows using deprecated methods on this class (otherwise,
884 they raise AttributeError).
885 """
886 if transfer is not None:
887 # Deprecated: to drop
888 self.__transfer = transfer
889 transfer.setCallback(self)
890 self.__event_callback_dict = {}
891 self.__errorCallback = DEFAULT_ASYNC_TRANSFER_ERROR_CALLBACK
892
893 def submit(self):
894 """
895 Submit the asynchronous read request.
896 Deprecated. Use submit on transfer.
897 """
898 # Deprecated: to drop
899 self.__transfer.submit()
900
901 def cancel(self):
902 """
903 Cancel a pending read request.
904 Deprecated. Use cancel on transfer.
905 """
906 # Deprecated: to drop
907 self.__transfer.cancel()
908
909 def setEventCallback(self, event, callback):
910 """
911 Set a function to call for a given event.
912 event must be one of:
913 TRANSFER_COMPLETED
914 TRANSFER_ERROR
915 TRANSFER_TIMED_OUT
916 TRANSFER_CANCELLED
917 TRANSFER_STALL
918 TRANSFER_NO_DEVICE
919 TRANSFER_OVERFLOW
920 """
921 if event not in EVENT_CALLBACK_SET:
922 raise ValueError(f'Unknown event {event!r}.')
923 self.__event_callback_dict[event] = callback
924
925 def setDefaultCallback(self, callback):
926 """
927 Set the function to call for event which don't have a specific callback
928 registered.
929 The initial default callback does nothing and returns False.
930 """
931 self.__errorCallback = callback
932
933 def getEventCallback(self, event, default=None):
934 """
935 Return the function registered to be called for given event identifier.
936 """
937 return self.__event_callback_dict.get(event, default)
938
939 def __call__(self, transfer):
940 """
941 Callback to set on transfers.
942 """
943 if self.getEventCallback(transfer.getStatus(), self.__errorCallback)(
944 transfer):
945 try:
946 transfer.submit()
947 except DoomedTransferError:
948 pass
949
950 def isSubmited(self):
951 """
952 Returns whether this reader is currently waiting for an event.
953 Deprecatd. Use isSubmitted on transfer.
954 """
955 # Deprecated: to drop
956 return self.__transfer.isSubmitted()
957
958 class USBPoller:
959 """
960 Class allowing integration of USB event polling in a file-descriptor
961 monitoring event loop.
962
963 WARNING: Do not call "poll" from several threads concurently. Do not use
964 synchronous USB transfers in a thread while "poll" is running. Doing so
965 will result in unnecessarily long pauses in some threads. Opening and/or
966 closing devices while polling can cause race conditions to occur.
967 """
968 def __init__(self, context, poller):
969 """
970 Create a poller for given context.
971 Warning: it will not check if another poller instance was already
972 present for that context, and will replace it.
973
974 poller is a polling instance implementing the following methods:
975 - register(fd, event_flags)
976 event_flags have the same meaning as in poll API (POLLIN & POLLOUT)
977 - unregister(fd)
978 - poll(timeout)
979 timeout being a float in seconds, or negative/None if there is no
980 timeout.
981 It must return a list of (descriptor, event) pairs.
982 Note: USBPoller is itself a valid poller.
983 Note2: select.poll uses a timeout in milliseconds, for some reason
984 (all other select.* classes use seconds for timeout), so you should
985 wrap it to convert & round/truncate timeout.
986 """
987 self.__context = context
988 self.__poller = poller
989 self.__fd_set = set()
990 context.setPollFDNotifiers(self._registerFD, self._unregisterFD)
991 for fd, events in context.getPollFDList():
992 self._registerFD(fd, events)
993
994 def __del__(self):
995 self.__context.setPollFDNotifiers(None, None)
996
997 def poll(self, timeout=None):
998 """
999 Poll for events.
1000 timeout can be a float in seconds, or None for no timeout.
1001 Returns a list of (descriptor, event) pairs.
1002 """
1003 next_usb_timeout = self.__context.getNextTimeout()
1004 if timeout is None or timeout < 0:
1005 usb_timeout = next_usb_timeout
1006 elif next_usb_timeout:
1007 usb_timeout = min(next_usb_timeout, timeout)
1008 else:
1009 usb_timeout = timeout
1010 event_list = self.__poller.poll(usb_timeout)
1011 if event_list:
1012 fd_set = self.__fd_set
1013 result = [(x, y) for x, y in event_list if x not in fd_set]
1014 if len(result) != len(event_list):
1015 self.__context.handleEventsTimeout()
1016 else:
1017 result = event_list
1018 self.__context.handleEventsTimeout()
1019 return result
1020
1021 def register(self, fd, events):
1022 """
1023 Register an USB-unrelated fd to poller.
1024 Convenience method.
1025 """
1026 if fd in self.__fd_set:
1027 raise ValueError(
1028 'This fd is a special USB event fd, it cannot be polled.'
1029 )
1030 self.__poller.register(fd, events)
1031
1032 def unregister(self, fd):
1033 """
1034 Unregister an USB-unrelated fd from poller.
1035 Convenience method.
1036 """
1037 if fd in self.__fd_set:
1038 raise ValueError(
1039 'This fd is a special USB event fd, it must stay registered.'
1040 )
1041 self.__poller.unregister(fd)
1042
1043 # pylint: disable=unused-argument
1044 def _registerFD(self, fd, events, user_data=None):
1045 self.register(fd, events)
1046 self.__fd_set.add(fd)
1047 # pylint: enable=unused-argument
1048
1049 # pylint: disable=unused-argument
1050 def _unregisterFD(self, fd, user_data=None):
1051 self.__fd_set.discard(fd)
1052 self.unregister(fd)
1053 # pylint: enable=unused-argument
1054
1055 class _ReleaseInterface:
1056 def __init__(self, handle, interface):
1057 self._handle = handle
1058 self._interface = interface
1059
1060 def __enter__(self):
1061 # USBDeviceHandle.claimInterface already claimed the interface.
1062 pass
1063
1064 def __exit__(self, exc_type, exc_val, exc_tb):
1065 self._handle.releaseInterface(self._interface)
1066
1067 class USBDeviceHandle(_LibUSB1Finalizer):
1068 """
1069 Represents an opened USB device.
1070 """
1071 __handle = None
1072
1073 def __init__(
1074 self,
1075 context,
1076 handle,
1077 device,
1078 getFinalizer,
1079 can_close_device,
1080 ):
1081 """
1082 You should not instanciate this class directly.
1083 Call "open" method on an USBDevice instance to get an USBDeviceHandle
1084 instance.
1085 """
1086 super().__init__()
1087 self.__context = context
1088 # Strong references to inflight transfers so they do not get freed
1089 # even if user drops all strong references to them. If this instance
1090 # is garbage-collected, we close all transfers, so it's fine.
1091 inflight = set()
1092 # XXX: For some reason, doing self.__inflight.{add|remove} inside
1093 # getTransfer causes extra intermediate python objects for each
1094 # allocated transfer. Storing them as properties solves this. Found
1095 # with objgraph.
1096 self.__inflight_add = inflight.add
1097 self.__inflight_remove = inflight.remove
1098 self.__handle = handle
1099 self.__device = device
1100 self.close = getFinalizer(
1101 self,
1102 self.close, # Note: static method
1103 context=context,
1104 handle=handle,
1105 device=(
1106 device
1107 if can_close_device else
1108 None
1109 ),
1110 inflight=inflight,
1111 finalizer_dict=self._finalizer_dict,
1112 libusb_close=libusb1.libusb_close,
1113 )
1114
1115 @staticmethod
1116 def close( # pylint: disable=method-hidden
1117 context,
1118 handle,
1119 device,
1120 inflight,
1121 finalizer_dict,
1122 libusb_close,
1123
1124 set_=set,
1125 # pylint: disable=undefined-variable
1126 USBErrorNotFound_=USBErrorNotFound,
1127 USBErrorNoDevice_=USBErrorNoDevice,
1128 USBErrorInterrupted_=USBErrorInterrupted,
1129 # pylint: enable=undefined-variable
1130 ):
1131 """
1132 Close this handle. If not called explicitely, will be called by
1133 destructor.
1134
1135 This method cancels any in-flight transfer when it is called. As
1136 cancellation is not immediate, this method needs to let libusb handle
1137 events until transfers are actually cancelled.
1138 In multi-threaded programs, this can lead to stalls. To avoid this,
1139 do not close nor let GC collect a USBDeviceHandle which has in-flight
1140 transfers.
1141 """
1142 cancelled_set = set_()
1143 while inflight:
1144 for transfer in tuple(inflight):
1145 if transfer not in cancelled_set:
1146 try:
1147 transfer.cancel()
1148 except (USBErrorNotFound_, USBErrorNoDevice_):
1149 pass
1150 cancelled_set.add(transfer)
1151 try:
1152 context.handleEvents()
1153 except USBErrorInterrupted_:
1154 pass
1155 while finalizer_dict:
1156 for finalizer_handle, finalizer in list(finalizer_dict.items()):
1157 finalizer()
1158 assert finalizer_handle not in finalizer_dict
1159 if device is not None:
1160 device.close()
1161 libusb_close(handle)
1162
1163 def getDevice(self):
1164 """
1165 Get an USBDevice instance for the device accessed through this handle,
1166 to access to the descriptors available in OS cache.
1167 """
1168 return self.__device
1169
1170 def getConfiguration(self):
1171 """
1172 Get the current configuration number for this device.
1173 """
1174 configuration = c_int()
1175 mayRaiseUSBError(libusb1.libusb_get_configuration(
1176 self.__handle, byref(configuration),
1177 ))
1178 return configuration.value
1179
1180 def setConfiguration(self, configuration):
1181 """
1182 Set the configuration number for this device.
1183 """
1184 mayRaiseUSBError(
1185 libusb1.libusb_set_configuration(self.__handle, configuration),
1186 )
1187
1188 def getManufacturer(self):
1189 """
1190 Get device's manufaturer name.
1191 """
1192 return self.getASCIIStringDescriptor(
1193 self.__device.device_descriptor.iManufacturer,
1194 )
1195
1196 def getProduct(self):
1197 """
1198 Get device's product name.
1199 """
1200 return self.getASCIIStringDescriptor(
1201 self.__device.device_descriptor.iProduct,
1202 )
1203
1204 def getSerialNumber(self):
1205 """
1206 Get device's serial number.
1207 """
1208 return self.getASCIIStringDescriptor(
1209 self.__device.device_descriptor.iSerialNumber,
1210 )
1211
1212 def claimInterface(self, interface):
1213 """
1214 Claim (= get exclusive access to) given interface number. Required to
1215 receive/send data.
1216
1217 Can be used as a context manager:
1218 with handle.claimInterface(0):
1219 # do stuff
1220 # handle.releaseInterface(0) gets automatically called
1221 """
1222 mayRaiseUSBError(
1223 libusb1.libusb_claim_interface(self.__handle, interface),
1224 )
1225 return _ReleaseInterface(self, interface)
1226
1227 def releaseInterface(self, interface):
1228 """
1229 Release interface, allowing another process to use it.
1230 """
1231 mayRaiseUSBError(
1232 libusb1.libusb_release_interface(self.__handle, interface),
1233 )
1234
1235 def setInterfaceAltSetting(self, interface, alt_setting):
1236 """
1237 Set interface's alternative setting (both parameters are integers).
1238 """
1239 mayRaiseUSBError(libusb1.libusb_set_interface_alt_setting(
1240 self.__handle, interface, alt_setting,
1241 ))
1242
1243 def clearHalt(self, endpoint):
1244 """
1245 Clear a halt state on given endpoint number.
1246 """
1247 mayRaiseUSBError(libusb1.libusb_clear_halt(self.__handle, endpoint))
1248
1249 def resetDevice(self):
1250 """
1251 Reinitialise current device.
1252 Attempts to restore current configuration & alt settings.
1253 If this fails, will result in a device disconnect & reconnect, so you
1254 have to close current device and rediscover it (notified by an
1255 USBErrorNotFound exception).
1256 """
1257 mayRaiseUSBError(libusb1.libusb_reset_device(self.__handle))
1258
1259 def kernelDriverActive(self, interface):
1260 """
1261 Tell whether a kernel driver is active on given interface number.
1262 """
1263 result = libusb1.libusb_kernel_driver_active(self.__handle, interface)
1264 if result == 0:
1265 return False
1266 if result == 1:
1267 return True
1268 raiseUSBError(result)
1269 return None # unreachable, to make pylint happy
1270
1271 def detachKernelDriver(self, interface):
1272 """
1273 Ask kernel driver to detach from given interface number.
1274 """
1275 mayRaiseUSBError(
1276 libusb1.libusb_detach_kernel_driver(self.__handle, interface),
1277 )
1278
1279 def attachKernelDriver(self, interface):
1280 """
1281 Ask kernel driver to re-attach to given interface number.
1282 """
1283 mayRaiseUSBError(
1284 libusb1.libusb_attach_kernel_driver(self.__handle, interface),
1285 )
1286
1287 def setAutoDetachKernelDriver(self, enable):
1288 """
1289 Control automatic kernel driver detach.
1290 enable (bool)
1291 True to enable auto-detach, False to disable it.
1292 """
1293 mayRaiseUSBError(libusb1.libusb_set_auto_detach_kernel_driver(
1294 self.__handle, bool(enable),
1295 ))
1296
1297 def getSupportedLanguageList(self):
1298 """
1299 Return a list of USB language identifiers (as integers) supported by
1300 current device for its string descriptors.
1301
1302 Note: language identifiers seem (I didn't check them all...) very
1303 similar to windows language identifiers, so you may want to use
1304 locales.windows_locale to get an rfc3066 representation. The 5 standard
1305 HID language codes are missing though.
1306 """
1307 descriptor_string, _ = create_binary_buffer(STRING_LENGTH)
1308 result = libusb1.libusb_get_string_descriptor(
1309 self.__handle, 0, 0, descriptor_string, sizeof(descriptor_string),
1310 )
1311 # pylint: disable=undefined-variable
1312 if result == ERROR_PIPE:
1313 # pylint: enable=undefined-variable
1314 # From libusb_control_transfer doc:
1315 # control request not supported by the device
1316 return []
1317 mayRaiseUSBError(result)
1318 langid_list = cast(descriptor_string, POINTER(c_uint16))
1319 return [
1320 libusb1.libusb_le16_to_cpu(langid_list[offset])
1321 for offset in range(1, cast(descriptor_string, POINTER(c_ubyte))[0] // 2)
1322 ]
1323
1324 def getStringDescriptor(self, descriptor, lang_id, errors='strict'):
1325 """
1326 Fetch description string for given descriptor and in given language.
1327 Use getSupportedLanguageList to know which languages are available.
1328 Return value is a unicode string.
1329 Return None if there is no such descriptor on device.
1330 """
1331 if descriptor == 0:
1332 return None
1333 descriptor_string = bytearray(STRING_LENGTH)
1334 try:
1335 received = mayRaiseUSBError(libusb1.libusb_get_string_descriptor(
1336 self.__handle, descriptor, lang_id,
1337 create_binary_buffer(descriptor_string)[0],
1338 STRING_LENGTH,
1339 ))
1340 # pylint: disable=undefined-variable
1341 except USBErrorNotFound:
1342 # pylint: enable=undefined-variable
1343 return None
1344 # pylint: disable=undefined-variable
1345 if received < 2 or descriptor_string[1] != DT_STRING:
1346 # pylint: enable=undefined-variable
1347 raise ValueError('Invalid string descriptor')
1348 return descriptor_string[2:min(
1349 received,
1350 descriptor_string[0],
1351 )].decode('UTF-16-LE', errors=errors)
1352
1353 def getASCIIStringDescriptor(self, descriptor, errors='strict'):
1354 """
1355 Fetch description string for given descriptor in first available
1356 language.
1357 Return value is a unicode string.
1358 Return None if there is no such descriptor on device.
1359 """
1360 if descriptor == 0:
1361 return None
1362 descriptor_string = bytearray(STRING_LENGTH)
1363 try:
1364 received = mayRaiseUSBError(libusb1.libusb_get_string_descriptor_ascii(
1365 self.__handle, descriptor,
1366 create_binary_buffer(descriptor_string)[0],
1367 STRING_LENGTH,
1368 ))
1369 # pylint: disable=undefined-variable
1370 except USBErrorNotFound:
1371 # pylint: enable=undefined-variable
1372 return None
1373 return descriptor_string[:received].decode('ASCII', errors=errors)
1374
1375 # Sync I/O
1376
1377 def _controlTransfer(
1378 self, request_type, request, value, index, data, length, timeout):
1379 result = libusb1.libusb_control_transfer(
1380 self.__handle, request_type, request, value, index, data, length,
1381 timeout,
1382 )
1383 mayRaiseUSBError(result)
1384 return result
1385
1386 def controlWrite(
1387 self, request_type, request, value, index, data, timeout=0):
1388 """
1389 Synchronous control write.
1390 request_type: request type bitmask (bmRequestType), see
1391 constants TYPE_* and RECIPIENT_*.
1392 request: request id (some values are standard).
1393 value, index, data: meaning is request-dependent.
1394 timeout: in milliseconds, how long to wait for device acknowledgement.
1395 Set to 0 to disable.
1396
1397 To avoid memory copies, use an object implementing the writeable buffer
1398 interface (ex: bytearray) for the "data" parameter.
1399
1400 Returns the number of bytes actually sent.
1401 """
1402 # pylint: disable=undefined-variable
1403 request_type = (request_type & ~ENDPOINT_DIR_MASK) | ENDPOINT_OUT
1404 # pylint: enable=undefined-variable
1405 data, _ = create_initialised_buffer(data)
1406 return self._controlTransfer(request_type, request, value, index, data,
1407 sizeof(data), timeout)
1408
1409 def controlRead(
1410 self, request_type, request, value, index, length, timeout=0):
1411 """
1412 Synchronous control read.
1413 timeout: in milliseconds, how long to wait for data. Set to 0 to
1414 disable.
1415 See controlWrite for other parameters description.
1416
1417 To avoid memory copies, use an object implementing the writeable buffer
1418 interface (ex: bytearray) for the "data" parameter.
1419
1420 Returns received data.
1421 """
1422 # pylint: disable=undefined-variable
1423 request_type = (request_type & ~ENDPOINT_DIR_MASK) | ENDPOINT_IN
1424 # pylint: enable=undefined-variable
1425 data, data_buffer = create_binary_buffer(length)
1426 transferred = self._controlTransfer(
1427 request_type, request, value, index, data, length, timeout,
1428 )
1429 return data_buffer[:transferred]
1430
1431 def _bulkTransfer(self, endpoint, data, length, timeout):
1432 transferred = c_int()
1433 try:
1434 mayRaiseUSBError(libusb1.libusb_bulk_transfer(
1435 self.__handle, endpoint, data, length, byref(transferred), timeout,
1436 ))
1437 # pylint: disable=undefined-variable
1438 except USBErrorTimeout as exception:
1439 # pylint: enable=undefined-variable
1440 exception.transferred = transferred.value
1441 raise
1442 return transferred.value
1443
1444 def bulkWrite(self, endpoint, data, timeout=0):
1445 """
1446 Synchronous bulk write.
1447 endpoint: endpoint to send data to.
1448 data: data to send.
1449 timeout: in milliseconds, how long to wait for device acknowledgement.
1450 Set to 0 to disable.
1451
1452 To avoid memory copies, use an object implementing the writeable buffer
1453 interface (ex: bytearray) for the "data" parameter.
1454
1455 Returns the number of bytes actually sent.
1456
1457 May raise an exception from the USBError family. USBErrorTimeout
1458 exception has a "transferred" property giving the number of bytes sent
1459 up to the timeout.
1460 """
1461 # pylint: disable=undefined-variable
1462 endpoint = (endpoint & ~ENDPOINT_DIR_MASK) | ENDPOINT_OUT
1463 # pylint: enable=undefined-variable
1464 data, _ = create_initialised_buffer(data)
1465 return self._bulkTransfer(endpoint, data, sizeof(data), timeout)
1466
1467 def bulkRead(self, endpoint, length, timeout=0):
1468 """
1469 Synchronous bulk read.
1470 timeout: in milliseconds, how long to wait for data. Set to 0 to
1471 disable.
1472 See bulkWrite for other parameters description.
1473
1474 To avoid memory copies, use an object implementing the writeable buffer
1475 interface (ex: bytearray) for the "data" parameter.
1476
1477 Returns received data.
1478
1479 May raise an exception from the USBError family. USBErrorTimeout
1480 exception has a "received" property giving the bytes received up to the
1481 timeout.
1482 """
1483 # pylint: disable=undefined-variable
1484 endpoint = (endpoint & ~ENDPOINT_DIR_MASK) | ENDPOINT_IN
1485 # pylint: enable=undefined-variable
1486 data, data_buffer = create_binary_buffer(length)
1487 try:
1488 transferred = self._bulkTransfer(endpoint, data, length, timeout)
1489 # pylint: disable=undefined-variable
1490 except USBErrorTimeout as exception:
1491 # pylint: enable=undefined-variable
1492 exception.received = data_buffer[:exception.transferred]
1493 raise
1494 return data_buffer[:transferred]
1495
1496 def _interruptTransfer(self, endpoint, data, length, timeout):
1497 transferred = c_int()
1498 try:
1499 mayRaiseUSBError(libusb1.libusb_interrupt_transfer(
1500 self.__handle,
1501 endpoint,
1502 data,
1503 length,
1504 byref(transferred),
1505 timeout,
1506 ))
1507 # pylint: disable=undefined-variable
1508 except USBErrorTimeout as exception:
1509 # pylint: enable=undefined-variable
1510 exception.transferred = transferred.value
1511 raise
1512 return transferred.value
1513
1514 def interruptWrite(self, endpoint, data, timeout=0):
1515 """
1516 Synchronous interrupt write.
1517 endpoint: endpoint to send data to.
1518 data: data to send.
1519 timeout: in milliseconds, how long to wait for device acknowledgement.
1520 Set to 0 to disable.
1521
1522 To avoid memory copies, use an object implementing the writeable buffer
1523 interface (ex: bytearray) for the "data" parameter.
1524
1525 Returns the number of bytes actually sent.
1526
1527 May raise an exception from the USBError family. USBErrorTimeout
1528 exception has a "transferred" property giving the number of bytes sent
1529 up to the timeout.
1530 """
1531 # pylint: disable=undefined-variable
1532 endpoint = (endpoint & ~ENDPOINT_DIR_MASK) | ENDPOINT_OUT
1533 # pylint: enable=undefined-variable
1534 data, _ = create_initialised_buffer(data)
1535 return self._interruptTransfer(endpoint, data, sizeof(data), timeout)
1536
1537 def interruptRead(self, endpoint, length, timeout=0):
1538 """
1539 Synchronous interrupt write.
1540 timeout: in milliseconds, how long to wait for data. Set to 0 to
1541 disable.
1542 See interruptWrite for other parameters description.
1543
1544 To avoid memory copies, use an object implementing the writeable buffer
1545 interface (ex: bytearray) for the "data" parameter.
1546
1547 Returns received data.
1548
1549 May raise an exception from the USBError family. USBErrorTimeout
1550 exception has a "received" property giving the bytes received up to the
1551 timeout.
1552 """
1553 # pylint: disable=undefined-variable
1554 endpoint = (endpoint & ~ENDPOINT_DIR_MASK) | ENDPOINT_IN
1555 # pylint: enable=undefined-variable
1556 data, data_buffer = create_binary_buffer(length)
1557 try:
1558 transferred = self._interruptTransfer(
1559 endpoint,
1560 data,
1561 length,
1562 timeout,
1563 )
1564 # pylint: disable=undefined-variable
1565 except USBErrorTimeout as exception:
1566 # pylint: enable=undefined-variable
1567 exception.received = data_buffer[:exception.transferred]
1568 raise
1569 return data_buffer[:transferred]
1570
1571 def getTransfer(self, iso_packets=0, short_is_error=False, add_zero_packet=False):
1572 """
1573 Get an USBTransfer instance for asynchronous use.
1574 iso_packets: the number of isochronous transfer descriptors to
1575 allocate.
1576 short_is_error: When true, short frames are reported as errors.
1577 add_zero_packet: When true, transfers of a multiple of the endpoint
1578 size are followed by a zero-length packet.
1579 """
1580 return USBTransfer(
1581 context=self.__context,
1582 handle=self.__handle,
1583 iso_packets=iso_packets,
1584 before_submit=self.__inflight_add,
1585 after_completion=self.__inflight_remove,
1586 getFinalizer=self._getFinalizer,
1587 short_is_error=short_is_error,
1588 add_zero_packet=add_zero_packet,
1589 )
1590
1591 class USBConfiguration:
1592 def __init__(self, context, config, device_speed):
1593 """
1594 You should not instanciate this class directly.
1595 Call USBDevice methods to get instances of this class.
1596 """
1597 if not isinstance(config, libusb1.libusb_config_descriptor):
1598 raise TypeError('Unexpected descriptor type.')
1599 self.__config = config
1600 self.__context = context
1601 self.__device_speed = device_speed
1602
1603 def getNumInterfaces(self):
1604 return self.__config.bNumInterfaces
1605
1606 __len__ = getNumInterfaces
1607
1608 def getConfigurationValue(self):
1609 return self.__config.bConfigurationValue
1610
1611 def getDescriptor(self):
1612 return self.__config.iConfiguration
1613
1614 def getAttributes(self):
1615 return self.__config.bmAttributes
1616
1617 def getMaxPower(self):
1618 """
1619 Returns device's power consumption in mA.
1620
1621 USB descriptor is expressed in units of 2 mA when the device is operating in high-speed mode
1622 and in units of 8 mA when the device is operating in super-speed mode. This function scales
1623 the descriptor value appropriately.
1624 """
1625 # pylint: disable=undefined-variable
1626 return self.__config.MaxPower * (8 if self.__device_speed == SPEED_SUPER else 2)
1627 # pylint: enable=undefined-variable
1628
1629 def getExtra(self):
1630 """
1631 Returns a list of extra (non-basic) descriptors (DFU, HID, ...).
1632 """
1633 return libusb1.get_extra(self.__config)
1634
1635 def __iter__(self):
1636 """
1637 Iterates over interfaces available in this configuration, yielding
1638 USBInterface instances.
1639 """
1640 context = self.__context
1641 interface_list = self.__config.interface
1642 for interface_num in range(self.getNumInterfaces()):
1643 yield USBInterface(context, interface_list[interface_num])
1644
1645 # BBB
1646 iterInterfaces = __iter__
1647
1648 def __getitem__(self, interface):
1649 """
1650 Returns an USBInterface instance.
1651 """
1652 if not isinstance(interface, int):
1653 raise TypeError('interface parameter must be an integer')
1654 if not 0 <= interface < self.getNumInterfaces():
1655 raise IndexError(f'No such interface: {interface!r}')
1656 return USBInterface(self.__context, self.__config.interface[interface])
1657
1658 class USBInterface:
1659 def __init__(self, context, interface):
1660 """
1661 You should not instanciate this class directly.
1662 Call USBConfiguration methods to get instances of this class.
1663 """
1664 if not isinstance(interface, libusb1.libusb_interface):
1665 raise TypeError('Unexpected descriptor type.')
1666 self.__interface = interface
1667 self.__context = context
1668
1669 def getNumSettings(self):
1670 return self.__interface.num_altsetting
1671
1672 __len__ = getNumSettings
1673
1674 def __iter__(self):
1675 """
1676 Iterates over settings in this insterface, yielding
1677 USBInterfaceSetting instances.
1678 """
1679 context = self.__context
1680 alt_setting_list = self.__interface.altsetting
1681 for alt_setting_num in range(self.getNumSettings()):
1682 yield USBInterfaceSetting(
1683 context, alt_setting_list[alt_setting_num])
1684
1685 # BBB
1686 iterSettings = __iter__
1687
1688 def __getitem__(self, alt_setting):
1689 """
1690 Returns an USBInterfaceSetting instance.
1691 """
1692 if not isinstance(alt_setting, int):
1693 raise TypeError('alt_setting parameter must be an integer')
1694 if not 0 <= alt_setting < self.getNumSettings():
1695 raise IndexError(f'No such setting: {alt_setting!r}')
1696 return USBInterfaceSetting(
1697 self.__context, self.__interface.altsetting[alt_setting])
1698
1699 class USBInterfaceSetting:
1700 def __init__(self, context, alt_setting):
1701 """
1702 You should not instanciate this class directly.
1703 Call USBDevice or USBInterface methods to get instances of this class.
1704 """
1705 if not isinstance(alt_setting, libusb1.libusb_interface_descriptor):
1706 raise TypeError('Unexpected descriptor type.')
1707 self.__alt_setting = alt_setting
1708 self.__context = context
1709
1710 def getNumber(self):
1711 return self.__alt_setting.bInterfaceNumber
1712
1713 def getAlternateSetting(self):
1714 return self.__alt_setting.bAlternateSetting
1715
1716 def getNumEndpoints(self):
1717 return self.__alt_setting.bNumEndpoints
1718
1719 __len__ = getNumEndpoints
1720
1721 def getClass(self):
1722 return self.__alt_setting.bInterfaceClass
1723
1724 def getSubClass(self):
1725 return self.__alt_setting.bInterfaceSubClass
1726
1727 def getClassTuple(self):
1728 """
1729 For convenience: class and subclass are probably often matched
1730 simultaneously.
1731 """
1732 alt_setting = self.__alt_setting
1733 return (alt_setting.bInterfaceClass, alt_setting.bInterfaceSubClass)
1734
1735 # BBB
1736 getClassTupple = getClassTuple
1737
1738 def getProtocol(self):
1739 return self.__alt_setting.bInterfaceProtocol
1740
1741 def getDescriptor(self):
1742 return self.__alt_setting.iInterface
1743
1744 def getExtra(self):
1745 return libusb1.get_extra(self.__alt_setting)
1746
1747 def __iter__(self):
1748 """
1749 Iterates over endpoints in this interface setting , yielding
1750 USBEndpoint instances.
1751 """
1752 context = self.__context
1753 endpoint_list = self.__alt_setting.endpoint
1754 for endpoint_num in range(self.getNumEndpoints()):
1755 yield USBEndpoint(context, endpoint_list[endpoint_num])
1756
1757 # BBB
1758 iterEndpoints = __iter__
1759
1760 def __getitem__(self, endpoint):
1761 """
1762 Returns an USBEndpoint instance.
1763 """
1764 if not isinstance(endpoint, int):
1765 raise TypeError('endpoint parameter must be an integer')
1766 if not 0 <= endpoint < self.getNumEndpoints():
1767 raise ValueError(f'No such endpoint: {endpoint}')
1768 return USBEndpoint(
1769 self.__context, self.__alt_setting.endpoint[endpoint])
1770
1771 class USBEndpoint:
1772 def __init__(self, context, endpoint):
1773 if not isinstance(endpoint, libusb1.libusb_endpoint_descriptor):
1774 raise TypeError('Unexpected descriptor type.')
1775 self.__endpoint = endpoint
1776 # pylint: disable=unused-private-member
1777 self.__context = context
1778 # pylint: enable=unused-private-member
1779
1780 def getAddress(self):
1781 return self.__endpoint.bEndpointAddress
1782
1783 def getAttributes(self):
1784 return self.__endpoint.bmAttributes
1785
1786 def getMaxPacketSize(self):
1787 return self.__endpoint.wMaxPacketSize
1788
1789 def getInterval(self):
1790 return self.__endpoint.bInterval
1791
1792 def getRefresh(self):
1793 return self.__endpoint.bRefresh
1794
1795 def getSyncAddress(self):
1796 return self.__endpoint.bSynchAddress
1797
1798 def getExtra(self):
1799 return libusb1.get_extra(self.__endpoint)
1800
1801 class USBDevice(_LibUSB1Finalizer):
1802 """
1803 Represents a USB device.
1804
1805 Exposes USB descriptors which are available from OS without needing to get
1806 a USBDeviceHandle: device descriptor, configuration descriptors, interface
1807 descriptors, setting descritptors, endpoint descriptors.
1808 """
1809
1810 __configuration_descriptor_list = ()
1811 __device_handle = None
1812
1813 def __init__(
1814 self,
1815 context,
1816 device_p,
1817 getFinalizer,
1818 can_load_configuration,
1819 can_change_refcount,
1820 handle_p,
1821 ):
1822 """
1823 You should not instanciate this class directly.
1824 Call USBContext methods to receive instances of this class.
1825 """
1826 super().__init__()
1827 self.__context = context
1828 self.__configuration_descriptor_list = descriptor_list = []
1829 if can_change_refcount:
1830 libusb1.libusb_ref_device(device_p)
1831 self.close = getFinalizer(
1832 self,
1833 self.close, # Note: static method
1834 device_p=(
1835 device_p
1836 if can_change_refcount else
1837 None
1838 ),
1839 finalizer_dict=self._finalizer_dict,
1840 descriptor_list=descriptor_list,
1841 libusb_unref_device=libusb1.libusb_unref_device,
1842 libusb_free_config_descriptor=libusb1.libusb_free_config_descriptor,
1843 )
1844 self.device_p = device_p
1845 # Fetch device descriptor
1846 # Note: if this is made lazy, access errors will happen later, breaking
1847 # getDeviceIterator exception handling.
1848 device_descriptor = libusb1.libusb_device_descriptor()
1849 result = libusb1.libusb_get_device_descriptor(
1850 device_p, byref(device_descriptor))
1851 mayRaiseUSBError(result)
1852 self.device_descriptor = device_descriptor
1853 if can_load_configuration:
1854 append = descriptor_list.append
1855 for configuration_id in range(
1856 self.device_descriptor.bNumConfigurations):
1857 config = libusb1.libusb_config_descriptor_p()
1858 result = libusb1.libusb_get_config_descriptor(
1859 device_p, configuration_id, byref(config))
1860 # pylint: disable=undefined-variable
1861 if result == ERROR_NOT_FOUND:
1862 # pylint: enable=undefined-variable
1863 # Some devices (ex windows' root hubs) tell they have
1864 # one configuration, but they have no configuration
1865 # descriptor.
1866 continue
1867 mayRaiseUSBError(result)
1868 append(config.contents)
1869 self.__bus_number = libusb1.libusb_get_bus_number(device_p)
1870 self.__port_number = libusb1.libusb_get_port_number(device_p)
1871 self.__device_address = libusb1.libusb_get_device_address(device_p)
1872 if handle_p is not None:
1873 self.__device_handle = USBDeviceHandle(
1874 context=context,
1875 handle=handle_p,
1876 device=self,
1877 getFinalizer=self._getFinalizer,
1878 can_close_device=True,
1879 )
1880
1881 @staticmethod
1882 def close( # pylint: disable=method-hidden
1883 device_p,
1884 finalizer_dict,
1885 descriptor_list,
1886 libusb_unref_device,
1887 libusb_free_config_descriptor,
1888
1889 byref_=byref,
1890 ):
1891 while finalizer_dict:
1892 for handle, finalizer in list(finalizer_dict.items()):
1893 finalizer()
1894 assert handle not in finalizer_dict
1895 if device_p is not None:
1896 libusb_unref_device(device_p)
1897 while descriptor_list:
1898 libusb_free_config_descriptor(
1899 byref_(descriptor_list.pop()),
1900 )
1901
1902 def __str__(self):
1903 return (
1904 f'Bus {self.getBusNumber():03} '
1905 f'Device {self.getDeviceAddress():03}: '
1906 f'ID {self.getVendorID():04x}:{self.getProductID():04x}'
1907 )
1908
1909 def __len__(self):
1910 return len(self.__configuration_descriptor_list)
1911
1912 def __getitem__(self, index):
1913 return USBConfiguration(
1914 self.__context, self.__configuration_descriptor_list[index], self.getDeviceSpeed())
1915
1916 def __key(self):
1917 return (
1918 id(self.__context), self.__bus_number,
1919 self.__device_address, self.device_descriptor.idVendor,
1920 self.device_descriptor.idProduct,
1921 )
1922
1923 def __hash__(self):
1924 return hash(self.__key())
1925
1926 def __eq__(self, other):
1927 # pylint: disable=unidiomatic-typecheck
1928 return type(self) == type(other) and (
1929 # pylint: enable=unidiomatic-typecheck
1930 self.device_p == other.device_p or
1931 # pylint: disable=protected-access
1932 self.__key() == other.__key()
1933 # pylint: enable=protected-access
1934 )
1935
1936 def iterConfigurations(self):
1937 context = self.__context
1938 for config in self.__configuration_descriptor_list:
1939 yield USBConfiguration(context, config, self.getDeviceSpeed())
1940
1941 # BBB
1942 iterConfiguations = iterConfigurations
1943
1944 def iterSettings(self):
1945 for config in self.iterConfigurations():
1946 for interface in config:
1947 yield from interface
1948
1949 def getBusNumber(self):
1950 """
1951 Get device's bus number.
1952 """
1953 return self.__bus_number
1954
1955 def getPortNumber(self):
1956 """
1957 Get device's port number.
1958 """
1959 return self.__port_number
1960
1961 def getPortNumberList(self):
1962 """
1963 Get the port number of each hub toward device.
1964 """
1965 port_list = (c_uint8 * PATH_MAX_DEPTH)()
1966 result = libusb1.libusb_get_port_numbers(
1967 self.device_p, port_list, len(port_list))
1968 mayRaiseUSBError(result)
1969 return list(port_list[:result])
1970
1971 # TODO: wrap libusb_get_parent when/if libusb removes the need to be inside
1972 # a libusb_(get|free)_device_list block.
1973
1974 def getDeviceAddress(self):
1975 """
1976 Get device's address on its bus.
1977 """
1978 return self.__device_address
1979
1980 def getbcdUSB(self):
1981 """
1982 Get the USB spec version device complies to, in BCD format.
1983 """
1984 return self.device_descriptor.bcdUSB
1985
1986 def getDeviceClass(self):
1987 """
1988 Get device's class id.
1989 """
1990 return self.device_descriptor.bDeviceClass
1991
1992 def getDeviceSubClass(self):
1993 """
1994 Get device's subclass id.
1995 """
1996 return self.device_descriptor.bDeviceSubClass
1997
1998 def getDeviceProtocol(self):
1999 """
2000 Get device's protocol id.
2001 """
2002 return self.device_descriptor.bDeviceProtocol
2003
2004 def getMaxPacketSize0(self):
2005 """
2006 Get device's max packet size for endpoint 0 (control).
2007 """
2008 return self.device_descriptor.bMaxPacketSize0
2009
2010 def getMaxPacketSize(self, endpoint):
2011 """
2012 Get device's max packet size for given endpoint.
2013
2014 Warning: this function will not always give you the expected result.
2015 See https://libusb.org/ticket/77 . You should instead consult the
2016 endpoint descriptor of current configuration and alternate setting.
2017 """
2018 result = libusb1.libusb_get_max_packet_size(self.device_p, endpoint)
2019 mayRaiseUSBError(result)
2020 return result
2021
2022 def getMaxISOPacketSize(self, endpoint):
2023 """
2024 Get the maximum size for a single isochronous packet for given
2025 endpoint.
2026
2027 Warning: this function will not always give you the expected result.
2028 See https://libusb.org/ticket/77 . You should instead consult the
2029 endpoint descriptor of current configuration and alternate setting.
2030 """
2031 result = libusb1.libusb_get_max_iso_packet_size(self.device_p, endpoint)
2032 mayRaiseUSBError(result)
2033 return result
2034
2035 def getVendorID(self):
2036 """
2037 Get device's vendor id.
2038 """
2039 return self.device_descriptor.idVendor
2040
2041 def getProductID(self):
2042 """
2043 Get device's product id.
2044 """
2045 return self.device_descriptor.idProduct
2046
2047 def getbcdDevice(self):
2048 """
2049 Get device's release number.
2050 """
2051 return self.device_descriptor.bcdDevice
2052
2053 def getSupportedLanguageList(self):
2054 """
2055 Get the list of language ids device has string descriptors for.
2056 Note: opens the device temporarily and uses synchronous API.
2057 """
2058 return self.open().getSupportedLanguageList()
2059
2060 def getManufacturer(self):
2061 """
2062 Get device's manufaturer name.
2063
2064 Shortcut for .open().getManufacturer() .
2065 """
2066 return self.open().getManufacturer()
2067
2068 def getManufacturerDescriptor(self):
2069 """
2070 Get the string index of device's manufacturer.
2071 You can pass this value to USBHandle.getASCIIStringDescriptor to get
2072 the actual manufacturer string.
2073 """
2074 return self.device_descriptor.iManufacturer
2075
2076 def getProduct(self):
2077 """
2078 Get device's product name.
2079
2080 Shortcut for .open().getProduct() .
2081 """
2082 return self.open().getProduct()
2083
2084 def getProductDescriptor(self):
2085 """
2086 Get the string index of device's product name.
2087 You can pass this value to USBHandle.getASCIIStringDescriptor to get
2088 the actual product name string.
2089 """
2090 return self.device_descriptor.iProduct
2091
2092 def getSerialNumber(self):
2093 """
2094 Get device's serial number.
2095
2096 Shortcut for .open().getSerialNumber() .
2097 """
2098 return self.open().getSerialNumber()
2099
2100 def getSerialNumberDescriptor(self):
2101 """
2102 Get the string index of device's serial number.
2103 You can pass this value to USBHandle.getASCIIStringDescriptor to get
2104 the actual serial number string.
2105 """
2106 return self.device_descriptor.iSerialNumber
2107
2108 def getNumConfigurations(self):
2109 """
2110 Get device's number of possible configurations.
2111 """
2112 return self.device_descriptor.bNumConfigurations
2113
2114 def getDeviceSpeed(self):
2115 """
2116 Get device's speed.
2117
2118 Returns one of:
2119 SPEED_UNKNOWN
2120 SPEED_LOW
2121 SPEED_FULL
2122 SPEED_HIGH
2123 SPEED_SUPER
2124 SPEED_SUPER_PLUS
2125 """
2126 return libusb1.libusb_get_device_speed(self.device_p)
2127
2128 def open(self):
2129 """
2130 Open device.
2131 Returns an USBDeviceHandle instance.
2132 """
2133 if self.__device_handle is not None:
2134 return self.__device_handle
2135 handle = libusb1.libusb_device_handle_p()
2136 mayRaiseUSBError(libusb1.libusb_open(self.device_p, byref(handle)))
2137 return USBDeviceHandle(
2138 context=self.__context,
2139 handle=handle,
2140 device=self,
2141 getFinalizer=self._getFinalizer,
2142 can_close_device=False,
2143 )
2144
2145 _zero_tv = libusb1.timeval(0, 0)
2146 _zero_tv_p = byref(_zero_tv)
2147 _null_pointer = c_void_p()
2148 _NULL_LOG_CALLBACK = libusb1.libusb_log_cb_p(0)
2149
2150 class USBContext(_LibUSB1Finalizer):
2151 """
2152 libusb1 USB context.
2153
2154 Provides methods to enumerate & look up USB devices.
2155 Also provides access to global (device-independent) libusb1 functions.
2156 """
2157 __context_p = None
2158 __added_cb = None
2159 __removed_cb = None
2160 __poll_cb_user_data = None
2161 __auto_open = True
2162 __has_pollfd_finalizer = False
2163 __mayRaiseUSBError = staticmethod(mayRaiseUSBError)
2164 __libusb_handle_events = None
2165
2166 # pylint: disable=no-self-argument,protected-access
2167 def _validContext(func):
2168 # Defined inside USBContext so we can access "self.__*".
2169 @contextlib.contextmanager
2170 def refcount(self):
2171 with self.__context_cond:
2172 if not self.__context_p and self.__auto_open:
2173 # BBB
2174 warnings.warn(
2175 'Use "with USBContext() as context:" for safer cleanup'
2176 ' on interpreter shutdown. See also USBContext.open().',
2177 DeprecationWarning,
2178 stacklevel=4
2179 )
2180 self.open()
2181 self.__context_refcount += 1
2182 try:
2183 yield
2184 finally:
2185 with self.__context_cond:
2186 self.__context_refcount -= 1
2187 if not self.__context_refcount:
2188 self.__context_cond.notify_all()
2189 if inspect.isgeneratorfunction(func):
2190 def wrapper(self, *args, **kw):
2191 with refcount(self):
2192 if self.__context_p:
2193 # pylint: disable=not-callable
2194 generator = func(self, *args, **kw)
2195 # pylint: enable=not-callable
2196 try:
2197 yield from generator
2198 finally:
2199 generator.close()
2200 else:
2201 def wrapper(self, *args, **kw):
2202 with refcount(self):
2203 if self.__context_p:
2204 # pylint: disable=not-callable
2205 return func(self, *args, **kw)
2206 # pylint: enable=not-callable
2207 return None
2208 functools.update_wrapper(wrapper, func)
2209 return wrapper
2210 # pylint: enable=no-self-argument,protected-access
2211
2212 def __init__(
2213 self,
2214 log_level=None,
2215 use_usbdk=False,
2216 with_device_discovery=True,
2217 log_callback=None,
2218 ):
2219 """
2220 Create a new USB context.
2221
2222 log_level (LOG_LEVEL_*)
2223 Sets the context's log level as soon as it is created.
2224 Maybe have no effect depending on libusb's build options.
2225 use_usbdk (bool)
2226 Windows only.
2227 Whether to use the UsbDk backend if available.
2228 with_device_discovery (bool)
2229 Linux only.
2230 Disables device scan while initialising the library.
2231 This has knowck-on effects on how devices may be opened and how
2232 descriptors are accessed. For more details, see libusb1's
2233 documentation.
2234 log_callback ((int, bytes): None)
2235 Context's log callback function.
2236
2237 Note: providing non-default values may cause context creation (during
2238 __enter__, open, or the first context-dependent call, whichever happens
2239 first) to fail if libusb is older than v1.0.27 .
2240 """
2241 super().__init__()
2242 # Used to prevent an exit to cause a segfault if a concurrent thread
2243 # is still in libusb.
2244 self.__context_refcount = 0
2245 self.__context_cond = threading.Condition()
2246 self.__context_p = libusb1.libusb_context_p()
2247 assert not self.__context_p
2248 self.__hotplug_callback_dict = {}
2249 self.__log_level = log_level
2250 self.__use_usbdk = use_usbdk
2251 self.__with_device_discovery = with_device_discovery
2252 self.__user_log_callback = log_callback
2253 self.__log_callback_p = libusb1.libusb_log_cb_p(self.__log_callback)
2254
2255 def __enter__(self):
2256 return self.open()
2257
2258 def __exit__(self, exc_type, exc_val, exc_tb):
2259 self.close()
2260
2261 def open(self):
2262 """
2263 Finish context initialisation, as is normally done in __enter__ .
2264
2265 This happens automatically on the first method call needing access to
2266 the uninitialised properties, but with a warning.
2267 Call this method ONLY if your usage pattern prevents you from using the
2268 with USBContext() as context:
2269 form: this means there are ways to avoid calling close(), which can
2270 cause issues particularly hard to debug (ex: interpreter hangs on
2271 exit).
2272
2273 Calls loadLibrary.
2274 """
2275 assert self.__context_refcount == 0
2276 assert not self.__context_p
2277 loadLibrary()
2278 self.__libusb_handle_events = libusb1.libusb_handle_events
2279 option_array = (
2280 libusb1.libusb_init_option * libusb1.LIBUSB_OPTION_MAX
2281 )()
2282 option_count = 0
2283 if self.__log_level is not None:
2284 option = option_array[option_count]
2285 option_count += 1
2286 option.option = libusb1.LIBUSB_OPTION_LOG_LEVEL
2287 option.value.ival = self.__log_level
2288 if self.__use_usbdk:
2289 option = option_array[option_count]
2290 option_count += 1
2291 option.option = libusb1.LIBUSB_OPTION_USE_USBDK
2292 option.value.ival = 1
2293 if not self.__with_device_discovery:
2294 option = option_array[option_count]
2295 option_count += 1
2296 option.option = libusb1.LIBUSB_OPTION_NO_DEVICE_DISCOVERY
2297 option.value.ival = 1
2298 if self.__user_log_callback is not None:
2299 option = option_array[option_count]
2300 option_count += 1
2301 option.option = libusb1.LIBUSB_OPTION_LOG_CB
2302 option.value.log_cbval = self.__log_callback_p
2303 mayRaiseUSBError(libusb1.libusb_init_context(
2304 byref(self.__context_p),
2305 option_array,
2306 option_count,
2307 ))
2308 self.__close = weakref.finalize(
2309 self,
2310 self.___close, # Note: static method
2311 context_p=self.__context_p,
2312 hotplug_callback_dict=self.__hotplug_callback_dict,
2313 finalizer_dict=self._finalizer_dict,
2314 libusb_exit=libusb1.libusb_exit,
2315 libusb_hotplug_deregister_callback=libusb1.libusb_hotplug_deregister_callback,
2316 )
2317 return self
2318
2319 def close(self):
2320 """
2321 Close (destroy) this USB context, and all related instances.
2322
2323 When this method has been called, methods on its instance will
2324 become mosty no-ops, returning None until explicitly re-opened
2325 (by calling open() or __enter__()).
2326
2327 Note: "exit" is a deprecated alias of "close".
2328 """
2329 self.__auto_open = False
2330 self.__context_cond.acquire()
2331 try:
2332 while self.__context_refcount and self.__context_p:
2333 self.__context_cond.wait()
2334 self.__close()
2335 # pylint: disable=unused-private-member
2336 self.__added_cb = None
2337 self.__removed_cb = None
2338 self.__poll_cb_user_data = None
2339 # pylint: enable=unused-private-member
2340 finally:
2341 self.__context_cond.notify_all()
2342 self.__context_cond.release()
2343
2344 # BBB
2345 exit = close
2346
2347 @staticmethod
2348 def __close(): # pylint: disable=method-hidden
2349 # Placeholder, masked on open()
2350 pass
2351
2352 @staticmethod
2353 def ___close( # pylint: disable=method-hidden
2354 context_p,
2355 hotplug_callback_dict,
2356 finalizer_dict,
2357 libusb_exit,
2358 libusb_hotplug_deregister_callback,
2359 ):
2360 while hotplug_callback_dict:
2361 # Duplicates hotplugDeregisterCallback logic, to avoid finalizer
2362 # referencing its own instance.
2363 handle, _ = hotplug_callback_dict.popitem()
2364 libusb_hotplug_deregister_callback(context_p, handle)
2365 while finalizer_dict:
2366 for handle, finalizer in list(finalizer_dict.items()):
2367 finalizer()
2368 assert handle not in finalizer_dict
2369 libusb_exit(context_p)
2370 context_p.value = None
2371
2372 @_validContext
2373 def getDeviceIterator(self, skip_on_error=False):
2374 """
2375 Return an iterator over all USB devices currently plugged in, as USBDevice
2376 instances.
2377
2378 skip_on_error (bool)
2379 If True, ignore devices which raise USBError.
2380 """
2381 libusb_free_device_list = libusb1.libusb_free_device_list
2382 device_p_p = libusb1.libusb_device_p_p()
2383 device_list_len = libusb1.libusb_get_device_list(self.__context_p,
2384 byref(device_p_p))
2385 mayRaiseUSBError(device_list_len)
2386 try:
2387 for device_p in device_p_p[:device_list_len]:
2388 try:
2389 device = USBDevice(
2390 context=self,
2391 device_p=device_p,
2392 getFinalizer=self._getFinalizer,
2393 can_load_configuration=True,
2394 can_change_refcount=True,
2395 handle_p=None,
2396 )
2397 except USBError:
2398 if not skip_on_error:
2399 raise
2400 else:
2401 yield device
2402 finally:
2403 libusb_free_device_list(device_p_p, 1)
2404
2405 def getDeviceList(self, skip_on_access_error=False, skip_on_error=False):
2406 """
2407 Return a list of all USB devices currently plugged in, as USBDevice
2408 instances.
2409
2410 skip_on_error (bool)
2411 If True, ignore devices which raise USBError.
2412
2413 skip_on_access_error (bool)
2414 DEPRECATED. Alias for skip_on_error.
2415 """
2416 return list(
2417 self.getDeviceIterator(
2418 skip_on_error=skip_on_access_error or skip_on_error,
2419 ),
2420 )
2421
2422 def getByVendorIDAndProductID(
2423 self, vendor_id, product_id,
2424 skip_on_access_error=False, skip_on_error=False):
2425 """
2426 Get the first USB device matching given vendor and product ids.
2427 Returns an USBDevice instance, or None if no present device match.
2428 skip_on_error (bool)
2429 (see getDeviceList)
2430 skip_on_access_error (bool)
2431 (see getDeviceList)
2432 """
2433 device_iterator = self.getDeviceIterator(
2434 skip_on_error=skip_on_access_error or skip_on_error,
2435 )
2436 try:
2437 for device in device_iterator:
2438 if device.getVendorID() == vendor_id and \
2439 device.getProductID() == product_id:
2440 return device
2441 device.close()
2442 finally:
2443 device_iterator.close()
2444 return None
2445
2446 def openByVendorIDAndProductID(
2447 self, vendor_id, product_id,
2448 skip_on_access_error=False, skip_on_error=False):
2449 """
2450 Get the first USB device matching given vendor and product ids.
2451 Returns an USBDeviceHandle instance, or None if no present device
2452 match.
2453 skip_on_error (bool)
2454 (see getDeviceList)
2455 skip_on_access_error (bool)
2456 (see getDeviceList)
2457 """
2458 result = self.getByVendorIDAndProductID(
2459 vendor_id, product_id,
2460 skip_on_access_error=skip_on_access_error,
2461 skip_on_error=skip_on_error)
2462 if result is not None:
2463 return result.open()
2464 return None
2465
2466 @_validContext
2467 def wrapSysDevice(self, sys_device):
2468 """
2469 Wrap sys_device to obtain a USBDeviceHandle instance.
2470
2471 sys_device (file, int):
2472 File or file descriptor of the sys device node to wrap.
2473 You must keep this file open while the device is,
2474 and are expected to close it any time after it is closed.
2475
2476 You may get a USBDevice instance by calling getDevice on the returned
2477 value, but note that this device will be closed once the handle is.
2478 """
2479 if not isinstance(sys_device, int):
2480 sys_device = sys_device.fileno()
2481 handle_p = libusb1.libusb_device_handle_p()
2482 mayRaiseUSBError(
2483 libusb1.libusb_wrap_sys_device(
2484 self.__context_p,
2485 sys_device,
2486 byref(handle_p),
2487 )
2488 )
2489 return USBDevice(
2490 context=self,
2491 device_p=libusb1.libusb_get_device(handle_p),
2492 getFinalizer=self._getFinalizer,
2493 can_load_configuration=True, # XXX: give the caller control ?
2494 can_change_refcount=False,
2495 handle_p=handle_p,
2496 ).open()
2497
2498 @_validContext
2499 def getPollFDList(self):
2500 """
2501 Return file descriptors to be used to poll USB events.
2502 You should not have to call this method, unless you are integrating
2503 this class with a polling mechanism.
2504 """
2505 pollfd_p_p = libusb1.libusb_get_pollfds(self.__context_p)
2506 if not pollfd_p_p:
2507 errno = get_errno()
2508 if errno:
2509 raise OSError(errno)
2510 # Assume not implemented
2511 raise NotImplementedError(
2512 'Your libusb does not seem to implement pollable FDs')
2513 try:
2514 result = []
2515 append = result.append
2516 fd_index = 0
2517 while pollfd_p_p[fd_index]:
2518 append((
2519 pollfd_p_p[fd_index].contents.fd,
2520 pollfd_p_p[fd_index].contents.events,
2521 ))
2522 fd_index += 1
2523 finally:
2524 libusb1.libusb_free_pollfds(pollfd_p_p)
2525 return result
2526
2527 @_validContext
2528 def handleEvents(self):
2529 """
2530 Handle any pending event (blocking).
2531 See libusb1 documentation for details (there is a timeout, so it's
2532 not "really" blocking).
2533 """
2534 self.__mayRaiseUSBError(
2535 self.__libusb_handle_events(self.__context_p),
2536 )
2537
2538 # TODO: handleEventsCompleted
2539
2540 @_validContext
2541 def handleEventsTimeout(self, tv=0):
2542 """
2543 Handle any pending event.
2544 If tv is 0, will return immediately after handling already-pending
2545 events.
2546 Otherwise, defines the maximum amount of time to wait for events, in
2547 seconds.
2548 """
2549 if tv is None:
2550 tv = 0
2551 tv_s = int(tv)
2552 real_tv = libusb1.timeval(tv_s, int((tv - tv_s) * 1000000))
2553 mayRaiseUSBError(
2554 libusb1.libusb_handle_events_timeout(
2555 self.__context_p, byref(real_tv),
2556 ),
2557 )
2558
2559 # TODO: handleEventsTimeoutCompleted
2560
2561 @_validContext
2562 def interruptEventHandler(self):
2563 """
2564 Interrupt any active thread that is handling events.
2565 This is mainly useful for interrupting a dedicated event handling thread
2566 when the application wishes to exit.
2567 """
2568 libusb1.libusb_interrupt_event_handler(self.__context_p)
2569
2570 @_validContext
2571 def setPollFDNotifiers(
2572 self, added_cb=None, removed_cb=None, user_data=None):
2573 """
2574 Give libusb1 methods to call when it should add/remove file descriptor
2575 for polling.
2576 You should not have to call this method, unless you are integrating
2577 this class with a polling mechanism.
2578 """
2579 if added_cb is None:
2580 added_cb = _null_pointer
2581 else:
2582 added_cb = libusb1.libusb_pollfd_added_cb_p(added_cb)
2583 if removed_cb is None:
2584 removed_cb = _null_pointer
2585 else:
2586 removed_cb = libusb1.libusb_pollfd_removed_cb_p(removed_cb)
2587 if user_data is None:
2588 user_data = _null_pointer
2589 # pylint: disable=unused-private-member
2590 self.__added_cb = added_cb
2591 self.__removed_cb = removed_cb
2592 self.__poll_cb_user_data = user_data
2593 # pylint: enable=unused-private-member
2594 libusb1.libusb_set_pollfd_notifiers(
2595 self.__context_p,
2596 cast(added_cb, libusb1.libusb_pollfd_added_cb_p),
2597 cast(removed_cb, libusb1.libusb_pollfd_removed_cb_p),
2598 user_data,
2599 )
2600 if not self.__has_pollfd_finalizer:
2601 # Note: the above condition is just to avoid creating finalizers on
2602 # every call. If more than one is created (because of a
2603 # race-condition) it is not a big deal, as __finalizePollFDNotifiers
2604 # will do the right thing even if called multiple times in a row.
2605 self.__has_pollfd_finalizer = True
2606 self._getFinalizer(
2607 self,
2608 self.__finalizePollFDNotifiers, # Note: staticmethod
2609 context_p=self.__context_p,
2610 libusb_set_pollfd_notifiers=libusb1.libusb_set_pollfd_notifiers,
2611 )
2612
2613 @staticmethod
2614 def __finalizePollFDNotifiers(
2615 context_p,
2616 libusb_set_pollfd_notifiers,
2617
2618 null_pointer=_null_pointer,
2619 added_cb_p=cast(_null_pointer, libusb1.libusb_pollfd_added_cb_p),
2620 removed_cb_p=cast(_null_pointer, libusb1.libusb_pollfd_removed_cb_p),
2621 ):
2622 libusb_set_pollfd_notifiers(
2623 context_p,
2624 added_cb_p,
2625 removed_cb_p,
2626 null_pointer,
2627 )
2628
2629 @_validContext
2630 def getNextTimeout(self):
2631 """
2632 Returns the next internal timeout that libusb needs to handle, in
2633 seconds, or None if no timeout is needed.
2634 You should not have to call this method, unless you are integrating
2635 this class with a polling mechanism.
2636 """
2637 timeval = libusb1.timeval()
2638 result = libusb1.libusb_get_next_timeout(
2639 self.__context_p, byref(timeval))
2640 if result == 0:
2641 return None
2642 if result == 1:
2643 return timeval.tv_sec + (timeval.tv_usec * 0.000001)
2644 raiseUSBError(result)
2645 return None # unreachable, to make pylint happy
2646
2647 @_validContext
2648 def setDebug(self, level):
2649 """
2650 Set debugging level. See LOG_LEVEL_* constants.
2651 Note: depending on libusb compilation settings, this might have no
2652 effect.
2653 """
2654 libusb1.libusb_set_debug(self.__context_p, level)
2655
2656 @_validContext
2657 def tryLockEvents(self):
2658 warnings.warn(
2659 'You may not be able to unlock in the event of USBContext exit. '
2660 'Consider looping over handleEvents() in a thread.',
2661 DeprecationWarning,
2662 )
2663 return libusb1.libusb_try_lock_events(self.__context_p)
2664
2665 @_validContext
2666 def lockEvents(self):
2667 warnings.warn(
2668 'You may not be able to unlock in the event of USBContext exit. '
2669 'Consider looping over handleEvents() in a thread.',
2670 DeprecationWarning,
2671 )
2672 libusb1.libusb_lock_events(self.__context_p)
2673
2674 @_validContext
2675 def lockEventWaiters(self):
2676 warnings.warn(
2677 'You may not be able to unlock in the event of USBContext exit. '
2678 'Consider looping over handleEvents() in a thread.',
2679 DeprecationWarning,
2680 )
2681 libusb1.libusb_lock_event_waiters(self.__context_p)
2682
2683 @_validContext
2684 def waitForEvent(self, tv=0):
2685 warnings.warn(
2686 'Consider looping over handleEvents() in a thread.',
2687 DeprecationWarning,
2688 )
2689 if tv is None:
2690 tv = 0
2691 tv_s = int(tv)
2692 real_tv = libusb1.timeval(tv_s, int((tv - tv_s) * 1000000))
2693 libusb1.libusb_wait_for_event(self.__context_p, byref(real_tv))
2694
2695 @_validContext
2696 def unlockEventWaiters(self):
2697 warnings.warn(
2698 'This method will lock in the event of USBContext exit, '
2699 'preventing libusb lock release. '
2700 'Consider looping over handleEvents() in a thread.',
2701 DeprecationWarning,
2702 )
2703 libusb1.libusb_unlock_event_waiters(self.__context_p)
2704
2705 @_validContext
2706 def eventHandlingOK(self):
2707 warnings.warn(
2708 'Consider looping over handleEvents() in a thread.',
2709 DeprecationWarning,
2710 )
2711 return libusb1.libusb_event_handling_ok(self.__context_p)
2712
2713 @_validContext
2714 def unlockEvents(self):
2715 warnings.warn(
2716 'This method will lock in the event of USBContext exit, '
2717 'preventing libusb lock release. '
2718 'Consider looping over handleEvents() in a thread.',
2719 DeprecationWarning,
2720 )
2721 libusb1.libusb_unlock_events(self.__context_p)
2722
2723 @_validContext
2724 def handleEventsLocked(self):
2725 warnings.warn(
2726 'Consider looping over handleEvents() in a thread.',
2727 DeprecationWarning,
2728 )
2729 # XXX: does tv parameter need to be exposed ?
2730 mayRaiseUSBError(libusb1.libusb_handle_events_locked(
2731 self.__context_p, _zero_tv_p,
2732 ))
2733
2734 @_validContext
2735 def eventHandlerActive(self):
2736 warnings.warn(
2737 'Consider looping over handleEvents() in a thread.',
2738 DeprecationWarning,
2739 )
2740 return libusb1.libusb_event_handler_active(self.__context_p)
2741
2742 @staticmethod
2743 def hasCapability(capability):
2744 """
2745 Backward-compatibility alias for module-level hasCapability.
2746 """
2747 return hasCapability(capability)
2748
2749 @_validContext
2750 def hotplugRegisterCallback(
2751 self, callback,
2752 # pylint: disable=undefined-variable
2753 events=HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT,
2754 flags=HOTPLUG_ENUMERATE,
2755 vendor_id=HOTPLUG_MATCH_ANY,
2756 product_id=HOTPLUG_MATCH_ANY,
2757 dev_class=HOTPLUG_MATCH_ANY,
2758 # pylint: enable=undefined-variable
2759 ):
2760 """
2761 Registers an hotplug callback.
2762 On success, returns an opaque value which can be passed to
2763 hotplugDeregisterCallback.
2764 Callback must accept the following positional arguments:
2765 - this USBContext instance
2766 - an USBDevice instance
2767 If device has left, configuration descriptors may not be
2768 available. Its device descriptor will be available.
2769 - event type, one of:
2770 HOTPLUG_EVENT_DEVICE_ARRIVED
2771 HOTPLUG_EVENT_DEVICE_LEFT
2772 Callback must return whether it must be unregistered (any true value
2773 to be unregistered, any false value to be kept registered).
2774
2775 Note: given callback will be invoked during event handling, meaning
2776 it cannot call any synchronous libusb function.
2777 """
2778 def wrapped_callback(context_p, device_p, event, _):
2779 assert context_p == self.__context_p.value, (
2780 context_p, self.__context_p,
2781 )
2782 device = USBDevice(
2783 context=self,
2784 device_p=device_p,
2785 getFinalizer=self._getFinalizer,
2786 # pylint: disable=undefined-variable
2787 can_load_configuration=event != HOTPLUG_EVENT_DEVICE_LEFT,
2788 # pylint: enable=undefined-variable
2789 can_change_refcount=True,
2790 handle_p=None,
2791 )
2792 unregister = bool(callback(
2793 self,
2794 device,
2795 event,
2796 ))
2797 if unregister:
2798 del self.__hotplug_callback_dict[handle]
2799 return unregister
2800 handle = c_int()
2801 callback_p = libusb1.libusb_hotplug_callback_fn_p(wrapped_callback)
2802 mayRaiseUSBError(libusb1.libusb_hotplug_register_callback(
2803 self.__context_p, events, flags, vendor_id, product_id, dev_class,
2804 callback_p, None, byref(handle),
2805 ))
2806 handle = handle.value
2807 # Keep strong references
2808 assert handle not in self.__hotplug_callback_dict, (
2809 handle,
2810 self.__hotplug_callback_dict,
2811 )
2812 self.__hotplug_callback_dict[handle] = (callback_p, wrapped_callback)
2813 return handle
2814
2815 @_validContext
2816 def hotplugDeregisterCallback(self, handle):
2817 """
2818 Deregisters an hotplug callback.
2819 handle (opaque)
2820 Return value of a former hotplugRegisterCallback call.
2821 """
2822 del self.__hotplug_callback_dict[handle]
2823 libusb1.libusb_hotplug_deregister_callback(self.__context_p, handle)
2824
2825 def __log_callback(self, _unused_context_p, level, value):
2826 """
2827 Internal log callback function, calls into the user-provided function
2828 if any.
2829 """
2830 # Note: as of libusb1, context_p is de facto guaranteed to be us:
2831 # ctx->log_handler(ctx, level, buf);
2832 # so do not bother checking.
2833 user_log_callback = self.__user_log_callback
2834 if user_log_callback is not None:
2835 user_log_callback(self, level, value)
2836
2837 @_validContext
2838 def setLogCallback(self, log_callback):
2839 """
2840 Change the active log callback for this context.
2841
2842 log_callback (None, (USBContext, int, bytes): None)
2843 The function called when libusb emits log messages for the current
2844 context.
2845 None to disable the callback.
2846 """
2847 user_log_callback_was_unset = self.__user_log_callback is None
2848 self.__user_log_callback = log_callback
2849 if user_log_callback_was_unset != (log_callback is None):
2850 libusb1.libusb_set_log_cb(
2851 self.__context_p,
2852 (
2853 _NULL_LOG_CALLBACK
2854 if log_callback is None else
2855 self.__log_callback_p
2856 ),
2857 libusb1.LIBUSB_LOG_CB_CONTEXT,
2858 )
2859
2860 del USBContext._validContext
2861
2862 def getVersion():
2863 """
2864 Returns underlying libusb's version information as a 6-namedtuple (or
2865 6-tuple if namedtuples are not avaiable):
2866 - major
2867 - minor
2868 - micro
2869 - nano
2870 - rc
2871 - describe
2872 Returns (0, 0, 0, 0, '', '') if libusb doesn't have required entry point.
2873
2874 Calls loadLibrary.
2875 """
2876 loadLibrary()
2877 version = libusb1.libusb_get_version().contents
2878 return Version(
2879 version.major,
2880 version.minor,
2881 version.micro,
2882 version.nano,
2883 version.rc,
2884 version.describe,
2885 )
2886
2887 def hasCapability(capability):
2888 """
2889 Tests feature presence.
2890
2891 capability should be one of:
2892 CAP_HAS_CAPABILITY
2893 CAP_HAS_HOTPLUG
2894 CAP_HAS_HID_ACCESS
2895 CAP_SUPPORTS_DETACH_KERNEL_DRIVER
2896
2897 Calls loadLibrary.
2898 """
2899 loadLibrary()
2900 return libusb1.libusb_has_capability(capability)
2901
2902 class __GlobalLogCallback: # pylint: disable=too-few-public-methods
2903 """
2904 Singleton class keeping a reference to the global log callback function
2905 so it is unregistered from libusb before the module gets garbage-collected.
2906 """
2907 __user_log_callback = None
2908 __finalizer = None
2909
2910 def __init__(self):
2911 self.__log_callback_p = libusb1.libusb_log_cb_p(self.__log_callback)
2912
2913 @staticmethod
2914 def __close(
2915 libusb_set_log_cb,
2916 LIBUSB_LOG_CB_GLOBAL,
2917 ):
2918 libusb_set_log_cb(None, _NULL_LOG_CALLBACK, LIBUSB_LOG_CB_GLOBAL)
2919
2920 def __log_callback(self, context_p, level, message):
2921 # As of at least libusb1, context_p of the global log callback
2922 # is always NULL, even when the event originated from a context.
2923 # So just ignore it here, forcing it to None.
2924 # Should it change later, then some USBContext lookup will be
2925 # needed.
2926 _ = context_p
2927 user_log_callback = self.__user_log_callback
2928 if user_log_callback is not None:
2929 user_log_callback(None, level, message)
2930
2931 def __call__(self, log_callback):
2932 """
2933 Set the global log callback.
2934
2935 log_callback (None, (None, int, bytes): None)
2936 A callable to set as libusb global log callback, or None to disable
2937 this feature.
2938 The first argument should be ignored.
2939 The second argument is the message level.
2940 The third argument is the message itself, as bytes.
2941
2942 Calls loadLibrary.
2943 libusb_set_log_cb will be called once more during module teardown.
2944 """
2945 if self.__finalizer is None:
2946 # Lazy initialisation, so loadLibrary is not called at
2947 # module load time.
2948 loadLibrary()
2949 self.__finalizer = weakref.finalize(
2950 self,
2951 self.__close, # Note: static method
2952 libusb_set_log_cb=libusb1.libusb_set_log_cb,
2953 LIBUSB_LOG_CB_GLOBAL=libusb1.LIBUSB_LOG_CB_GLOBAL,
2954 )
2955 user_log_callback_was_unset = self.__user_log_callback is None
2956 self.__user_log_callback = log_callback
2957 if user_log_callback_was_unset != (log_callback is None):
2958 libusb1.libusb_set_log_cb(
2959 None,
2960 (
2961 _NULL_LOG_CALLBACK
2962 if log_callback is None else
2963 self.__log_callback_p
2964 ),
2965 libusb1.LIBUSB_LOG_CB_GLOBAL,
2966 )
2967 setLogCallback = __GlobalLogCallback().__call__
2968
2969 def setLocale(locale):
2970 """
2971 Set locale used for translatable libusb1 messages.
2972
2973 locale (str)
2974 2 letter ISO 639-1 code, optionally followed by region and codeset.
2975
2976 Calls loadLibrary.
2977 """
2978 loadLibrary()
2979 mayRaiseUSBError(
2980 libusb1.libusb_setlocale(locale.encode('ascii'))
2981 )
2982
2983 class LibUSBContext(USBContext):
2984 """
2985 Backward-compatibility alias for USBContext.
2986 """
2987 def __init__(self):
2988 warnings.warn(
2989 'LibUSBContext is being renamed to USBContext',
2990 DeprecationWarning,
2991 )
2992 super().__init__()
2993
2994 loadLibrary = libusb1.loadLibrary