core.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. # Copyright (C) 2009-2011 Wander Lairson Costa
  2. #
  3. # The following terms apply to all files associated
  4. # with the software unless explicitly disclaimed in individual files.
  5. #
  6. # The authors hereby grant permission to use, copy, modify, distribute,
  7. # and license this software and its documentation for any purpose, provided
  8. # that existing copyright notices are retained in all copies and that this
  9. # notice is included verbatim in any distributions. No written agreement,
  10. # license, or royalty fee is required for any of the authorized uses.
  11. # Modifications to this software may be copyrighted by their authors
  12. # and need not follow the licensing terms described here, provided that
  13. # the new terms are clearly indicated on the first page of each file where
  14. # they apply.
  15. #
  16. # IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
  17. # FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
  18. # ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
  19. # DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
  20. # POSSIBILITY OF SUCH DAMAGE.
  21. #
  22. # THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
  23. # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
  24. # FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
  25. # IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
  26. # NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
  27. # MODIFICATIONS.
  28. r"""usb.core - Core USB features.
  29. This module exports:
  30. Device - a class representing a USB device.
  31. Configuration - a class representing a configuration descriptor.
  32. Interface - a class representing an interface descriptor.
  33. Endpoint - a class representing an endpoint descriptor.
  34. find() - a function to find USB devices.
  35. """
  36. __author__ = 'Wander Lairson Costa'
  37. __all__ = ['Device', 'Configuration', 'Interface', 'Endpoint', 'find']
  38. import usb.util as util
  39. import copy
  40. import operator
  41. import usb._interop as _interop
  42. import logging
  43. _logger = logging.getLogger('usb.core')
  44. _DEFAULT_TIMEOUT = 1000
  45. def _set_attr(input, output, fields):
  46. for f in fields:
  47. setattr(output, f, int(getattr(input, f)))
  48. class _ResourceManager(object):
  49. def __init__(self, dev, backend):
  50. self.backend = backend
  51. self._active_cfg_index = None
  52. self.dev = dev
  53. self.handle = None
  54. self._claimed_intf = _interop._set()
  55. self._alt_set = {}
  56. self._ep_type_map = {}
  57. def managed_open(self):
  58. if self.handle is None:
  59. self.handle = self.backend.open_device(self.dev)
  60. return self.handle
  61. def managed_close(self):
  62. if self.handle is not None:
  63. self.backend.close_device(self.handle)
  64. self.handle = None
  65. def managed_set_configuration(self, device, config):
  66. if config is None:
  67. cfg = device[0]
  68. elif isinstance(config, Configuration):
  69. cfg = config
  70. elif config == 0: # unconfigured state
  71. class FakeConfiguration(object):
  72. def __init__(self):
  73. self.index = None
  74. self.bConfigurationValue = 0
  75. cfg = FakeConfiguration()
  76. else:
  77. cfg = util.find_descriptor(device, bConfigurationValue=config)
  78. self.managed_open()
  79. self.backend.set_configuration(self.handle, cfg.bConfigurationValue)
  80. # cache the index instead of the object to avoid cyclic references
  81. # of the device and Configuration (Device tracks the _ResourceManager,
  82. # which tracks the Configuration, which tracks the Device)
  83. self._active_cfg_index = cfg.index
  84. # after changing configuration, our alternate setting and endpoint type caches
  85. # are not valid anymore
  86. self._ep_type_map.clear()
  87. self._alt_set.clear()
  88. def managed_claim_interface(self, device, intf):
  89. self.managed_open()
  90. if intf is None:
  91. cfg = self.get_active_configuration(device)
  92. i = cfg[(0,0)].bInterfaceNumber
  93. elif isinstance(intf, Interface):
  94. i = intf.bInterfaceNumber
  95. else:
  96. i = intf
  97. if i not in self._claimed_intf:
  98. self.backend.claim_interface(self.handle, i)
  99. self._claimed_intf.add(i)
  100. def managed_release_interface(self, device, intf):
  101. if intf is None:
  102. cfg = self.get_active_configuration(device)
  103. i = cfg[(0,0)].bInterfaceNumber
  104. elif isinstance(intf, Interface):
  105. i = intf.bInterfaceNumber
  106. else:
  107. i = intf
  108. if i in self._claimed_intf:
  109. self.backend.release_interface(self.handle, i)
  110. self._claimed_intf.remove(i)
  111. def managed_set_interface(self, device, intf, alt):
  112. if intf is None:
  113. i = self.get_interface(device, intf)
  114. elif isinstance(intf, Interface):
  115. i = intf
  116. else:
  117. cfg = self.get_active_configuration(device)
  118. if alt is not None:
  119. i = util.find_descriptor(cfg, bInterfaceNumber=intf, bAlternateSetting=alt)
  120. else:
  121. i = util.find_descriptor(cfg, bInterfaceNumber=intf)
  122. self.managed_claim_interface(device, i)
  123. if alt is None:
  124. alt = i.bAlternateSetting
  125. self.backend.set_interface_altsetting(self.handle, i.bInterfaceNumber, alt)
  126. self._alt_set[i.bInterfaceNumber] = alt
  127. def get_interface(self, device, intf):
  128. # TODO: check the viability of issuing a GET_INTERFACE
  129. # request when we don't have a alternate setting cached
  130. if intf is None:
  131. cfg = self.get_active_configuration(device)
  132. return cfg[(0,0)]
  133. elif isinstance(intf, Interface):
  134. return intf
  135. else:
  136. cfg = self.get_active_configuration(device)
  137. if intf in self._alt_set:
  138. return util.find_descriptor(cfg,
  139. bInterfaceNumber=intf,
  140. bAlternateSetting=self._alt_set[intf])
  141. else:
  142. return util.find_descriptor(cfg, bInterfaceNumber=intf)
  143. def get_active_configuration(self, device):
  144. if self._active_cfg_index is None:
  145. cfg = util.find_descriptor(
  146. device,
  147. bConfigurationValue=self.backend.get_configuration(self.handle)
  148. )
  149. if cfg is None:
  150. raise USBError('Configuration not set')
  151. self._active_cfg_index = cfg.index
  152. return cfg
  153. return device[self._active_cfg_index]
  154. def get_endpoint_type(self, device, address, intf):
  155. intf = self.get_interface(device, intf)
  156. key = (address, intf.bInterfaceNumber, intf.bAlternateSetting)
  157. try:
  158. return self._ep_type_map[key]
  159. except KeyError:
  160. e = util.find_descriptor(intf, bEndpointAddress=address)
  161. etype = util.endpoint_type(e.bmAttributes)
  162. self._ep_type_map[key] = etype
  163. return etype
  164. def release_all_interfaces(self, device):
  165. claimed = copy.copy(self._claimed_intf)
  166. for i in claimed:
  167. self.managed_release_interface(device, i)
  168. def dispose(self, device, close_handle = True):
  169. self.release_all_interfaces(device)
  170. if close_handle:
  171. self.managed_close()
  172. self._ep_type_map.clear()
  173. self._alt_set.clear()
  174. self._active_cfg_index = None
  175. class USBError(IOError):
  176. r"""Exception class for USB errors.
  177. Backends must raise this exception when USB related errors occur.
  178. """
  179. pass
  180. class Endpoint(object):
  181. r"""Represent an endpoint object.
  182. This class contains all fields of the Endpoint Descriptor
  183. according to the USB Specification. You may access them as class
  184. properties. For example, to access the field bEndpointAddress
  185. of the endpoint descriptor:
  186. >>> import usb.core
  187. >>> dev = usb.core.find()
  188. >>> for cfg in dev:
  189. >>> for i in cfg:
  190. >>> for e in i:
  191. >>> print e.bEndpointAddress
  192. """
  193. def __init__(self, device, endpoint, interface = 0,
  194. alternate_setting = 0, configuration = 0):
  195. r"""Initialize the Endpoint object.
  196. The device parameter is the device object returned by the find()
  197. function. endpoint is the endpoint logical index (not the endpoint address).
  198. The configuration parameter is the logical index of the
  199. configuration (not the bConfigurationValue field). The interface
  200. parameter is the interface logical index (not the bInterfaceNumber field)
  201. and alternate_setting is the alternate setting logical index (not the
  202. bAlternateSetting value). Not every interface has more than one alternate
  203. setting. In this case, the alternate_setting parameter should be zero.
  204. By "logical index" we mean the relative order of the configurations returned by the
  205. peripheral as a result of GET_DESCRIPTOR request.
  206. """
  207. self.device = device
  208. intf = Interface(device, interface, alternate_setting, configuration)
  209. self.interface = intf.bInterfaceNumber
  210. self.index = endpoint
  211. backend = device._ctx.backend
  212. desc = backend.get_endpoint_descriptor(
  213. device._ctx.dev,
  214. endpoint,
  215. interface,
  216. alternate_setting,
  217. configuration
  218. )
  219. _set_attr(
  220. desc,
  221. self,
  222. (
  223. 'bLength',
  224. 'bDescriptorType',
  225. 'bEndpointAddress',
  226. 'bmAttributes',
  227. 'wMaxPacketSize',
  228. 'bInterval',
  229. 'bRefresh',
  230. 'bSynchAddress'
  231. )
  232. )
  233. def write(self, data, timeout = None):
  234. r"""Write data to the endpoint.
  235. The parameter data contains the data to be sent to the endpoint and
  236. timeout is the time limit of the operation. The transfer type and
  237. endpoint address are automatically inferred.
  238. The method returns the number of bytes written.
  239. For details, see the Device.write() method.
  240. """
  241. return self.device.write(self.bEndpointAddress, data, self.interface, timeout)
  242. def read(self, size, timeout = None):
  243. r"""Read data from the endpoint.
  244. The parameter size is the number of bytes to read and timeout is the
  245. time limit of the operation.The transfer type and endpoint address
  246. are automatically inferred.
  247. The method returns an array.array object with the data read.
  248. For details, see the Device.read() method.
  249. """
  250. return self.device.read(self.bEndpointAddress, size, self.interface, timeout)
  251. class Interface(object):
  252. r"""Represent an interface object.
  253. This class contains all fields of the Interface Descriptor
  254. according to the USB Specification. You may access them as class
  255. properties. For example, to access the field bInterfaceNumber
  256. of the interface descriptor:
  257. >>> import usb.core
  258. >>> dev = usb.core.find()
  259. >>> for cfg in dev:
  260. >>> for i in cfg:
  261. >>> print i.bInterfaceNumber
  262. """
  263. def __init__(self, device, interface = 0,
  264. alternate_setting = 0, configuration = 0):
  265. r"""Initialize the interface object.
  266. The device parameter is the device object returned by the find()
  267. function. The configuration parameter is the logical index of the
  268. configuration (not the bConfigurationValue field). The interface
  269. parameter is the interface logical index (not the bInterfaceNumber field)
  270. and alternate_setting is the alternate setting logical index (not the
  271. bAlternateSetting value). Not every interface has more than one alternate
  272. setting. In this case, the alternate_setting parameter should be zero.
  273. By "logical index" we mean the relative order of the configurations returned by the
  274. peripheral as a result of GET_DESCRIPTOR request.
  275. """
  276. self.device = device
  277. self.alternate_index = alternate_setting
  278. self.index = interface
  279. self.configuration = configuration
  280. backend = device._ctx.backend
  281. desc = backend.get_interface_descriptor(
  282. self.device._ctx.dev,
  283. interface,
  284. alternate_setting,
  285. configuration
  286. )
  287. _set_attr(
  288. desc,
  289. self,
  290. (
  291. 'bLength',
  292. 'bDescriptorType',
  293. 'bInterfaceNumber',
  294. 'bAlternateSetting',
  295. 'bNumEndpoints',
  296. 'bInterfaceClass',
  297. 'bInterfaceSubClass',
  298. 'bInterfaceProtocol',
  299. 'iInterface'
  300. )
  301. )
  302. def set_altsetting(self):
  303. r"""Set the interface alternate setting."""
  304. self.device.set_interface_altsetting(
  305. self.bInterfaceNumber,
  306. self.bAlternateSetting
  307. )
  308. def __iter__(self):
  309. r"""Iterate over all endpoints of the interface."""
  310. for i in range(self.bNumEndpoints):
  311. yield Endpoint(
  312. self.device,
  313. i,
  314. self.index,
  315. self.alternate_index,
  316. self.configuration
  317. )
  318. def __getitem__(self, index):
  319. r"""Return the Endpoint object in the given position."""
  320. return Endpoint(
  321. self.device,
  322. index,
  323. self.index,
  324. self.alternate_index,
  325. self.configuration
  326. )
  327. class Configuration(object):
  328. r"""Represent a configuration object.
  329. This class contains all fields of the Configuration Descriptor
  330. according to the USB Specification. You may access them as class
  331. properties. For example, to access the field bConfigurationValue
  332. of the configuration descriptor:
  333. >>> import usb.core
  334. >>> dev = usb.core.find()
  335. >>> for cfg in dev:
  336. >>> print cfg.bConfigurationValue
  337. """
  338. def __init__(self, device, configuration = 0):
  339. r"""Initialize the configuration object.
  340. The device parameter is the device object returned by the find()
  341. function. The configuration parameter is the logical index of the
  342. configuration (not the bConfigurationValue field). By "logical index"
  343. we mean the relative order of the configurations returned by the
  344. peripheral as a result of GET_DESCRIPTOR request.
  345. """
  346. self.device = device
  347. self.index = configuration
  348. backend = device._ctx.backend
  349. desc = backend.get_configuration_descriptor(
  350. self.device._ctx.dev,
  351. configuration
  352. )
  353. _set_attr(
  354. desc,
  355. self,
  356. (
  357. 'bLength',
  358. 'bDescriptorType',
  359. 'wTotalLength',
  360. 'bNumInterfaces',
  361. 'bConfigurationValue',
  362. 'iConfiguration',
  363. 'bmAttributes',
  364. 'bMaxPower'
  365. )
  366. )
  367. def set(self):
  368. r"""Set this configuration as the active one."""
  369. self.device.set_configuration(self.bConfigurationValue)
  370. def __iter__(self):
  371. r"""Iterate over all interfaces of the configuration."""
  372. for i in range(self.bNumInterfaces):
  373. alt = 0
  374. try:
  375. while True:
  376. yield Interface(self.device, i, alt, self.index)
  377. alt += 1
  378. except (USBError, IndexError):
  379. pass
  380. def __getitem__(self, index):
  381. r"""Return the Interface object in the given position.
  382. index is a tuple of two values with interface index and
  383. alternate setting index, respectivally. Example:
  384. >>> interface = config[(0, 0)]
  385. """
  386. return Interface(self.device, index[0], index[1], self.index)
  387. class Device(object):
  388. r"""Device object.
  389. This class contains all fields of the Device Descriptor according
  390. to the USB Specification. You may access them as class properties.
  391. For example, to access the field bDescriptorType of the device
  392. descriptor:
  393. >>> import usb.core
  394. >>> dev = usb.core.find()
  395. >>> dev.bDescriptorType
  396. Additionally, the class provides methods to communicate with
  397. the hardware. Typically, an application will first call the
  398. set_configuration() method to put the device in a known configured
  399. state, optionally call the set_interface_altsetting() to select the
  400. alternate setting (if there is more than one) of the interface used,
  401. and call the write() and read() method to send and receive data.
  402. When working in a new hardware, one first try would be like this:
  403. >>> import usb.core
  404. >>> dev = usb.core.find(idVendor=myVendorId, idProduct=myProductId)
  405. >>> dev.set_configuration()
  406. >>> dev.write(1, 'test')
  407. This sample finds the device of interest (myVendorId and myProductId should be
  408. replaced by the corresponding values of your device), then configures the device
  409. (by default, the configuration value is 1, which is a typical value for most
  410. devices) and then writes some data to the endpoint 0x01.
  411. Timeout values for the write, read and ctrl_transfer methods are specified in
  412. miliseconds. If the parameter is omitted, Device.default_timeout value will
  413. be used instead. This property can be set by the user at anytime.
  414. """
  415. def __init__(self, dev, backend):
  416. r"""Initialize the Device object.
  417. Library users should normally get a Device instance through
  418. the find function. The dev parameter is the identification
  419. of a device to the backend and its meaning is opaque outside
  420. of it. The backend parameter is a instance of a backend
  421. object.
  422. """
  423. self._ctx = _ResourceManager(dev, backend)
  424. self.__default_timeout = _DEFAULT_TIMEOUT
  425. desc = backend.get_device_descriptor(dev)
  426. _set_attr(
  427. desc,
  428. self,
  429. (
  430. 'bLength',
  431. 'bDescriptorType',
  432. 'bcdUSB',
  433. 'bDeviceClass',
  434. 'bDeviceSubClass',
  435. 'bDeviceProtocol',
  436. 'bMaxPacketSize0',
  437. 'idVendor',
  438. 'idProduct',
  439. 'bcdDevice',
  440. 'iManufacturer',
  441. 'iProduct',
  442. 'iSerialNumber',
  443. 'bNumConfigurations'
  444. )
  445. )
  446. def set_configuration(self, configuration = None):
  447. r"""Set the active configuration.
  448. The configuration parameter is the bConfigurationValue field of the
  449. configuration you want to set as active. If you call this method
  450. without parameter, it will use the first configuration found.
  451. As a device hardly ever has more than one configuration, calling
  452. the method without parameter is enough to get the device ready.
  453. """
  454. self._ctx.managed_set_configuration(self, configuration)
  455. def get_active_configuration(self):
  456. r"""Return a Configuration object representing the current configuration set."""
  457. return self._ctx.get_active_configuration(self)
  458. def set_interface_altsetting(self, interface = None, alternate_setting = None):
  459. r"""Set the alternate setting for an interface.
  460. When you want to use an interface and it has more than one alternate setting,
  461. you should call this method to select the alternate setting you would like
  462. to use. If you call the method without one or the two parameters, it will
  463. be selected the first one found in the Device in the same way of set_configuration
  464. method.
  465. Commonly, an interface has only one alternate setting and this call is
  466. not necessary. For most of the devices, either it has more than one alternate
  467. setting or not, it is not harmful to make a call to this method with no arguments,
  468. as devices will silently ignore the request when there is only one alternate
  469. setting, though the USB Spec allows devices with no additional alternate setting
  470. return an error to the Host in response to a SET_INTERFACE request.
  471. If you are in doubt, you may want to call it with no arguments wrapped by
  472. a try/except clause:
  473. >>> try:
  474. >>> dev.set_interface_altsetting()
  475. >>> except usb.core.USBError:
  476. >>> pass
  477. """
  478. self._ctx.managed_set_interface(self, interface, alternate_setting)
  479. def reset(self):
  480. r"""Reset the device."""
  481. self._ctx.dispose(self, False)
  482. self._ctx.backend.reset_device(self._ctx.handle)
  483. self._ctx.dispose(self, True)
  484. def write(self, endpoint, data, interface = None, timeout = None):
  485. r"""Write data to the endpoint.
  486. This method is used to send data to the device. The endpoint parameter
  487. corresponds to the bEndpointAddress member whose endpoint you want to
  488. communicate with. The interface parameter is the bInterfaceNumber field
  489. of the interface descriptor which contains the endpoint. If you do not
  490. provide one, the first one found will be used, as explained in the
  491. set_interface_altsetting() method.
  492. The data parameter should be a sequence like type convertible to
  493. array type (see array module).
  494. The timeout is specified in miliseconds.
  495. The method returns the number of bytes written.
  496. """
  497. backend = self._ctx.backend
  498. fn_map = {
  499. util.ENDPOINT_TYPE_BULK:backend.bulk_write,
  500. util.ENDPOINT_TYPE_INTR:backend.intr_write,
  501. util.ENDPOINT_TYPE_ISO:backend.iso_write
  502. }
  503. intf = self._ctx.get_interface(self, interface)
  504. fn = fn_map[self._ctx.get_endpoint_type(self, endpoint, intf)]
  505. self._ctx.managed_claim_interface(self, intf)
  506. return fn(
  507. self._ctx.handle,
  508. endpoint,
  509. intf.bInterfaceNumber,
  510. _interop.as_array(data),
  511. self.__get_timeout(timeout)
  512. )
  513. def read(self, endpoint, size, interface = None, timeout = None):
  514. r"""Read data from the endpoint.
  515. This method is used to receive data from the device. The endpoint parameter
  516. corresponds to the bEndpointAddress member whose endpoint you want to
  517. communicate with. The interface parameter is the bInterfaceNumber field
  518. of the interface descriptor which contains the endpoint. If you do not
  519. provide one, the first one found will be used, as explained in the
  520. set_interface_altsetting() method. The size parameters tells how many
  521. bytes you want to read.
  522. The timeout is specified in miliseconds.
  523. The method returns an array object with the data read.
  524. """
  525. backend = self._ctx.backend
  526. fn_map = {
  527. util.ENDPOINT_TYPE_BULK:backend.bulk_read,
  528. util.ENDPOINT_TYPE_INTR:backend.intr_read,
  529. util.ENDPOINT_TYPE_ISO:backend.iso_read
  530. }
  531. intf = self._ctx.get_interface(self, interface)
  532. fn = fn_map[self._ctx.get_endpoint_type(self, endpoint, intf)]
  533. self._ctx.managed_claim_interface(self, intf)
  534. return fn(
  535. self._ctx.handle,
  536. endpoint,
  537. intf.bInterfaceNumber,
  538. size,
  539. self.__get_timeout(timeout)
  540. )
  541. def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0,
  542. data_or_wLength = None, timeout = None):
  543. r"""Do a control transfer on the endpoint 0.
  544. This method is used to issue a control transfer over the
  545. endpoint 0(endpoint 0 is required to always be a control endpoint).
  546. The parameters bmRequestType, bRequest, wValue and wIndex are the
  547. same of the USB Standard Control Request format.
  548. Control requests may or may not have a data payload to write/read.
  549. In cases which it has, the direction bit of the bmRequestType
  550. field is used to infere the desired request direction. For
  551. host to device requests (OUT), data_or_wLength parameter is
  552. the data payload to send, and it must be a sequence type convertible
  553. to an array object. In this case, the return value is the number of data
  554. payload written. For device to host requests (IN), data_or_wLength
  555. is the wLength parameter of the control request specifying the
  556. number of bytes to read in data payload. In this case, the return
  557. value is the data payload read, as an array object.
  558. """
  559. if util.ctrl_direction(bmRequestType) == util.CTRL_OUT:
  560. a = _interop.as_array(data_or_wLength)
  561. elif data_or_wLength is None:
  562. a = 0
  563. else:
  564. a = data_or_wLength
  565. self._ctx.managed_open()
  566. return self._ctx.backend.ctrl_transfer(
  567. self._ctx.handle,
  568. bmRequestType,
  569. bRequest,
  570. wValue,
  571. wIndex,
  572. a,
  573. self.__get_timeout(timeout)
  574. )
  575. def is_kernel_driver_active(self, interface):
  576. r"""Determine if there is kernel driver associated with the interface.
  577. If a kernel driver is active, and the object will be unable to perform I/O.
  578. """
  579. self._ctx.managed_open()
  580. return self._ctx.backend.is_kernel_driver_active(self._ctx.handle, interface)
  581. def detach_kernel_driver(self, interface):
  582. r"""Detach a kernel driver.
  583. If successful, you will then be able to perform I/O.
  584. """
  585. self._ctx.managed_open()
  586. self._ctx.backend.detach_kernel_driver(self._ctx.handle, interface)
  587. def attach_kernel_driver(self, interface):
  588. r"""Re-attach an interface's kernel driver, which was previously
  589. detached using detach_kernel_driver()."""
  590. self._ctx.managed_open()
  591. self._ctx.backend.attach_kernel_driver(self._ctx.handle, interface)
  592. def __iter__(self):
  593. r"""Iterate over all configurations of the device."""
  594. for i in range(self.bNumConfigurations):
  595. yield Configuration(self, i)
  596. def __getitem__(self, index):
  597. r"""Return the Configuration object in the given position."""
  598. return Configuration(self, index)
  599. def __del__(self):
  600. self._ctx.dispose(self)
  601. def __get_timeout(self, timeout):
  602. if timeout is not None:
  603. return timeout
  604. return self.__default_timeout
  605. def __set_def_tmo(self, tmo):
  606. if tmo < 0:
  607. raise ValueError('Timeout cannot be a negative value')
  608. self.__default_timeout = tmo
  609. def __get_def_tmo(self):
  610. return self.__default_timeout
  611. default_timeout = property(
  612. __get_def_tmo,
  613. __set_def_tmo,
  614. doc = 'Default timeout for transfer I/O functions'
  615. )
  616. def find(find_all=False, backend = None, custom_match = None, **args):
  617. r"""Find an USB device and return it.
  618. find() is the function used to discover USB devices.
  619. You can pass as arguments any combination of the
  620. USB Device Descriptor fields to match a device. For example:
  621. find(idVendor=0x3f4, idProduct=0x2009)
  622. will return the Device object for the device with
  623. idVendor Device descriptor field equals to 0x3f4 and
  624. idProduct equals to 0x2009.
  625. If there is more than one device which matchs the criteria,
  626. the first one found will be returned. If a matching device cannot
  627. be found the function returns None. If you want to get all
  628. devices, you can set the parameter find_all to True, then find
  629. will return an list with all matched devices. If no matching device
  630. is found, it will return an empty list. Example:
  631. printers = find(find_all=True, bDeviceClass=7)
  632. This call will get all the USB printers connected to the system.
  633. (actually may be not, because some devices put their class
  634. information in the Interface Descriptor).
  635. You can also use a customized match criteria:
  636. dev = find(custom_match = lambda d: d.idProduct=0x3f4 and d.idvendor=0x2009)
  637. A more accurate printer finder using a customized match would be like
  638. so:
  639. def is_printer(dev):
  640. import usb.util
  641. if dev.bDeviceClass == 7:
  642. return True
  643. for cfg in dev:
  644. if usb.util.find_descriptor(cfg, bInterfaceClass=7) is not None:
  645. return True
  646. printers = find(find_all=True, custom_match = is_printer)
  647. Now even if the device class code is in the interface descriptor the
  648. printer will be found.
  649. You can combine a customized match with device descriptor fields. In this
  650. case, the fields must match and the custom_match must return True. In the our
  651. previous example, if we would like to get all printers belonging to the
  652. manufacturer 0x3f4, the code would be like so:
  653. printers = find(find_all=True, idVendor=0x3f4, custom_match=is_printer)
  654. If you want to use find as a 'list all devices' function, just call
  655. it with find_all = True:
  656. devices = find(find_all=True)
  657. Finally, you may pass a custom backend to the find function:
  658. find(backend = MyBackend())
  659. PyUSB has builtin backends for libusb 0.1, libusb 1.0 and OpenUSB.
  660. If you do not supply a backend explicitly, find() function will select
  661. one of the predefineds backends according to system availability.
  662. Backends are explained in the usb.backend module.
  663. """
  664. def device_iter(k, v):
  665. for dev in backend.enumerate_devices():
  666. d = Device(dev, backend)
  667. if (custom_match is None or custom_match(d)) and \
  668. _interop._reduce(
  669. lambda a, b: a and b,
  670. map(
  671. operator.eq,
  672. v,
  673. map(lambda i: getattr(d, i), k)
  674. ),
  675. True
  676. ):
  677. yield d
  678. if backend is None:
  679. import usb.backend.libusb10 as libusb10
  680. import usb.backend.libusb01 as libusb01
  681. import usb.backend.openusb as openusb
  682. for m in (libusb10, openusb, libusb01):
  683. backend = m.get_backend()
  684. if backend is not None:
  685. _logger.info('find(): using backend "%s"', m.__name__)
  686. break
  687. else:
  688. raise ValueError('No backend available')
  689. k, v = args.keys(), args.values()
  690. if find_all:
  691. return [d for d in device_iter(k, v)]
  692. else:
  693. try:
  694. return _interop._next(device_iter(k, v))
  695. except StopIteration:
  696. return None