common.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # Copyright 2014 Google Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Common code for ADB and Fastboot.
  15. Common usb browsing, and usb communication.
  16. """
  17. import logging
  18. import platform
  19. import socket
  20. import threading
  21. import weakref
  22. import select
  23. import libusb1
  24. import usb1
  25. from adb import usb_exceptions
  26. DEFAULT_TIMEOUT_MS = 10000
  27. _LOG = logging.getLogger('android_usb')
  28. def GetInterface(setting):
  29. """Get the class, subclass, and protocol for the given USB setting."""
  30. return (setting.getClass(), setting.getSubClass(), setting.getProtocol())
  31. def InterfaceMatcher(clazz, subclass, protocol):
  32. """Returns a matcher that returns the setting with the given interface."""
  33. interface = (clazz, subclass, protocol)
  34. def Matcher(device):
  35. for setting in device.iterSettings():
  36. if GetInterface(setting) == interface:
  37. return setting
  38. return Matcher
  39. class UsbHandle(object):
  40. """USB communication object. Not thread-safe.
  41. Handles reading and writing over USB with the proper endpoints, exceptions,
  42. and interface claiming.
  43. Important methods:
  44. FlushBuffers()
  45. BulkRead(int length)
  46. BulkWrite(bytes data)
  47. """
  48. _HANDLE_CACHE = weakref.WeakValueDictionary()
  49. _HANDLE_CACHE_LOCK = threading.Lock()
  50. def __init__(self, device, setting, usb_info=None, timeout_ms=None):
  51. """Initialize USB Handle.
  52. Arguments:
  53. device: libusb_device to connect to.
  54. setting: libusb setting with the correct endpoints to communicate with.
  55. usb_info: String describing the usb path/serial/device, for debugging.
  56. timeout_ms: Timeout in milliseconds for all I/O.
  57. """
  58. self._setting = setting
  59. self._device = device
  60. self._handle = None
  61. self._usb_info = usb_info or ''
  62. self._timeout_ms = timeout_ms if timeout_ms else DEFAULT_TIMEOUT_MS
  63. self._max_read_packet_len = 0
  64. @property
  65. def usb_info(self):
  66. try:
  67. sn = self.serial_number
  68. except libusb1.USBError:
  69. sn = ''
  70. if sn and sn != self._usb_info:
  71. return '%s %s' % (self._usb_info, sn)
  72. return self._usb_info
  73. def Open(self):
  74. """Opens the USB device for this setting, and claims the interface."""
  75. # Make sure we close any previous handle open to this usb device.
  76. port_path = tuple(self.port_path)
  77. with self._HANDLE_CACHE_LOCK:
  78. old_handle = self._HANDLE_CACHE.get(port_path)
  79. if old_handle is not None:
  80. old_handle.Close()
  81. self._read_endpoint = None
  82. self._write_endpoint = None
  83. for endpoint in self._setting.iterEndpoints():
  84. address = endpoint.getAddress()
  85. if address & libusb1.USB_ENDPOINT_DIR_MASK:
  86. self._read_endpoint = address
  87. self._max_read_packet_len = endpoint.getMaxPacketSize()
  88. else:
  89. self._write_endpoint = address
  90. assert self._read_endpoint is not None
  91. assert self._write_endpoint is not None
  92. handle = self._device.open()
  93. iface_number = self._setting.getNumber()
  94. try:
  95. if (platform.system() != 'Windows'
  96. and handle.kernelDriverActive(iface_number)):
  97. handle.detachKernelDriver(iface_number)
  98. except libusb1.USBError as e:
  99. if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
  100. _LOG.warning('Kernel driver not found for interface: %s.', iface_number)
  101. else:
  102. raise
  103. handle.claimInterface(iface_number)
  104. self._handle = handle
  105. self._interface_number = iface_number
  106. with self._HANDLE_CACHE_LOCK:
  107. self._HANDLE_CACHE[port_path] = self
  108. # When this object is deleted, make sure it's closed.
  109. weakref.ref(self, self.Close)
  110. @property
  111. def serial_number(self):
  112. return self._device.getSerialNumber()
  113. @property
  114. def port_path(self):
  115. return [self._device.getBusNumber()] + self._device.getPortNumberList()
  116. def Close(self):
  117. if self._handle is None:
  118. return
  119. try:
  120. self._handle.releaseInterface(self._interface_number)
  121. self._handle.close()
  122. except libusb1.USBError:
  123. _LOG.info('USBError while closing handle %s: ',
  124. self.usb_info, exc_info=True)
  125. finally:
  126. self._handle = None
  127. def Timeout(self, timeout_ms):
  128. return timeout_ms if timeout_ms is not None else self._timeout_ms
  129. def FlushBuffers(self):
  130. while True:
  131. try:
  132. self.BulkRead(self._max_read_packet_len, timeout_ms=10)
  133. except usb_exceptions.ReadFailedError as e:
  134. if e.usb_error.value == libusb1.LIBUSB_ERROR_TIMEOUT:
  135. break
  136. raise
  137. def BulkWrite(self, data, timeout_ms=None):
  138. if self._handle is None:
  139. raise usb_exceptions.WriteFailedError(
  140. 'This handle has been closed, probably due to another being opened.',
  141. None)
  142. try:
  143. return self._handle.bulkWrite(
  144. self._write_endpoint, data, timeout=self.Timeout(timeout_ms))
  145. except libusb1.USBError as e:
  146. raise usb_exceptions.WriteFailedError(
  147. 'Could not send data to %s (timeout %sms)' % (
  148. self.usb_info, self.Timeout(timeout_ms)), e)
  149. def BulkRead(self, length, timeout_ms=None):
  150. if self._handle is None:
  151. raise usb_exceptions.ReadFailedError(
  152. 'This handle has been closed, probably due to another being opened.',
  153. None)
  154. try:
  155. # python-libusb1 > 1.6 exposes bytearray()s now instead of bytes/str.
  156. # To support older and newer versions, we ensure everything's bytearray()
  157. # from here on out.
  158. return bytearray(self._handle.bulkRead(
  159. self._read_endpoint, length, timeout=self.Timeout(timeout_ms)))
  160. except libusb1.USBError as e:
  161. raise usb_exceptions.ReadFailedError(
  162. 'Could not receive data from %s (timeout %sms)' % (
  163. self.usb_info, self.Timeout(timeout_ms)), e)
  164. def BulkReadAsync(self, length, timeout_ms=None):
  165. # See: https://pypi.python.org/pypi/libusb1 "Asynchronous I/O" section
  166. return
  167. @classmethod
  168. def PortPathMatcher(cls, port_path):
  169. """Returns a device matcher for the given port path."""
  170. if isinstance(port_path, str):
  171. # Convert from sysfs path to port_path.
  172. port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]
  173. return lambda device: device.port_path == port_path
  174. @classmethod
  175. def SerialMatcher(cls, serial):
  176. """Returns a device matcher for the given serial."""
  177. return lambda device: device.serial_number == serial
  178. @classmethod
  179. def FindAndOpen(cls, setting_matcher,
  180. port_path=None, serial=None, timeout_ms=None):
  181. dev = cls.Find(
  182. setting_matcher, port_path=port_path, serial=serial,
  183. timeout_ms=timeout_ms)
  184. dev.Open()
  185. dev.FlushBuffers()
  186. return dev
  187. @classmethod
  188. def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
  189. """Gets the first device that matches according to the keyword args."""
  190. if port_path:
  191. device_matcher = cls.PortPathMatcher(port_path)
  192. usb_info = port_path
  193. elif serial:
  194. device_matcher = cls.SerialMatcher(serial)
  195. usb_info = serial
  196. else:
  197. device_matcher = None
  198. usb_info = 'first'
  199. return cls.FindFirst(setting_matcher, device_matcher,
  200. usb_info=usb_info, timeout_ms=timeout_ms)
  201. @classmethod
  202. def FindFirst(cls, setting_matcher, device_matcher=None, **kwargs):
  203. """Find and return the first matching device.
  204. Args:
  205. setting_matcher: See cls.FindDevices.
  206. device_matcher: See cls.FindDevices.
  207. **kwargs: See cls.FindDevices.
  208. Returns:
  209. An instance of UsbHandle.
  210. Raises:
  211. DeviceNotFoundError: Raised if the device is not available.
  212. """
  213. try:
  214. return next(cls.FindDevices(
  215. setting_matcher, device_matcher=device_matcher, **kwargs))
  216. except StopIteration:
  217. raise usb_exceptions.DeviceNotFoundError(
  218. 'No device available, or it is in the wrong configuration.')
  219. @classmethod
  220. def FindDevices(cls, setting_matcher, device_matcher=None,
  221. usb_info='', timeout_ms=None):
  222. """Find and yield the devices that match.
  223. Args:
  224. setting_matcher: Function that returns the setting to use given a
  225. usb1.USBDevice, or None if the device doesn't have a valid setting.
  226. device_matcher: Function that returns True if the given UsbHandle is
  227. valid. None to match any device.
  228. usb_info: Info string describing device(s).
  229. timeout_ms: Default timeout of commands in milliseconds.
  230. Yields:
  231. UsbHandle instances
  232. """
  233. ctx = usb1.USBContext()
  234. for device in ctx.getDeviceList(skip_on_error=True):
  235. setting = setting_matcher(device)
  236. if setting is None:
  237. continue
  238. handle = cls(device, setting, usb_info=usb_info, timeout_ms=timeout_ms)
  239. if device_matcher is None or device_matcher(handle):
  240. yield handle
  241. class TcpHandle(object):
  242. """TCP connection object.
  243. Provides same interface as UsbHandle. """
  244. def __init__(self, serial, timeout_ms=None):
  245. """Initialize the TCP Handle.
  246. Arguments:
  247. serial: Android device serial of the form host or host:port.
  248. Host may be an IP address or a host name.
  249. """
  250. # if necessary, convert serial to a unicode string
  251. if isinstance(serial, (bytes, bytearray)):
  252. serial = serial.decode('utf-8')
  253. if ':' in serial:
  254. self.host, self.port = serial.split(':')
  255. else:
  256. self.host = serial
  257. self.port = "5555"
  258. self._connection = None
  259. self._serial_number = '%s:%s' % (self.host, self.port)
  260. self._timeout_ms = float(timeout_ms) if timeout_ms else None
  261. self._connect()
  262. def _connect(self):
  263. timeout = self.TimeoutSeconds(self._timeout_ms)
  264. self._connection = socket.create_connection((self.host, self.port),
  265. timeout=timeout)
  266. if timeout:
  267. self._connection.setblocking(0)
  268. @property
  269. def serial_number(self):
  270. return self._serial_number
  271. def BulkWrite(self, data, timeout=None):
  272. t = self.TimeoutSeconds(timeout)
  273. _, writeable, _ = select.select([], [self._connection], [], t)
  274. if writeable:
  275. return self._connection.send(data)
  276. msg = 'Sending data to {} timed out after {}s. No data was sent.'.format(
  277. self.serial_number, t)
  278. raise usb_exceptions.TcpTimeoutException(msg)
  279. def BulkRead(self, numbytes, timeout=None):
  280. t = self.TimeoutSeconds(timeout)
  281. readable, _, _ = select.select([self._connection], [], [], t)
  282. if readable:
  283. return self._connection.recv(numbytes)
  284. msg = 'Reading from {} timed out (Timeout {}s)'.format(
  285. self._serial_number, t)
  286. raise usb_exceptions.TcpTimeoutException(msg)
  287. def Timeout(self, timeout_ms):
  288. return float(timeout_ms) if timeout_ms is not None else self._timeout_ms
  289. def TimeoutSeconds(self, timeout_ms):
  290. timeout = self.Timeout(timeout_ms)
  291. return timeout / 1000.0 if timeout is not None else timeout
  292. def Close(self):
  293. return self._connection.close()