connection.py 32 KB

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