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