connection.py 31 KB

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