adb.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import re
  2. from functools import wraps
  3. import cv2
  4. import numpy as np
  5. import time
  6. from adbutils.errors import AdbError
  7. from lxml import etree
  8. from module.base.decorator import Config
  9. from module.device.connection import Connection
  10. from module.device.method.minitouch import smooth_path
  11. from module.device.method.utils import (RETRY_TRIES, retry_sleep, remove_prefix, handle_adb_error,
  12. ImageTruncated, PackageNotInstalled)
  13. from module.exception import RequestHumanTakeover, ScriptError
  14. from module.logger import logger
  15. def retry(func):
  16. @wraps(func)
  17. def retry_wrapper(self, *args, **kwargs):
  18. """
  19. Args:
  20. self (Adb):
  21. """
  22. init = None
  23. for _ in range(RETRY_TRIES):
  24. try:
  25. if callable(init):
  26. retry_sleep(_)
  27. init()
  28. return func(self, *args, **kwargs)
  29. # Can't handle
  30. except RequestHumanTakeover:
  31. break
  32. # When adb server was killed
  33. except ConnectionResetError as e:
  34. logger.error(e)
  35. def init():
  36. self.adb_reconnect()
  37. # AdbError
  38. except AdbError as e:
  39. if handle_adb_error(e):
  40. def init():
  41. self.adb_reconnect()
  42. else:
  43. break
  44. # Package not installed
  45. except PackageNotInstalled as e:
  46. logger.error(e)
  47. def init():
  48. self.detect_package()
  49. # ImageTruncated
  50. except ImageTruncated as e:
  51. logger.error(e)
  52. def init():
  53. pass
  54. # Unknown
  55. except Exception as e:
  56. logger.exception(e)
  57. def init():
  58. pass
  59. logger.critical(f'Retry {func.__name__}() failed')
  60. raise RequestHumanTakeover
  61. return retry_wrapper
  62. def load_screencap(data):
  63. """
  64. Args:
  65. data: Raw data from `screencap`
  66. Returns:
  67. np.ndarray:
  68. """
  69. # Load data
  70. header = np.frombuffer(data[0:12], dtype=np.uint32)
  71. channel = 4 # screencap sends an RGBA image
  72. width, height, _ = header # Usually to be 1280, 720, 1
  73. image = np.frombuffer(data, dtype=np.uint8)
  74. if image is None:
  75. raise ImageTruncated('Empty image after reading from buffer')
  76. try:
  77. image = image[-int(width * height * channel):].reshape(height, width, channel)
  78. except ValueError as e:
  79. # ValueError: cannot reshape array of size 0 into shape (720,1280,4)
  80. raise ImageTruncated(str(e))
  81. image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
  82. if image is None:
  83. raise ImageTruncated('Empty image after cv2.cvtColor')
  84. return image
  85. class Adb(Connection):
  86. __screenshot_method = [0, 1, 2]
  87. __screenshot_method_fixed = [0, 1, 2]
  88. @staticmethod
  89. def __load_screenshot(screenshot, method):
  90. if method == 0:
  91. pass
  92. elif method == 1:
  93. screenshot = screenshot.replace(b'\r\n', b'\n')
  94. elif method == 2:
  95. screenshot = screenshot.replace(b'\r\r\n', b'\n')
  96. else:
  97. raise ScriptError(f'Unknown method to load screenshots: {method}')
  98. # fix compatibility issues for adb screencap decode problem when the data is from vmos pro
  99. # When use adb screencap for a screenshot from vmos pro, there would be a header more than that from emulator
  100. # which would cause image decode problem. So i check and remove the header there.
  101. screenshot = remove_prefix(screenshot, b'long long=8 fun*=10\n')
  102. image = np.frombuffer(screenshot, np.uint8)
  103. if image is None:
  104. raise ImageTruncated('Empty image after reading from buffer')
  105. image = cv2.imdecode(image, cv2.IMREAD_COLOR)
  106. if image is None:
  107. raise ImageTruncated('Empty image after cv2.imdecode')
  108. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  109. if image is None:
  110. raise ImageTruncated('Empty image after cv2.cvtColor')
  111. return image
  112. def __process_screenshot(self, screenshot):
  113. for method in self.__screenshot_method_fixed:
  114. try:
  115. result = self.__load_screenshot(screenshot, method=method)
  116. self.__screenshot_method_fixed = [method] + self.__screenshot_method
  117. return result
  118. except (OSError, ImageTruncated):
  119. continue
  120. self.__screenshot_method_fixed = self.__screenshot_method
  121. if len(screenshot) < 500:
  122. logger.warning(f'Unexpected screenshot: {screenshot}')
  123. raise OSError(f'cannot load screenshot')
  124. @retry
  125. @Config.when(DEVICE_OVER_HTTP=False)
  126. def screenshot_adb(self):
  127. data = self.adb_shell(['screencap', '-p'], stream=True)
  128. if len(data) < 500:
  129. logger.warning(f'Unexpected screenshot: {data}')
  130. return self.__process_screenshot(data)
  131. @retry
  132. @Config.when(DEVICE_OVER_HTTP=True)
  133. def screenshot_adb(self):
  134. data = self.adb_shell(['screencap'], stream=True)
  135. if len(data) < 500:
  136. logger.warning(f'Unexpected screenshot: {data}')
  137. return load_screencap(data)
  138. @retry
  139. def screenshot_adb_nc(self):
  140. data = self.adb_shell_nc(['screencap'])
  141. if len(data) < 500:
  142. logger.warning(f'Unexpected screenshot: {data}')
  143. return load_screencap(data)
  144. @retry
  145. def click_adb(self, x, y):
  146. start = time.time()
  147. self.adb_shell(['input', 'tap', x, y])
  148. if time.time() - start <= 0.05:
  149. self.sleep(0.05)
  150. @retry
  151. def swipe_adb(self, p1, p2, duration=0.1):
  152. duration = int(duration * 1000)
  153. self.adb_shell(['input', 'swipe', *p1, *p2, duration])
  154. def long_click_adb(self, x: float, y: float, duration: float):
  155. """
  156. :param x:
  157. :param y:
  158. :param duration: 单位是s
  159. :return:
  160. """
  161. if not 0 < duration < 3:
  162. duration = duration / 1000
  163. self.adb_shell(['input', 'swipe', x, y, x, y, int(duration*1000)])
  164. @retry
  165. def app_current_adb(self):
  166. """
  167. Copied from uiautomator2
  168. Returns:
  169. str: Package name.
  170. Raises:
  171. OSError
  172. For developer:
  173. Function reset_uiautomator need this function, so can't use jsonrpc here.
  174. """
  175. # Related issue: https://github.com/openatx/uiautomator2/issues/200
  176. # $ adb shell dumpsys window windows
  177. # Example output:
  178. # mCurrentFocus=Window{41b37570 u0 com.incall.apps.launcher/com.incall.apps.launcher.Launcher}
  179. # mFocusedApp=AppWindowToken{422df168 token=Token{422def98 ActivityRecord{422dee38 u0 com.example/.UI.play.PlayActivity t14}}}
  180. # Regexp
  181. # r'mFocusedApp=.*ActivityRecord{\w+ \w+ (?P<package>.*)/(?P<activity>.*) .*'
  182. # r'mCurrentFocus=Window{\w+ \w+ (?P<package>.*)/(?P<activity>.*)\}')
  183. _focusedRE = re.compile(
  184. r'mCurrentFocus=Window{.*\s+(?P<package>[^\s]+)/(?P<activity>[^\s]+)\}'
  185. )
  186. m = _focusedRE.search(self.adb_shell(['dumpsys', 'window', 'windows']))
  187. if m:
  188. return m.group('package')
  189. # try: adb shell dumpsys activity top
  190. _activityRE = re.compile(
  191. r'ACTIVITY (?P<package>[^\s]+)/(?P<activity>[^/\s]+) \w+ pid=(?P<pid>\d+)'
  192. )
  193. output = self.adb_shell(['dumpsys', 'activity', 'top'])
  194. ms = _activityRE.finditer(output)
  195. ret = None
  196. for m in ms:
  197. ret = m.group('package')
  198. if ret: # get last result
  199. return ret
  200. raise OSError("Couldn't get focused app")
  201. @retry
  202. def app_start_adb(self, package_name=None, allow_failure=False):
  203. """
  204. Args:
  205. package_name (str):
  206. allow_failure (bool):
  207. Returns:
  208. bool: If success to start
  209. """
  210. if not package_name:
  211. package_name = self.package
  212. result = self.adb_shell([
  213. 'monkey', '-p', package_name, '-c',
  214. 'android.intent.category.LAUNCHER', '--pct-syskeys', '0', '1'
  215. ])
  216. if 'No activities found' in result:
  217. # ** No activities found to run, monkey aborted.
  218. if allow_failure:
  219. return False
  220. else:
  221. logger.error(result)
  222. raise PackageNotInstalled(package_name)
  223. elif 'inaccessible' in result:
  224. # /system/bin/sh: monkey: inaccessible or not found
  225. pass
  226. else:
  227. # Events injected: 1
  228. # ## Network stats: elapsed time=4ms (0ms mobile, 0ms wifi, 4ms not connected)
  229. return True
  230. logger.warning('Fallback to use am start')
  231. result = self.adb_shell(['dumpsys', 'package', package_name])
  232. res = re.search(r'android.intent.action.MAIN:\s+\w+ ([\w.\/]+) filter \w+\s+'
  233. r'.*\s+Category: "android.intent.category.LAUNCHER"',
  234. result)
  235. if res:
  236. activity_name = res.group(1)
  237. self.adb_shell(['am', 'start', '-a', 'android.intent.action.MAIN', '-c',
  238. 'android.intent.category.LAUNCHER', '-n', activity_name])
  239. elif 'com.netease.ntunisdk.base.deeplink.UniDeepLinkActivity' in result:
  240. activity_name = 'com.netease.ntunisdk.base.deeplink.UniDeepLinkActivity'
  241. result = self.adb_shell([
  242. 'am', 'start', '-n',
  243. f'{package_name}/com.netease.ntunisdk.base.deeplink.UniDeepLinkActivity'
  244. ])
  245. else:
  246. if allow_failure:
  247. return False
  248. else:
  249. logger.error(result)
  250. raise PackageNotInstalled(package_name)
  251. self.adb_shell(['am', 'start', '-a', 'android.intent.action.MAIN', '-c',
  252. 'android.intent.category.LAUNCHER', '-n', activity_name])
  253. @retry
  254. def app_stop_adb(self, package_name=None):
  255. """ Stop one application: am force-stop"""
  256. if not package_name:
  257. package_name = self.package
  258. self.adb_shell(['am', 'force-stop', package_name])
  259. @retry
  260. def dump_hierarchy_adb(self, temp: str = '/data/local/tmp/hierarchy.xml') -> etree._Element:
  261. """
  262. Args:
  263. temp (str): Temp file store on emulator.
  264. Returns:
  265. etree._Element:
  266. """
  267. # Remove existing file
  268. # self.adb_shell(['rm', '/data/local/tmp/hierarchy.xml'])
  269. # Dump hierarchy
  270. for _ in range(2):
  271. response = self.adb_shell(['uiautomator', 'dump', '--compressed', temp])
  272. if 'hierchary' in response:
  273. # UI hierchary dumped to: /data/local/tmp/hierarchy.xml
  274. break
  275. else:
  276. # <None>
  277. # Must kill uiautomator2
  278. self.app_stop_adb('com.github.uiautomator')
  279. self.app_stop_adb('com.github.uiautomator.test')
  280. continue
  281. # Read from device
  282. content = b''
  283. for chunk in self.adb.sync.iter_content(temp):
  284. if chunk:
  285. content += chunk
  286. else:
  287. break
  288. # Parse with lxml
  289. hierarchy = etree.fromstring(content)
  290. return hierarchy
  291. def draw_adb(self, points: list, interval=0.01):
  292. """
  293. 通过多个点画连续线段,模拟连续触摸绘制
  294. Args:
  295. points: 点的列表,格式为 [(x1, y1), (x2, y2), ...]
  296. interval: 移动间隔时间(秒)
  297. """
  298. if len(points) < 2:
  299. logger.warning('至少需要2个点来画线')
  300. return
  301. # 平滑路径
  302. smooth_points = smooth_path(points)
  303. start_point = smooth_points[0]
  304. # 按下起始点
  305. self.adb_shell(['input', 'motionevent', 'DOWN', str(start_point[0]), str(start_point[1])])
  306. # 移动到后续点
  307. for i, point in enumerate(smooth_points[1:], start=1):
  308. # 给点间隔
  309. time.sleep(interval)
  310. self.adb_shell(['input', 'motionevent', 'MOVE', str(point[0]), str(point[1])])
  311. # 抬起手指
  312. final_point = smooth_points[-1]
  313. self.adb_shell(['input', 'motionevent', 'UP', str(final_point[0]), str(final_point[1])])
  314. if __name__ == "__main__":
  315. adb = Adb(config='oas1')
  316. # logger.info(adb.app_start_adb())
  317. cv2.imshow("iiii", adb.screenshot_adb_nc())
  318. cv2.waitKey(0)