connection.py 31 KB

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