connection.py 31 KB

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