common.py 14 KB

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