forked from pyusb/pyusb
/
core.py
1191 lines (988 loc) · 42.9 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2009-2014 Wander Lairson Costa
#
# The following terms apply to all files associated
# with the software unless explicitly disclaimed in individual files.
#
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors
# and need not follow the licensing terms described here, provided that
# the new terms are clearly indicated on the first page of each file where
# they apply.
#
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
# FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
# ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
# DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
# MODIFICATIONS.
r"""usb.core - Core USB features.
This module exports:
Device - a class representing a USB device.
Configuration - a class representing a configuration descriptor.
Interface - a class representing an interface descriptor.
Endpoint - a class representing an endpoint descriptor.
find() - a function to find USB devices.
"""
__author__ = 'Wander Lairson Costa'
__all__ = [ 'Device', 'Configuration', 'Interface', 'Endpoint', 'find',
'show_devices' ]
import usb.util as util
import copy
import operator
import usb._interop as _interop
import usb._lookup as _lu
import logging
import array
_logger = logging.getLogger('usb.core')
_DEFAULT_TIMEOUT = 1000
def _set_attr(input, output, fields):
for f in fields:
setattr(output, f, getattr(input, f))
def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
""" try to get a string, but return a string no matter what
"""
if index == 0 :
string = default_str_i0
else:
try:
if langid is None:
string = util.get_string(dev, index)
else:
string = util.get_string(dev, index, langid)
except :
string = default_access_error
return string
def _try_lookup(table, value, default = ""):
""" try to get a string from the lookup table, return "" instead of key
error
"""
try:
string = table[ value ]
except KeyError:
string = default
return string
class _DescriptorInfo(str):
""" this class is used so that when a descriptor is shown on the
terminal it is propely formatted """
def __repr__(self):
return self
class _ResourceManager(object):
def __init__(self, dev, backend):
self.backend = backend
self._active_cfg_index = None
self.dev = dev
self.handle = None
self._claimed_intf = _interop._set()
self._ep_info = {}
def managed_open(self):
if self.handle is None:
self.handle = self.backend.open_device(self.dev)
return self.handle
def managed_close(self):
if self.handle is not None:
self.backend.close_device(self.handle)
self.handle = None
def managed_set_configuration(self, device, config):
if config is None:
cfg = device[0]
elif isinstance(config, Configuration):
cfg = config
elif config == 0: # unconfigured state
class MockConfiguration(object):
def __init__(self):
self.index = None
self.bConfigurationValue = 0
cfg = MockConfiguration()
else:
cfg = util.find_descriptor(device, bConfigurationValue=config)
self.managed_open()
self.backend.set_configuration(self.handle, cfg.bConfigurationValue)
# cache the index instead of the object to avoid cyclic references
# of the device and Configuration (Device tracks the _ResourceManager,
# which tracks the Configuration, which tracks the Device)
self._active_cfg_index = cfg.index
self._ep_info.clear()
def managed_claim_interface(self, device, intf):
self.managed_open()
if isinstance(intf, Interface):
i = intf.bInterfaceNumber
else:
i = intf
if i not in self._claimed_intf:
self.backend.claim_interface(self.handle, i)
self._claimed_intf.add(i)
def managed_release_interface(self, device, intf):
if intf is None:
cfg = self.get_active_configuration(device)
i = cfg[(0,0)].bInterfaceNumber
elif isinstance(intf, Interface):
i = intf.bInterfaceNumber
else:
i = intf
if i in self._claimed_intf:
self.backend.release_interface(self.handle, i)
self._claimed_intf.remove(i)
def managed_set_interface(self, device, intf, alt):
if isinstance(intf, Interface):
i = intf
else:
cfg = self.get_active_configuration(device)
if intf is None:
intf = cfg[(0,0)].bInterfaceNumber
if alt is not None:
i = util.find_descriptor(cfg, bInterfaceNumber=intf, bAlternateSetting=alt)
else:
i = util.find_descriptor(cfg, bInterfaceNumber=intf)
self.managed_claim_interface(device, i)
if alt is None:
alt = i.bAlternateSetting
self.backend.set_interface_altsetting(self.handle, i.bInterfaceNumber, alt)
def setup_request(self, device, endpoint):
# we need the endpoint address, but the "endpoint" parameter
# can be either the a Endpoint object or the endpoint address itself
if isinstance(endpoint, Endpoint):
endpoint_address = endpoint.bEndpointAddress
else:
endpoint_address = endpoint
intf, ep = self.get_interface_and_endpoint(device, endpoint_address)
self.managed_claim_interface(device, intf)
return (intf, ep)
# Find the interface and endpoint objects which endpoint address belongs to
def get_interface_and_endpoint(self, device, endpoint_address):
try:
return self._ep_info[endpoint_address]
except KeyError:
for intf in self.get_active_configuration(device):
ep = util.find_descriptor(intf, bEndpointAddress=endpoint_address)
if ep is not None:
self._ep_info[endpoint_address] = (intf, ep)
return intf, ep
raise ValueError('Invalid endpoint address ' + hex(endpoint_address))
def get_active_configuration(self, device):
if self._active_cfg_index is None:
self.managed_open()
cfg = util.find_descriptor(
device,
bConfigurationValue=self.backend.get_configuration(self.handle)
)
if cfg is None:
raise USBError('Configuration not set')
self._active_cfg_index = cfg.index
return cfg
return device[self._active_cfg_index]
def release_all_interfaces(self, device):
claimed = copy.copy(self._claimed_intf)
for i in claimed:
self.managed_release_interface(device, i)
def dispose(self, device, close_handle = True):
self.release_all_interfaces(device)
if close_handle:
self.managed_close()
self._ep_info.clear()
self._active_cfg_index = None
class USBError(IOError):
r"""Exception class for USB errors.
Backends must raise this exception when USB related errors occur. The
backend specific error code is available through the 'backend_error_code'
member variable.
"""
def __init__(self, strerror, error_code = None, errno = None):
r"""Initialize the object.
This initializes the USBError object. The strerror and errno are passed
to the parent object. The error_code parameter is attributed to the
backend_error_code member variable.
"""
IOError.__init__(self, errno, strerror)
self.backend_error_code = error_code
class Endpoint(object):
r"""Represent an endpoint object.
This class contains all fields of the Endpoint Descriptor according to the
USB Specification. You may access them as class properties. For example, to
access the field bEndpointAddress of the endpoint descriptor:
>>> import usb.core
>>> dev = usb.core.find()
>>> for cfg in dev:
>>> for i in cfg:
>>> for e in i:
>>> print e.bEndpointAddress
"""
def __init__(self, device, endpoint, interface = 0,
alternate_setting = 0, configuration = 0):
r"""Initialize the Endpoint object.
The device parameter is the device object returned by the find()
function. endpoint is the endpoint logical index (not the endpoint
address). The configuration parameter is the logical index of the
configuration (not the bConfigurationValue field). The interface
parameter is the interface logical index (not the bInterfaceNumber
field) and alternate_setting is the alternate setting logical index
(not the bAlternateSetting value). Not every interface has more than
one alternate setting. In this case, the alternate_setting parameter
should be zero. By "logical index" we mean the relative order of the
configurations returned by the peripheral as a result of GET_DESCRIPTOR
request.
"""
self.device = device
self.index = endpoint
backend = device._ctx.backend
desc = backend.get_endpoint_descriptor(
device._ctx.dev,
endpoint,
interface,
alternate_setting,
configuration
)
_set_attr(
desc,
self,
(
'bLength',
'bDescriptorType',
'bEndpointAddress',
'bmAttributes',
'wMaxPacketSize',
'bInterval',
'bRefresh',
'bSynchAddress'
)
)
def __repr__(self):
return "<" + self._str() + ">"
def __str__(self):
headstr = " " + self._str() + " "
return "%s%s\n" % (headstr, "=" * (60 - len(headstr))) + \
" %-17s:%#7x (7 bytes)\n" % (
"bLength", self.bLength) + \
" %-17s:%#7x %s\n" % (
"bDescriptorType", self.bDescriptorType,
_try_lookup(_lu.descriptors, self.bDescriptorType)) + \
" %-17s:%#7x %s\n" % (
"bEndpointAddress", self.bEndpointAddress,
"IN" if (0x80 & self.bEndpointAddress) else "OUT") + \
" %-17s:%#7x %s\n" % (
"bmAttributes", self.bmAttributes,
_lu.ep_attributes[(self.bmAttributes & 0x3)]) + \
" %-17s:%#7x (%d bytes)\n" % (
"wMaxPacketSize", self.wMaxPacketSize, self.wMaxPacketSize) + \
" %-17s:%#7x" % ("bInterval", self.bInterval)
def write(self, data, timeout = None):
r"""Write data to the endpoint.
The parameter data contains the data to be sent to the endpoint and
timeout is the time limit of the operation. The transfer type and
endpoint address are automatically inferred.
The method returns the number of bytes written.
For details, see the Device.write() method.
"""
return self.device.write(self, data, timeout)
def read(self, size_or_buffer, timeout = None):
r"""Read data from the endpoint.
The parameter size_or_buffer is either the number of bytes to
read or an array object where the data will be put in and timeout is the
time limit of the operation. The transfer type and endpoint address
are automatically inferred.
The method returns either an array object or the number of bytes
actually read.
For details, see the Device.read() method.
"""
return self.device.read(self, size_or_buffer, timeout)
def clear_halt(self):
r"""Clear the halt/status condition."""
self.device.clear_halt(self.bEndpointAddress)
def _str(self):
return (
"ENDPOINT 0x%X: %s %s" % (self.bEndpointAddress,
_lu.ep_attributes[(self.bmAttributes & 0x3)],
"IN" if (0x80 & self.bEndpointAddress) else "OUT")
)
class Interface(object):
r"""Represent an interface object.
This class contains all fields of the Interface Descriptor
according to the USB Specification. You may access them as class
properties. For example, to access the field bInterfaceNumber
of the interface descriptor:
>>> import usb.core
>>> dev = usb.core.find()
>>> for cfg in dev:
>>> for i in cfg:
>>> print i.bInterfaceNumber
"""
def __init__(self, device, interface = 0,
alternate_setting = 0, configuration = 0):
r"""Initialize the interface object.
The device parameter is the device object returned by the find()
function. The configuration parameter is the logical index of the
configuration (not the bConfigurationValue field). The interface
parameter is the interface logical index (not the bInterfaceNumber
field) and alternate_setting is the alternate setting logical index
(not the bAlternateSetting value). Not every interface has more than
one alternate setting. In this case, the alternate_setting parameter
should be zero. By "logical index" we mean the relative order of the
configurations returned by the peripheral as a result of GET_DESCRIPTOR
request.
"""
self.device = device
self.alternate_index = alternate_setting
self.index = interface
self.configuration = configuration
backend = device._ctx.backend
desc = backend.get_interface_descriptor(
self.device._ctx.dev,
interface,
alternate_setting,
configuration
)
_set_attr(
desc,
self,
(
'bLength',
'bDescriptorType',
'bInterfaceNumber',
'bAlternateSetting',
'bNumEndpoints',
'bInterfaceClass',
'bInterfaceSubClass',
'bInterfaceProtocol',
'iInterface',
)
)
def __repr__(self):
return "<" + self._str() + ">"
def __str__(self):
""" show all information for the interface
"""
string = self._get_full_descriptor_str()
for endpoint in self:
string += "\n" + str(endpoint)
return string
def endpoints(self):
r"""Return a tuple of the interface endpoints."""
return tuple(self)
def set_altsetting(self):
r"""Set the interface alternate setting."""
self.device.set_interface_altsetting(
self.bInterfaceNumber,
self.bAlternateSetting
)
def __iter__(self):
r"""Iterate over all endpoints of the interface."""
for i in range(self.bNumEndpoints):
yield Endpoint(
self.device,
i,
self.index,
self.alternate_index,
self.configuration
)
def __getitem__(self, index):
r"""Return the Endpoint object in the given position."""
return Endpoint(
self.device,
index,
self.index,
self.alternate_index,
self.configuration
)
def _str(self):
return "INTERFACE %d%s: %s" % (self.bInterfaceNumber,
", %d" % (self.bAlternateSetting) if self.bAlternateSetting else "",
_try_lookup(_lu.interface_classes, self.bInterfaceClass,
default = "Unknown Class"))
def _get_full_descriptor_str(self):
headstr = " " + self._str() + " "
return "%s%s\n" % (headstr, "=" * (60 - len(headstr))) + \
" %-19s:%#7x (9 bytes)\n" % (
"bLength", self.bLength) + \
" %-19s:%#7x %s\n" % (
"bDescriptorType", self.bDescriptorType,
_try_lookup(_lu.descriptors, self.bDescriptorType)) + \
" %-19s:%#7x\n" % (
"bInterfaceNumber", self.bInterfaceNumber) + \
" %-19s:%#7x\n" % (
"bAlternateSetting", self.bAlternateSetting) + \
" %-19s:%#7x\n" % (
"bNumEndpoints", self.bNumEndpoints) + \
" %-19s:%#7x %s\n" % (
"bInterfaceClass", self.bInterfaceClass,
_try_lookup(_lu.interface_classes, self.bInterfaceClass)) + \
" %-19s:%#7x\n" % (
"bInterfaceSubClass", self.bInterfaceSubClass) + \
" %-19s:%#7x\n" % (
"bInterfaceProtocol", self.bInterfaceProtocol) + \
" %-19s:%#7x %s" % (
"iInterface", self.iInterface,
_try_get_string(self.device, self.iInterface))
class Configuration(object):
r"""Represent a configuration object.
This class contains all fields of the Configuration Descriptor according to
the USB Specification. You may access them as class properties. For
example, to access the field bConfigurationValue of the configuration
descriptor:
>>> import usb.core
>>> dev = usb.core.find()
>>> for cfg in dev:
>>> print cfg.bConfigurationValue
"""
def __init__(self, device, configuration = 0):
r"""Initialize the configuration object.
The device parameter is the device object returned by the find()
function. The configuration parameter is the logical index of the
configuration (not the bConfigurationValue field). By "logical index"
we mean the relative order of the configurations returned by the
peripheral as a result of GET_DESCRIPTOR request.
"""
self.device = device
self.index = configuration
backend = device._ctx.backend
desc = backend.get_configuration_descriptor(
self.device._ctx.dev,
configuration
)
_set_attr(
desc,
self,
(
'bLength',
'bDescriptorType',
'wTotalLength',
'bNumInterfaces',
'bConfigurationValue',
'iConfiguration',
'bmAttributes',
'bMaxPower'
)
)
def __repr__(self):
return "<" + self._str() + ">"
def __str__(self):
string = self._get_full_descriptor_str()
for interface in self:
string += "\n%s" % str(interface)
return string
def interfaces(self):
r"""Return a tuple of the configuration interfaces."""
return tuple(self)
def set(self):
r"""Set this configuration as the active one."""
self.device.set_configuration(self.bConfigurationValue)
def __iter__(self):
r"""Iterate over all interfaces of the configuration."""
for i in range(self.bNumInterfaces):
alt = 0
try:
while True:
yield Interface(self.device, i, alt, self.index)
alt += 1
except (USBError, IndexError):
pass
def __getitem__(self, index):
r"""Return the Interface object in the given position.
index is a tuple of two values with interface index and
alternate setting index, respectivally. Example:
>>> interface = config[(0, 0)]
"""
return Interface(self.device, index[0], index[1], self.index)
def _str(self):
return "CONFIGURATION %d: %d mA" % (
self.bConfigurationValue,
_lu.MAX_POWER_UNITS_USB2p0 * self.bMaxPower)
def _get_full_descriptor_str(self):
headstr = " " + self._str() + " "
return "%s%s\n" % (headstr, "=" * (60 - len(headstr))) + \
" %-21s:%#7x (9 bytes)\n" % (
"bLength", self.bLength) + \
" %-21s:%#7x %s\n" % (
"bDescriptorType", self.bDescriptorType,
_try_lookup(_lu.descriptors, self.bDescriptorType)) + \
" %-21s:%#7x (%d bytes)\n" % (
"wTotalLength", self.wTotalLength, self.wTotalLength) + \
" %-21s:%#7x\n" % (
"bNumInterfaces", self.bNumInterfaces) + \
" %-21s:%#7x\n" % (
"bConfigurationValue", self.bConfigurationValue) + \
" %-21s:%#7x %s\n" % (
"iConfiguration", self.iConfiguration,
_try_get_string(self.device, self.iConfiguration)) + \
" %-21s:%#7x %s Powered%s\n" % (
"bmAttributes", self.bmAttributes,
"Self" if (self.bmAttributes & (1<<6)) else "Bus",
", Remote Wakeup" if (self.bmAttributes & (1<<5)) else ""
# bit 7 is high, bit 4..0 are 0
) + \
" %-21s:%#7x (%d mA)" % (
"bMaxPower", self.bMaxPower,
_lu.MAX_POWER_UNITS_USB2p0 * self.bMaxPower)
# FIXME : add a check for superspeed vs usb 2.0
class Device(object):
r"""Device object.
This class contains all fields of the Device Descriptor according to the
USB Specification. You may access them as class properties. For example,
to access the field bDescriptorType of the device descriptor:
>>> import usb.core
>>> dev = usb.core.find()
>>> dev.bDescriptorType
Additionally, the class provides methods to communicate with the hardware.
Typically, an application will first call the set_configuration() method to
put the device in a known configured state, optionally call the
set_interface_altsetting() to select the alternate setting (if there is
more than one) of the interface used, and call the write() and read()
method to send and receive data.
When working in a new hardware, one first try would be like this:
>>> import usb.core
>>> dev = usb.core.find(idVendor=myVendorId, idProduct=myProductId)
>>> dev.set_configuration()
>>> dev.write(1, 'test')
This sample finds the device of interest (myVendorId and myProductId should
be replaced by the corresponding values of your device), then configures
the device (by default, the configuration value is 1, which is a typical
value for most devices) and then writes some data to the endpoint 0x01.
Timeout values for the write, read and ctrl_transfer methods are specified
in miliseconds. If the parameter is omitted, Device.default_timeout value
will be used instead. This property can be set by the user at anytime.
"""
def __repr__(self):
return "<" + self._str() + ">"
def __str__(self):
string = self._get_full_descriptor_str()
try:
for configuration in self:
string += "\n%s" % str(configuration)
except USBError:
try:
configuration = self.get_active_configuration()
string += "\n%s" % (configuration.info)
except USBError:
string += " USBError Accessing Configurations"
return string
def configurations(self):
r"""Return a tuple of the device configurations."""
return tuple(self)
def __init__(self, dev, backend):
r"""Initialize the Device object.
Library users should normally get a Device instance through
the find function. The dev parameter is the identification
of a device to the backend and its meaning is opaque outside
of it. The backend parameter is a instance of a backend
object.
"""
self._ctx = _ResourceManager(dev, backend)
self.__default_timeout = _DEFAULT_TIMEOUT
self._serial_number, self._product, self._manufacturer = None, None, None
desc = backend.get_device_descriptor(dev)
_set_attr(
desc,
self,
(
'bLength',
'bDescriptorType',
'bcdUSB',
'bDeviceClass',
'bDeviceSubClass',
'bDeviceProtocol',
'bMaxPacketSize0',
'idVendor',
'idProduct',
'bcdDevice',
'iManufacturer',
'iProduct',
'iSerialNumber',
'bNumConfigurations',
'address',
'bus',
'port_number'
)
)
if desc.bus is not None:
self.bus = int(desc.bus)
else:
self.bus = None
if desc.address is not None:
self.address = int(desc.address)
else:
self.address = None
if desc.port_number is not None:
self.port_number = int(desc.port_number)
else:
self.port_number = None
@property
def serial_number(self):
""" Return the USB device's serial number string descriptor
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._serial_number is None:
self._serial_number = util.get_string(self, self.iSerialNumber)
return self._serial_number
@property
def product(self):
""" Return the USB device's product string descriptor
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._product is None:
self._product = util.get_string(self, self.iProduct)
return self._product
@property
def manufacturer(self):
""" Return the USB device's manufacturer string descriptor
This property will cause some USB traffic the first time it is accessed
and cache the resulting value for future use.
"""
if self._manufacturer is None:
self._manufacturer = util.get_string(self, self.iManufacturer)
return self._manufacturer
def set_configuration(self, configuration = None):
r"""Set the active configuration.
The configuration parameter is the bConfigurationValue field of the
configuration you want to set as active. If you call this method
without parameter, it will use the first configuration found. As a
device hardly ever has more than one configuration, calling the method
without parameter is enough to get the device ready.
"""
self._ctx.managed_set_configuration(self, configuration)
def get_active_configuration(self):
r"""Return a Configuration object representing the current
configuration set.
"""
return self._ctx.get_active_configuration(self)
def set_interface_altsetting(self, interface = None, alternate_setting = None):
r"""Set the alternate setting for an interface.
When you want to use an interface and it has more than one alternate
setting, you should call this method to select the alternate setting
you would like to use. If you call the method without one or the two
parameters, it will be selected the first one found in the Device in
the same way of set_configuration method.
Commonly, an interface has only one alternate setting and this call is
not necessary. For most of the devices, either it has more than one
alternate setting or not, it is not harmful to make a call to this
method with no arguments, as devices will silently ignore the request
when there is only one alternate setting, though the USB Spec allows
devices with no additional alternate setting return an error to the
Host in response to a SET_INTERFACE request.
If you are in doubt, you may want to call it with no arguments wrapped
by a try/except clause:
>>> try:
>>> dev.set_interface_altsetting()
>>> except usb.core.USBError:
>>> pass
"""
self._ctx.managed_set_interface(self, interface, alternate_setting)
def clear_halt(self, ep):
r""" Clear the halt/stall condition for the endpoint ep."""
if isinstance(ep, Endpoint):
ep = ep.bEndpointAddress
self._ctx.managed_open()
self._ctx.backend.clear_halt(self._ctx.handle, ep)
def reset(self):
r"""Reset the device."""
self._ctx.managed_open()
self._ctx.dispose(self, False)
self._ctx.backend.reset_device(self._ctx.handle)
self._ctx.dispose(self, True)
def write(self, endpoint, data, timeout = None):
r"""Write data to the endpoint.
This method is used to send data to the device. The endpoint parameter
corresponds to the bEndpointAddress member whose endpoint you want to
communicate with.
The data parameter should be a sequence like type convertible to
array type (see array module).
The timeout is specified in miliseconds.
The method returns the number of bytes written.
"""
backend = self._ctx.backend
fn_map = {
util.ENDPOINT_TYPE_BULK:backend.bulk_write,
util.ENDPOINT_TYPE_INTR:backend.intr_write,
util.ENDPOINT_TYPE_ISO:backend.iso_write
}
intf, ep = self._ctx.setup_request(self, endpoint)
fn = fn_map[util.endpoint_type(ep.bmAttributes)]
return fn(
self._ctx.handle,
ep.bEndpointAddress,
intf.bInterfaceNumber,
_interop.as_array(data),
self.__get_timeout(timeout)
)
def read(self, endpoint, size_or_buffer, timeout = None):
r"""Read data from the endpoint.
This method is used to receive data from the device. The endpoint
parameter corresponds to the bEndpointAddress member whose endpoint
you want to communicate with. The size_or_buffer parameter either
tells how many bytes you want to read or supplies the buffer to
receive the data (it *must* be an object of the type array).
The timeout is specified in miliseconds.
If the size_or_buffer parameter is the number of bytes to read, the
method returns an array object with the data read. If the
size_or_buffer parameter is an array object, it returns the number
of bytes actually read.
"""
backend = self._ctx.backend
fn_map = {
util.ENDPOINT_TYPE_BULK:backend.bulk_read,
util.ENDPOINT_TYPE_INTR:backend.intr_read,
util.ENDPOINT_TYPE_ISO:backend.iso_read
}
intf, ep = self._ctx.setup_request(self, endpoint)
fn = fn_map[util.endpoint_type(ep.bmAttributes)]
if isinstance(size_or_buffer, array.array):
buff = size_or_buffer
else: # here we consider it is a integer
buff = util.create_buffer(size_or_buffer)
ret = fn(
self._ctx.handle,
ep.bEndpointAddress,
intf.bInterfaceNumber,
buff,
self.__get_timeout(timeout))
if isinstance(size_or_buffer, array.array):
return ret
elif ret != len(buff) * buff.itemsize:
return buff[:ret]
else:
return buff
def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0,
data_or_wLength = None, timeout = None):
r"""Do a control transfer on the endpoint 0.
This method is used to issue a control transfer over the endpoint 0
(endpoint 0 is required to always be a control endpoint).
The parameters bmRequestType, bRequest, wValue and wIndex are the same
of the USB Standard Control Request format.
Control requests may or may not have a data payload to write/read.
In cases which it has, the direction bit of the bmRequestType
field is used to infere the desired request direction. For
host to device requests (OUT), data_or_wLength parameter is
the data payload to send, and it must be a sequence type convertible
to an array object. In this case, the return value is the number of data
payload written. For device to host requests (IN), data_or_wLength
is either the wLength parameter of the control request specifying the
number of bytes to read in data payload, and the return value is
an array object with data read, or an array object which the data
will be read to, and the return value is the number of bytes read.
"""
try:
buff = util.create_buffer(data_or_wLength)
except TypeError:
buff = _interop.as_array(data_or_wLength)
self._ctx.managed_open()
# Thanks to Johannes Stezenbach to point me out that we need to
# claim the recipient interface
recipient = bmRequestType & 3
if recipient == util.CTRL_RECIPIENT_INTERFACE:
interface_number = wIndex & 0xff
self._ctx.managed_claim_interface(self, interface_number)
ret = self._ctx.backend.ctrl_transfer(
self._ctx.handle,
bmRequestType,
bRequest,
wValue,
wIndex,
buff,
self.__get_timeout(timeout))
if isinstance(data_or_wLength, array.array) \
or util.ctrl_direction(bmRequestType) == util.CTRL_OUT:
return ret
elif ret != len(buff) * buff.itemsize:
return buff[:ret]
else:
return buff
def is_kernel_driver_active(self, interface):
r"""Determine if there is kernel driver associated with the interface.
If a kernel driver is active, and the object will be unable to perform
I/O.
The interface parameter is the device interface number to check.
"""
self._ctx.managed_open()
return self._ctx.backend.is_kernel_driver_active(
self._ctx.handle,
interface)
def detach_kernel_driver(self, interface):
r"""Detach a kernel driver.
If successful, you will then be able to perform I/O.
The interface parameter is the device interface number to detach the
driver from.
"""
self._ctx.managed_open()
self._ctx.backend.detach_kernel_driver(
self._ctx.handle,
interface)
def attach_kernel_driver(self, interface):
r"""Re-attach an interface's kernel driver, which was previously
detached using detach_kernel_driver().
The interface parameter is the device interface number to attach the
driver to.
"""
self._ctx.managed_open()
self._ctx.backend.attach_kernel_driver(
self._ctx.handle,
interface)
def __iter__(self):
r"""Iterate over all configurations of the device."""
for i in range(self.bNumConfigurations):
yield Configuration(self, i)
def __getitem__(self, index):