adb.py 13 KB

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