connection.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. # This Python file uses the following encoding: utf-8
  2. import ipaddress
  3. import logging
  4. import platform
  5. import re
  6. import socket
  7. import subprocess
  8. import time
  9. from functools import wraps
  10. import uiautomator2 as u2
  11. from adbutils import AdbClient, AdbDevice, AdbTimeout, ForwardItem, ReverseItem
  12. from adbutils.errors import AdbError
  13. from module.base.decorator import Config, cached_property, del_cached_property
  14. from module.base.utils import ensure_time
  15. from module.device.connection_attr import ConnectionAttr
  16. from module.device.method.utils import (
  17. RETRY_TRIES, remove_shell_warning, retry_sleep,
  18. handle_adb_error, PackageNotInstalled,
  19. recv_all, possible_reasons,
  20. random_port, get_serial_pair)
  21. from module.config.server import set_server
  22. from module.exception import RequestHumanTakeover, EmulatorNotRunningError
  23. from module.logger import logger
  24. from module.map.map_grids import SelectedGrids
  25. def retry(func):
  26. @wraps(func)
  27. def retry_wrapper(self, *args, **kwargs):
  28. """
  29. Args:
  30. self (Adb):
  31. """
  32. init = None
  33. for _ in range(RETRY_TRIES):
  34. try:
  35. if callable(init):
  36. retry_sleep(_)
  37. init()
  38. return func(self, *args, **kwargs)
  39. # Can't handle
  40. except RequestHumanTakeover:
  41. break
  42. # When adb server was killed
  43. except ConnectionResetError as e:
  44. logger.error(e)
  45. def init():
  46. self.adb_reconnect()
  47. # AdbError
  48. except AdbError as e:
  49. if handle_adb_error(e):
  50. def init():
  51. self.adb_reconnect()
  52. else:
  53. break
  54. # Package not installed
  55. except PackageNotInstalled as e:
  56. logger.error(e)
  57. def init():
  58. self.detect_package()
  59. # Unknown, probably a trucked image
  60. except Exception as e:
  61. logger.exception(e)
  62. def init():
  63. pass
  64. logger.critical(f'Retry {func.__name__}() failed')
  65. raise RequestHumanTakeover
  66. return retry_wrapper
  67. class AdbDeviceWithStatus(AdbDevice):
  68. def __init__(self, client: AdbClient, serial: str, status: str):
  69. self.status = status
  70. super().__init__(client, serial)
  71. def __str__(self):
  72. return f'AdbDevice({self.serial}, {self.status})'
  73. __repr__ = __str__
  74. def __bool__(self):
  75. return True
  76. class Connection(ConnectionAttr):
  77. def __init__(self, config):
  78. """
  79. Args:
  80. config (AzurLaneConfig, str): Name of the user config under ./config
  81. """
  82. super().__init__(config)
  83. # 桌面客户端模式:不经过 adb 设备/包检测,包名直接用配置值
  84. if self.is_desktop:
  85. self.package = self.config.script.device.package_name.value
  86. logger.attr('PackageName', self.package)
  87. return
  88. if not self.is_over_http:
  89. self.detect_device()
  90. # Connect
  91. self.adb_connect(self.serial)
  92. logger.attr('AdbDevice', self.adb)
  93. # Package
  94. # self.package = self.config.Emulator_PackageName
  95. self.package = self.config.script.device.package_name.value
  96. if self.package == 'auto':
  97. self.detect_package()
  98. else:
  99. pass
  100. # 因为用不到就注释掉了
  101. # set_server(self.package)
  102. logger.attr('PackageName', self.package)
  103. # logger.attr('Server', self.config.SERVER)
  104. @Config.when(DEVICE_OVER_HTTP=False)
  105. def adb_command(self, cmd, timeout=10):
  106. """
  107. Execute ADB commands in a subprocess,
  108. usually to be used when pulling or pushing large files.
  109. Args:
  110. cmd (list):
  111. timeout (int):
  112. Returns:
  113. str:
  114. """
  115. cmd = list(map(str, cmd))
  116. cmd = [self.adb_binary, '-s', self.serial] + cmd
  117. logger.info(f'Execute: {cmd}')
  118. # Use shell=True to disable console window when using GUI.
  119. # Although, there's still a window when you stop running in GUI, which cause by gooey.
  120. # To disable it, edit gooey/gui/util/taskkill.py
  121. # No gooey anymore, just shell=False
  122. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=False)
  123. try:
  124. stdout, stderr = process.communicate(timeout=timeout)
  125. except subprocess.TimeoutExpired:
  126. process.kill()
  127. stdout, stderr = process.communicate()
  128. logger.warning(f'TimeoutExpired when calling {cmd}, stdout={stdout}, stderr={stderr}')
  129. return stdout
  130. @Config.when(DEVICE_OVER_HTTP=True)
  131. def adb_command(self, cmd, timeout=10):
  132. logger.warning(
  133. f'adb_command() is not available when connecting over http: {self.serial}, '
  134. )
  135. raise RequestHumanTakeover
  136. @Config.when(DEVICE_OVER_HTTP=False)
  137. def adb_shell(self, cmd, stream=False, recvall=True, timeout=10, rstrip=True):
  138. """
  139. Equivalent to `adb -s <serial> shell <*cmd>`
  140. Args:
  141. cmd (list, str):
  142. stream (bool): Return stream instead of string output (Default: False)
  143. recvall (bool): Receive all data when stream=True (Default: True)
  144. timeout (int): (Default: 10)
  145. rstrip (bool): Strip the last empty line (Default: True)
  146. Returns:
  147. str if stream=False
  148. bytes if stream=True and recvall=True
  149. socket if stream=True and recvall=False
  150. """
  151. if not isinstance(cmd, str):
  152. cmd = list(map(str, cmd))
  153. if stream:
  154. result = self.adb.shell(cmd, stream=stream, timeout=timeout, rstrip=rstrip)
  155. if recvall:
  156. # bytes
  157. return recv_all(result)
  158. else:
  159. # socket
  160. return result
  161. else:
  162. result = self.adb.shell(cmd, stream=stream, timeout=timeout, rstrip=rstrip)
  163. result = remove_shell_warning(result)
  164. # str
  165. return result
  166. @Config.when(DEVICE_OVER_HTTP=True)
  167. def adb_shell(self, cmd, stream=False, recvall=True, timeout=10, rstrip=True):
  168. """
  169. Equivalent to http://127.0.0.1:7912/shell?command={command}
  170. Args:
  171. cmd (list, str):
  172. stream (bool): Return stream instead of string output (Default: False)
  173. recvall (bool): Receive all data when stream=True (Default: True)
  174. timeout (int): (Default: 10)
  175. rstrip (bool): Strip the last empty line (Default: True)
  176. Returns:
  177. str if stream=False
  178. bytes if stream=True
  179. """
  180. if not isinstance(cmd, str):
  181. cmd = list(map(str, cmd))
  182. if stream:
  183. result = self.u2.shell(cmd, stream=stream, timeout=timeout)
  184. # Already received all, so `recvall` is ignored
  185. result = remove_shell_warning(result.content)
  186. # bytes
  187. return result
  188. else:
  189. result = self.u2.shell(cmd, stream=stream, timeout=timeout).output
  190. if rstrip:
  191. result = result.rstrip()
  192. result = remove_shell_warning(result)
  193. # str
  194. return result
  195. def adb_getprop(self, name):
  196. """
  197. Get system property in Android, same as `getprop <name>`
  198. Args:
  199. name (str): Property name
  200. Returns:
  201. str:
  202. """
  203. return self.adb_shell(['getprop', name]).strip()
  204. @cached_property
  205. def cpu_abi(self) -> str:
  206. """
  207. Returns:
  208. str: arm64-v8a, armeabi-v7a, x86, x86_64
  209. """
  210. abi = self.adb_shell(['getprop', 'ro.product.cpu.abi']).strip()
  211. if not len(abi):
  212. logger.error(f'CPU ABI invalid: "{abi}"')
  213. return abi
  214. @cached_property
  215. def sdk_ver(self) -> int:
  216. """
  217. Android SDK/API levels, see https://apilevels.com/
  218. """
  219. sdk = self.adb_shell(['getprop', 'ro.build.version.sdk']).strip()
  220. try:
  221. return int(sdk)
  222. except ValueError:
  223. logger.error(f'SDK version invalid: {sdk}')
  224. return 0
  225. @cached_property
  226. def is_avd(self):
  227. if get_serial_pair(self.serial)[0] is None:
  228. return False
  229. if 'ranchu' in self.adb_shell(['getprop', 'ro.hardware']):
  230. return True
  231. if 'goldfish' in self.adb_shell(['getprop', 'ro.hardware.audio.primary']):
  232. return True
  233. return False
  234. @cached_property
  235. def nemud_app_keep_alive(self) -> str:
  236. res = self.adb_getprop('nemud.app_keep_alive')
  237. logger.attr('nemud.app_keep_alive', res)
  238. return res
  239. @cached_property
  240. def is_mumu_over_version_356(self) -> bool:
  241. """
  242. Returns:
  243. bool: If MuMu12 version >= 3.5.6,
  244. which has nemud.app_keep_alive and always be a vertical device
  245. """
  246. return self.nemud_app_keep_alive != ''
  247. @cached_property
  248. def _nc_server_host_port(self):
  249. """
  250. Returns:
  251. str, int, str, int:
  252. server_listen_host, server_listen_port, client_connect_host, client_connect_port
  253. """
  254. # For BlueStacks hyper-v, use ADB reverse
  255. if self.is_bluestacks_hyperv:
  256. host = '127.0.0.1'
  257. logger.info(f'Connecting to BlueStacks hyper-v, using host {host}')
  258. port = self.adb_reverse(f'tcp:{self.config.REVERSE_SERVER_PORT}')
  259. return host, port, host, self.config.REVERSE_SERVER_PORT
  260. # For emulators, listen on current host
  261. if self.is_emulator or self.is_over_http:
  262. try:
  263. host = socket.gethostbyname(socket.gethostname())
  264. except socket.gaierror as e:
  265. logger.error(e)
  266. logger.error(f'Unknown host name: {socket.gethostname()}')
  267. host = '127.0.0.1'
  268. if platform.system() == 'Linux' and host == '127.0.1.1':
  269. host = '127.0.0.1'
  270. logger.info(f'Connecting to local emulator, using host {host}')
  271. port = random_port(self.config.FORWARD_PORT_RANGE)
  272. # For AVD instance
  273. if self.is_avd:
  274. return host, port, "10.0.2.2", port
  275. return host, port, host, port
  276. # For local network devices, listen on the host under the same network as target device
  277. if self.is_network_device:
  278. hosts = socket.gethostbyname_ex(socket.gethostname())[2]
  279. logger.info(f'Current hosts: {hosts}')
  280. ip = ipaddress.ip_address(self.serial.split(':')[0])
  281. for host in hosts:
  282. if ip in ipaddress.ip_interface(f'{host}/24').network:
  283. logger.info(f'Connecting to local network device, using host {host}')
  284. port = random_port(self.config.FORWARD_PORT_RANGE)
  285. return host, port, host, port
  286. # For other devices, create an ADB reverse and listen on 127.0.0.1
  287. host = '127.0.0.1'
  288. logger.info(f'Connecting to unknown device, using host {host}')
  289. port = self.adb_reverse(f'tcp:{self.config.REVERSE_SERVER_PORT}')
  290. return host, port, host, self.config.REVERSE_SERVER_PORT
  291. @cached_property
  292. def reverse_server(self):
  293. """
  294. Setup a server on Alas, access it from emulator.
  295. This will bypass adb shell and be faster.
  296. """
  297. del_cached_property(self, '_nc_server_host_port')
  298. host_port = self._nc_server_host_port
  299. logger.info(f'Reverse server listening on {host_port[0]}:{host_port[1]}, '
  300. f'client can send data to {host_port[2]}:{host_port[3]}')
  301. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  302. server.bind(host_port[:2])
  303. server.settimeout(5)
  304. server.listen(5)
  305. return server
  306. @cached_property
  307. def nc_command(self):
  308. """
  309. Returns:
  310. list[str]: ['nc'] or ['busybox', 'nc']
  311. """
  312. sdk = self.sdk_ver
  313. logger.info(f'sdk_ver: {sdk}')
  314. if sdk >= 28:
  315. # Android 9 emulators does not have `nc`, try `busybox nc`
  316. # BlueStacks Pie (Android 9) has `nc` but cannot send data, try `busybox nc` first
  317. trial = [
  318. ['busybox', 'nc'],
  319. ['nc'],
  320. ]
  321. else:
  322. trial = [
  323. ['nc'],
  324. ['busybox', 'nc'],
  325. ]
  326. for command in trial:
  327. # About 3ms
  328. result = self.adb_shell(command)
  329. # Result should be command help if success
  330. # `/system/bin/sh: nc: not found`
  331. if 'not found' in result:
  332. continue
  333. # `/system/bin/sh: busybox: inaccessible or not found\n`
  334. if 'inaccessible' in result:
  335. continue
  336. logger.attr('nc command', command)
  337. return command
  338. logger.error('No `netcat` command available, please use screenshot methods without `_nc` suffix')
  339. raise RequestHumanTakeover
  340. def adb_shell_nc(self, cmd, timeout=5, chunk_size=262144):
  341. """
  342. Args:
  343. cmd (list):
  344. timeout (int):
  345. chunk_size (int): Default to 262144
  346. Returns:
  347. bytes:
  348. """
  349. # Server start listening
  350. server = self.reverse_server
  351. server.settimeout(timeout)
  352. # Client send data, waiting for server accept
  353. # <command> | nc 127.0.0.1 {port}
  354. cmd += ["|", *self.nc_command, *self._nc_server_host_port[2:]]
  355. stream = self.adb_shell(cmd, stream=True, recvall=False)
  356. try:
  357. # Server accept connection
  358. conn, conn_port = server.accept()
  359. except socket.timeout:
  360. output = recv_all(stream, chunk_size=chunk_size)
  361. logger.warning(str(output))
  362. raise AdbTimeout('reverse server accept timeout')
  363. # Server receive data
  364. data = recv_all(conn, chunk_size=chunk_size, recv_interval=0.001)
  365. # Server close connection
  366. conn.close()
  367. return data
  368. def adb_exec_out(self, cmd, serial=None):
  369. cmd.insert(0, 'exec-out')
  370. return self.adb_command(cmd, serial)
  371. def adb_forward(self, remote):
  372. """
  373. Do `adb forward <local> <remote>`.
  374. choose a random port in FORWARD_PORT_RANGE or reuse an existing forward,
  375. and also remove redundant forwards.
  376. Args:
  377. remote (str):
  378. tcp:<port>
  379. localabstract:<unix domain socket name>
  380. localreserved:<unix domain socket name>
  381. localfilesystem:<unix domain socket name>
  382. dev:<character device name>
  383. jdwp:<process pid> (remote only)
  384. Returns:
  385. int: Port
  386. """
  387. port = 0
  388. for forward in self.adb.forward_list():
  389. if forward.serial == self.serial and forward.remote == remote and forward.local.startswith('tcp:'):
  390. if not port:
  391. logger.info(f'Reuse forward: {forward}')
  392. port = int(forward.local[4:])
  393. else:
  394. logger.info(f'Remove redundant forward: {forward}')
  395. self.adb_forward_remove(forward.local)
  396. if port:
  397. return port
  398. else:
  399. # Create new forward
  400. port = random_port(self.config.FORWARD_PORT_RANGE)
  401. forward = ForwardItem(self.serial, f'tcp:{port}', remote)
  402. logger.info(f'Create forward: {forward}')
  403. self.adb.forward(forward.local, forward.remote)
  404. return port
  405. def adb_reverse(self, remote):
  406. port = 0
  407. for reverse in self.adb.reverse_list():
  408. if reverse.remote == remote and reverse.local.startswith('tcp:'):
  409. if not port:
  410. logger.info(f'Reuse reverse: {reverse}')
  411. port = int(reverse.local[4:])
  412. else:
  413. logger.info(f'Remove redundant forward: {reverse}')
  414. self.adb_forward_remove(reverse.local)
  415. if port:
  416. return port
  417. else:
  418. # Create new reverse
  419. port = random_port(self.config.FORWARD_PORT_RANGE)
  420. reverse = ReverseItem(f'tcp:{port}', remote)
  421. logger.info(f'Create reverse: {reverse}')
  422. self.adb.reverse(reverse.local, reverse.remote)
  423. return port
  424. def adb_forward_remove(self, local):
  425. """
  426. Equivalent to `adb -s <serial> forward --remove <local>`
  427. More about the commands send to ADB server, see:
  428. https://cs.android.com/android/platform/superproject/+/master:packages/modules/adb/SERVICES.TXT
  429. Args:
  430. local (str): Such as 'tcp:2437'
  431. """
  432. with self.adb_client._connect() as c:
  433. list_cmd = f"host-serial:{self.serial}:killforward:{local}"
  434. c.send_command(list_cmd)
  435. c.check_okay()
  436. def adb_reverse_remove(self, local):
  437. """
  438. Equivalent to `adb -s <serial> reverse --remove <local>`
  439. Args:
  440. local (str): Such as 'tcp:2437'
  441. """
  442. with self.adb_client._connect() as c:
  443. c.send_command(f"host:transport:{self.serial}")
  444. c.check_okay()
  445. list_cmd = f"reverse:killforward:{local}"
  446. c.send_command(list_cmd)
  447. c.check_okay()
  448. def adb_push(self, local, remote):
  449. """
  450. Args:
  451. local (str):
  452. remote (str):
  453. Returns:
  454. str:
  455. """
  456. cmd = ['push', local, remote]
  457. return self.adb_command(cmd)
  458. @Config.when(DEVICE_OVER_HTTP=False)
  459. def adb_connect(self, serial):
  460. """
  461. Connect to a serial, try 3 times at max.
  462. If there's an old ADB server running while Alas is using a newer one, which happens on Chinese emulators,
  463. the first connection is used to kill the other one, and the second is the real connect.
  464. Args:
  465. serial (str):
  466. Returns:
  467. bool: If success
  468. """
  469. # Disconnect offline device before connecting
  470. for device in self.list_device():
  471. if device.status == 'offline':
  472. logger.warning(f'Device {serial} is offline, disconnect it before connecting')
  473. self.adb_disconnect(serial)
  474. elif device.status == 'unauthorized':
  475. logger.error(f'Device {serial} is unauthorized, please accept ADB debugging on your device')
  476. elif device.status == 'device':
  477. pass
  478. else:
  479. logger.warning(f'Device {serial} is is having a unknown status: {device.status}')
  480. # Skip for emulator-5554
  481. if 'emulator-' in serial:
  482. logger.info(f'"{serial}" is a `emulator-*` serial, skip adb connect')
  483. return True
  484. if re.match(r'^[a-zA-Z0-9]+$', serial):
  485. logger.info(f'"{serial}" seems to be a Android serial, skip adb connect')
  486. return True
  487. # Try to connect
  488. for _ in range(3):
  489. msg = self.adb_client.connect(serial)
  490. logger.info(msg)
  491. if 'connected' in msg:
  492. # Connected to 127.0.0.1:59865
  493. # Already connected to 127.0.0.1:59865
  494. return True
  495. elif 'bad port' in msg:
  496. # bad port number '598265' in '127.0.0.1:598265'
  497. logger.error(msg)
  498. possible_reasons('Serial incorrect, might be a typo')
  499. raise RequestHumanTakeover
  500. elif '(10061)' in msg:
  501. # cannot connect to 127.0.0.1:55555:
  502. # No connection could be made because the target machine actively refused it. (10061)
  503. logger.info(msg)
  504. logger.warning('No such device exists, please restart the emulator or set a correct serial')
  505. raise EmulatorNotRunningError
  506. # Failed to connect
  507. logger.warning(f'Failed to connect {serial} after 3 trial, assume connected')
  508. self.detect_device()
  509. return False
  510. @Config.when(DEVICE_OVER_HTTP=True)
  511. def adb_connect(self, serial):
  512. # No adb connect if over http
  513. return True
  514. def adb_disconnect(self, serial):
  515. msg = self.adb_client.disconnect(serial)
  516. if msg:
  517. logger.info(msg)
  518. del_cached_property(self, 'hermit_session')
  519. del_cached_property(self, 'droidcast_session')
  520. del_cached_property(self, 'minitouch_builder')
  521. del_cached_property(self, 'reverse_server')
  522. def adb_restart(self):
  523. """
  524. Reboot adb client
  525. """
  526. logger.info('Restart adb')
  527. # Kill current client
  528. self.adb_client.server_kill()
  529. # Init adb client
  530. del_cached_property(self, 'adb_client')
  531. _ = self.adb_client
  532. @Config.when(DEVICE_OVER_HTTP=False)
  533. def adb_reconnect(self):
  534. """
  535. Reboot adb client if no device found, otherwise try reconnecting device.
  536. """
  537. # if self.config.Emulator_AdbRestart and len(self.list_device()) == 0:
  538. if self.config.script.device.adb_restart and len(self.list_device()) == 0:
  539. # Restart Adb
  540. self.adb_restart()
  541. # Connect to device
  542. self.adb_connect(self.serial)
  543. self.detect_device()
  544. else:
  545. self.adb_disconnect(self.serial)
  546. self.adb_connect(self.serial)
  547. self.detect_device()
  548. @Config.when(DEVICE_OVER_HTTP=True)
  549. def adb_reconnect(self):
  550. logger.warning(
  551. f'When connecting a device over http: {self.serial} '
  552. f'adb_reconnect() is skipped, you may need to restart ATX manually'
  553. )
  554. def install_uiautomator2(self):
  555. """
  556. Init uiautomator2 and remove minicap.
  557. """
  558. logger.info('Install uiautomator2')
  559. init = u2.init.Initer(self.adb, loglevel=logging.DEBUG)
  560. # MuMu X has no ro.product.cpu.abi, pick abi from ro.product.cpu.abilist
  561. if init.abi not in ['x86_64', 'x86', 'arm64-v8a', 'armeabi-v7a', 'armeabi']:
  562. init.abi = init.abis[0]
  563. init.set_atx_agent_addr('127.0.0.1:7912')
  564. try:
  565. init.install()
  566. except ConnectionError:
  567. u2.init.GITHUB_BASEURL = 'http://tool.appetizer.io/openatx'
  568. init.install()
  569. self.uninstall_minicap()
  570. def uninstall_minicap(self):
  571. """ minicap can't work or will send compressed images on some emulators. """
  572. logger.info('Removing minicap')
  573. self.adb_shell(["rm", "/data/local/tmp/minicap"])
  574. self.adb_shell(["rm", "/data/local/tmp/minicap.so"])
  575. @Config.when(DEVICE_OVER_HTTP=False)
  576. def restart_atx(self):
  577. """
  578. Minitouch supports only one connection at a time.
  579. Restart ATX to kick the existing one.
  580. """
  581. logger.info('Restart ATX')
  582. atx_agent_path = '/data/local/tmp/atx-agent'
  583. self.adb_shell([atx_agent_path, 'server', '--stop'])
  584. self.adb_shell([atx_agent_path, 'server', '--nouia', '-d', '--addr', '127.0.0.1:7912'])
  585. @Config.when(DEVICE_OVER_HTTP=True)
  586. def restart_atx(self):
  587. logger.warning(
  588. f'When connecting a device over http: {self.serial} '
  589. f'restart_atx() is skipped, you may need to restart ATX manually'
  590. )
  591. @staticmethod
  592. def sleep(second):
  593. """
  594. Args:
  595. second(int, float, tuple):
  596. """
  597. time.sleep(ensure_time(second))
  598. _orientation_description = {
  599. 0: 'Normal',
  600. 1: 'HOME key on the right',
  601. 2: 'HOME key on the top',
  602. 3: 'HOME key on the left',
  603. }
  604. orientation = 0
  605. @retry
  606. def get_orientation(self):
  607. """
  608. Rotation of the phone
  609. Returns:
  610. int:
  611. 0: 'Normal'
  612. 1: 'HOME key on the right'
  613. 2: 'HOME key on the top'
  614. 3: 'HOME key on the left'
  615. """
  616. # 桌面模式:窗口即横屏,方向恒为 0(Normal),不经过 adb dumpsys
  617. if self.is_desktop:
  618. self.orientation = 0
  619. return 0
  620. _DISPLAY_RE = re.compile(
  621. r'.*DisplayViewport{.*valid=true, .*orientation=(?P<orientation>\d+), .*deviceWidth=(?P<width>\d+), deviceHeight=(?P<height>\d+).*'
  622. )
  623. output = self.adb_shell(['dumpsys', 'display'])
  624. res = _DISPLAY_RE.search(output, 0)
  625. if res:
  626. o = int(res.group('orientation'))
  627. if o in Connection._orientation_description:
  628. pass
  629. else:
  630. o = 0
  631. logger.warning(f'Invalid device orientation: {o}, assume it is normal')
  632. else:
  633. o = 0
  634. logger.warning('Unable to get device orientation, assume it is normal')
  635. self.orientation = o
  636. logger.attr('Device Orientation', f'{o} ({Connection._orientation_description.get(o, "Unknown")})')
  637. return o
  638. @retry
  639. def list_device(self):
  640. """
  641. Returns:
  642. SelectedGrids[AdbDeviceWithStatus]:
  643. """
  644. devices = []
  645. try:
  646. with self.adb_client._connect() as c:
  647. c.send_command("host:devices")
  648. c.check_okay()
  649. output = c.read_string_block()
  650. logger.debug(output)
  651. for line in output.splitlines():
  652. parts = line.strip().split("\t")
  653. if len(parts) != 2:
  654. continue
  655. device = AdbDeviceWithStatus(self.adb_client, parts[0], parts[1])
  656. devices.append(device)
  657. except ConnectionResetError as e:
  658. # Happens only on CN users.
  659. # ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。
  660. logger.error(e)
  661. if '强迫关闭' in str(e):
  662. logger.critical('无法连接至ADB服务,请关闭UU加速器、原神私服、以及一些劣质代理软件。'
  663. '它们会劫持电脑上所有的网络连接,包括Alas与模拟器之间的本地连接。')
  664. return SelectedGrids(devices)
  665. def detect_device(self):
  666. """
  667. Find available devices
  668. If serial=='auto' and only 1 device detected, use it
  669. """
  670. logger.hr('Detect device')
  671. logger.info('Here are the available devices, '
  672. 'copy to Alas.Emulator.Serial to use it or set Alas.Emulator.Serial="auto"')
  673. devices = self.list_device()
  674. # Show available devices
  675. available = devices.select(status='device')
  676. for device in available:
  677. logger.info(device.serial)
  678. if not len(available):
  679. logger.info('No available devices')
  680. # Show unavailable devices if having any
  681. unavailable = devices.delete(available)
  682. if len(unavailable):
  683. logger.info('Here are the devices detected but unavailable')
  684. for device in unavailable:
  685. logger.info(f'{device.serial} ({device.status})')
  686. # Auto device detection
  687. if self.config.script.device.serial == 'auto':
  688. # if self.config.Emulator_Serial == 'auto':
  689. if available.count == 0:
  690. logger.critical('No available device found, auto device detection cannot work, '
  691. 'please set an exact serial in Alas.Emulator.Serial instead of using "auto"')
  692. raise RequestHumanTakeover
  693. elif available.count == 1:
  694. logger.info(f'Auto device detection found only one device, using it')
  695. self.serial = devices[0].serial
  696. del_cached_property(self, 'adb')
  697. else:
  698. logger.critical('Multiple devices found, auto device detection cannot decide which to choose, '
  699. 'please copy one of the available devices listed above to Alas.Emulator.Serial')
  700. raise RequestHumanTakeover
  701. # Handle LDPlayer
  702. # LDPlayer serial jumps between `127.0.0.1:5555+{X}` and `emulator-5554+{X}`
  703. port_serial, emu_serial = get_serial_pair(self.serial)
  704. if port_serial and emu_serial:
  705. # Might be LDPlayer, check connected devices
  706. port_device = devices.select(serial=port_serial).first_or_none()
  707. emu_device = devices.select(serial=emu_serial).first_or_none()
  708. if port_device and emu_device:
  709. # Paired devices found, check status to get the correct one
  710. if port_device.status == 'device' and emu_device.status == 'offline':
  711. self.serial = port_serial
  712. logger.info(f'LDPlayer device pair found: {port_device}, {emu_device}. '
  713. f'Using serial: {self.serial}')
  714. elif port_device.status == 'offline' and emu_device.status == 'device':
  715. self.serial = emu_serial
  716. logger.info(f'LDPlayer device pair found: {port_device}, {emu_device}. '
  717. f'Using serial: {self.serial}')
  718. elif not devices.select(serial=self.serial):
  719. # Current serial not found
  720. if port_device and not emu_device:
  721. logger.info(f'Current serial {self.serial} not found but paired device {port_serial} found. '
  722. f'Using serial: {port_serial}')
  723. self.serial = port_serial
  724. if not port_device and emu_device:
  725. logger.info(f'Current serial {self.serial} not found but paired device {emu_serial} found. '
  726. f'Using serial: {emu_serial}')
  727. self.serial = emu_serial
  728. @retry
  729. def list_package(self, show_log=True):
  730. """
  731. Find all packages on device.
  732. Use dumpsys first for faster.
  733. """
  734. # 80ms
  735. if show_log:
  736. logger.info('Get package list')
  737. output = self.adb_shell(r'dumpsys package | grep "Package \["')
  738. packages = re.findall(r'Package \[([^\s]+)\]', output)
  739. if len(packages):
  740. return packages
  741. # 200ms
  742. if show_log:
  743. logger.info('Get package list')
  744. output = self.adb_shell(['pm', 'list', 'packages'])
  745. packages = re.findall(r'package:([^\s]+)', output)
  746. return packages
  747. def list_app_packages(self, keywords=('onmyoji', 'yys'), show_log=True):
  748. """
  749. Args:
  750. keywords:
  751. show_log:
  752. Returns:
  753. list[str]: List of package names
  754. """
  755. packages = self.list_package(show_log=show_log)
  756. packages = [p for p in packages if any([k in p.lower() for k in keywords])]
  757. return packages
  758. # def list_known_packages(self, show_log=True):
  759. # """
  760. # Args:
  761. # show_log:
  762. #
  763. # Returns:
  764. # list[str]: List of package names
  765. # """
  766. # packages = self.list_package(show_log=show_log)
  767. # packages = [p for p in packages if p in server_.VALID_PACKAGE or p in server_.VALID_CLOUD_PACKAGE]
  768. # return packages
  769. def detect_package(self, keywords=('onmyoji', 'yys'), set_config=True):
  770. """
  771. Show all possible packages with the given keyword on this device.
  772. """
  773. logger.hr('Detect package')
  774. packages = self.list_app_packages(keywords=keywords)
  775. # Show packages
  776. logger.info(f'Here are the available packages in device "{self.serial}", '
  777. f'copy to Alas.Emulator.PackageName to use it')
  778. if len(packages):
  779. for package in packages:
  780. logger.info(package)
  781. else:
  782. logger.info(f'No available packages on device "{self.serial}"')
  783. # Auto package detection
  784. if len(packages) == 0:
  785. logger.critical(f'No {keywords[0]} package found, '
  786. f'please confirm {keywords[0]} has been installed on device "{self.serial}"')
  787. raise RequestHumanTakeover
  788. if len(packages) == 1:
  789. logger.info('Auto package detection found only one package, using it')
  790. self.package = packages[0]
  791. # Set config
  792. if set_config:
  793. self.config.Emulator_PackageName = self.package
  794. # Set server
  795. logger.info('Server changed, release resources')
  796. set_server(self.package)
  797. else:
  798. logger.critical(
  799. f'Multiple {keywords[0]} packages found, auto package detection cannot decide which to choose, '
  800. 'please copy one of the available devices listed above to Alas.Emulator.PackageName')
  801. raise RequestHumanTakeover