util.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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.util - Utility functions.
  29. This module exports:
  30. endpoint_address - return the endpoint absolute address.
  31. endpoint_direction - return the endpoint transfer direction.
  32. endpoint_type - return the endpoint type
  33. ctrl_direction - return the direction of a control transfer
  34. build_request_type - build a bmRequestType field of a control transfer.
  35. find_descriptor - find an inner descriptor.
  36. claim_interface - explicitly claim an interface.
  37. release_interface - explicitly release an interface.
  38. dispose_resources - release internal resources allocated by the object.
  39. get_string - retrieve a string descriptor from the device.
  40. """
  41. __author__ = 'Wander Lairson Costa'
  42. import operator
  43. import usb._interop as _interop
  44. # descriptor type
  45. DESC_TYPE_DEVICE = 0x01
  46. DESC_TYPE_CONFIG = 0x02
  47. DESC_TYPE_STRING = 0x03
  48. DESC_TYPE_INTERFACE = 0x04
  49. DESC_TYPE_ENDPOINT = 0x05
  50. # endpoint direction
  51. ENDPOINT_IN = 0x80
  52. ENDPOINT_OUT = 0x00
  53. # endpoint type
  54. ENDPOINT_TYPE_CTRL = 0x00
  55. ENDPOINT_TYPE_ISO = 0x01
  56. ENDPOINT_TYPE_BULK = 0x02
  57. ENDPOINT_TYPE_INTR = 0x03
  58. # control request type
  59. CTRL_TYPE_STANDARD = (0 << 5)
  60. CTRL_TYPE_CLASS = (1 << 5)
  61. CTRL_TYPE_VENDOR = (2 << 5)
  62. CTRL_TYPE_RESERVED = (3 << 5)
  63. # control request recipient
  64. CTRL_RECIPIENT_DEVICE = 0
  65. CTRL_RECIPIENT_INTERFACE = 1
  66. CTRL_RECIPIENT_ENDPOINT = 2
  67. CTRL_RECIPIENT_OTHER = 3
  68. # control request direction
  69. CTRL_OUT = 0x00
  70. CTRL_IN = 0x80
  71. _ENDPOINT_ADDR_MASK = 0x0f
  72. _ENDPOINT_DIR_MASK = 0x80
  73. _ENDPOINT_TRANSFER_TYPE_MASK = 0x03
  74. _CTRL_DIR_MASK = 0x80
  75. def endpoint_address(address):
  76. r"""Return the endpoint absolute address.
  77. The address parameter is the bEndpointAddress field
  78. of the endpoint descriptor.
  79. """
  80. return address & _ENDPOINT_ADDR_MASK
  81. def endpoint_direction(address):
  82. r"""Return the endpoint direction.
  83. The address parameter is the bEndpointAddress field
  84. of the endpoint descriptor.
  85. The possible return values are ENDPOINT_OUT or ENDPOINT_IN.
  86. """
  87. return address & _ENDPOINT_DIR_MASK
  88. def endpoint_type(bmAttributes):
  89. r"""Return the transfer type of the endpoint.
  90. The bmAttributes parameter is the bmAttributes field
  91. of the endpoint descriptor.
  92. The possible return values are: ENDPOINT_TYPE_CTRL,
  93. ENDPOINT_TYPE_ISO, ENDPOINT_TYPE_BULK or ENDPOINT_TYPE_INTR.
  94. """
  95. return bmAttributes & _ENDPOINT_TRANSFER_TYPE_MASK
  96. def ctrl_direction(bmRequestType):
  97. r"""Return the direction of a control request.
  98. The bmRequestType parameter is the value of the
  99. bmRequestType field of a control transfer.
  100. The possible return values are CTRL_OUT or CTRL_IN.
  101. """
  102. return bmRequestType & _CTRL_DIR_MASK
  103. def build_request_type(direction, type, recipient):
  104. r"""Build a bmRequestType field for control requests.
  105. These is a conventional function to build a bmRequestType
  106. for a control request.
  107. The direction parameter can be CTRL_OUT or CTRL_IN.
  108. The type parameter can be CTRL_TYPE_STANDARD, CTRL_TYPE_CLASS,
  109. CTRL_TYPE_VENDOR or CTRL_TYPE_RESERVED values.
  110. The recipient can be CTRL_RECIPIENT_DEVICE, CTRL_RECIPIENT_INTERFACE,
  111. CTRL_RECIPIENT_ENDPOINT or CTRL_RECIPIENT_OTHER.
  112. Return the bmRequestType value.
  113. """
  114. return recipient | type | direction
  115. def find_descriptor(desc, find_all=False, custom_match=None, **args):
  116. r"""Find an inner descriptor.
  117. find_descriptor works in the same way the core.find() function does,
  118. but it acts on general descriptor objects. For example, suppose you
  119. have a Device object called dev and want a Configuration of this
  120. object with its bConfigurationValue equals to 1, the code would
  121. be like so:
  122. >>> cfg = util.find_descriptor(dev, bConfigurationValue=1)
  123. You can use any field of the Descriptor as a match criteria, and you
  124. can supply a customized match just like core.find() does. The
  125. find_descriptor function also accepts the find_all parameter to get
  126. a list of descriptor instead of just one.
  127. """
  128. def desc_iter(k, v):
  129. for d in desc:
  130. if (custom_match is None or custom_match(d)) and \
  131. _interop._reduce(
  132. lambda a, b: a and b,
  133. map(
  134. operator.eq,
  135. v,
  136. map(lambda i: getattr(d, i), k)
  137. ),
  138. True
  139. ):
  140. yield d
  141. k, v = args.keys(), args.values()
  142. if find_all:
  143. return [d for d in desc_iter(k, v)]
  144. else:
  145. try:
  146. return _interop._next(desc_iter(k, v))
  147. except StopIteration:
  148. return None
  149. def claim_interface(device, interface):
  150. r"""Explicitly claim an interface.
  151. PyUSB users normally do not have to worry about interface claiming,
  152. as the library takes care of it automatically. But there are situations
  153. where you need deterministic interface claiming. For these uncommon
  154. cases, you can use claim_interface.
  155. If the interface is already claimed, either through a previously call
  156. to claim_interface or internally by the device object, nothing happens.
  157. """
  158. device._ctx.managed_claim_interface(device, interface)
  159. def release_interface(device, interface):
  160. r"""Explicitly release an interface.
  161. This function is used to release an interface previously claimed,
  162. either through a call to claim_interface or internally by the
  163. device object.
  164. Normally, you do not need to worry about claiming policies, as
  165. the device object takes care of it automatically.
  166. """
  167. device._ctx.managed_release_interface(device, interface)
  168. def dispose_resources(device):
  169. r"""Release internal resources allocated by the object.
  170. Sometimes you need to provide deterministic resources
  171. freeing, for example to allow another application to
  172. talk to the device. As Python does not provide deterministic
  173. destruction, this function releases all internal resources
  174. allocated by the device, like device handle and interface
  175. policy.
  176. After calling this function, you can continue using the device
  177. object normally. If the resources will be necessary again, it
  178. will allocate them automatically.
  179. """
  180. device._ctx.dispose(device)
  181. def get_string(dev, length, index, langid = None):
  182. r"""Retrieve a string descriptor from the device.
  183. dev is the Device object to which the request will be
  184. sent to.
  185. length is the length of string in number of characters.
  186. index is the string descriptor index and langid is the Language
  187. ID of the descriptor. If langid is omitted, the string descriptor
  188. of the first Language ID will be returned.
  189. The return value is the unicode string present in the descriptor.
  190. """
  191. from usb.control import get_descriptor
  192. if langid is None:
  193. # Asking for the zero'th index is special - it returns a string
  194. # descriptor that contains all the language IDs supported by the device.
  195. # Typically there aren't many - often only one. The language IDs are 16
  196. # bit numbers, and they start at the third byte in the descriptor. See
  197. # USB 2.0 specification section 9.6.7 for more information.
  198. #
  199. # Note from libusb 1.0 sources (descriptor.c)
  200. buf = get_descriptor(
  201. dev,
  202. 1024,
  203. DESC_TYPE_STRING,
  204. 0
  205. )
  206. assert len(buf) >= 4
  207. langid = buf[2] | (buf[3] << 8)
  208. buf = get_descriptor(
  209. dev,
  210. length * 2 + 2, # string is utf16 + 2 bytes of the descriptor
  211. DESC_TYPE_STRING,
  212. index,
  213. langid
  214. )
  215. return buf[2:].tostring().decode('utf-16-le')