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