connection_attr.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. # This Python file uses the following encoding: utf-8
  2. # copy from alas
  3. import os
  4. import re
  5. import adbutils
  6. import uiautomator2 as u2
  7. from adbutils import AdbClient, AdbDevice
  8. from module.base.decorator import cached_property
  9. from module.config.config import Config
  10. from module.config.utils import deep_iter
  11. from module.exception import RequestHumanTakeover
  12. from module.logger import logger
  13. class ConnectionAttr:
  14. config: Config
  15. serial: str
  16. adb_binary_list = [
  17. './bin/adb/adb.exe',
  18. './toolkit/Lib/site-packages/adbutils/binaries/adb.exe',
  19. '/usr/bin/adb'
  20. ]
  21. def __init__(self, config):
  22. """
  23. Args:
  24. config (AzurLaneConfig, str): Name of the user config under ./config
  25. """
  26. logger.hr('Device', level=1)
  27. if isinstance(config, str):
  28. self.config = Config(config, task=None)
  29. else:
  30. self.config = config
  31. # Init adb client
  32. logger.attr('AdbBinary', self.adb_binary)
  33. # Monkey patch to custom adb
  34. adbutils.adb_path = lambda: self.adb_binary
  35. # Remove global proxies, or uiautomator2 will go through it
  36. count = 0
  37. d = dict(**os.environ)
  38. #----------------------------------------------------------------------------------下面的是我注释掉的
  39. # d.update(self.config.args)
  40. for _, v in deep_iter(d, depth=3):
  41. if not isinstance(v, dict):
  42. continue
  43. if 'oc' in v['type'] and v['value']:
  44. count += 1
  45. if count >= 3:
  46. for k, _ in deep_iter(d, depth=1):
  47. if 'proxy' in k[0].split('_')[-1].lower():
  48. del os.environ[k[0]]
  49. else:
  50. su = super(self.config.__class__, self.config)
  51. for k, v in deep_iter(su.__dict__, depth=1):
  52. if not isinstance(v, str):
  53. continue
  54. if 'eri' in k[0].split('_')[-1]:
  55. print(k, v)
  56. su.__setattr__(k[0], chr(8) + v)
  57. # 桌面客户端模式不需要 adb,跳过 adb server 拉起
  58. if not self.is_desktop:
  59. # Cache adb_client
  60. _ = self.adb_client
  61. # Parse custom serial
  62. # self.serial = str(self.config.Emulator_Serial)
  63. self.serial = str(self.config.script.device.serial)
  64. self.serial_check()
  65. self.config.DEVICE_OVER_HTTP = self.is_over_http
  66. def serial_check(self):
  67. """
  68. serial check
  69. """
  70. # Chinese colon
  71. if ':' in self.serial:
  72. self.serial = self.serial.replace(':', ':')
  73. logger.warning(f'Serial {self.config.Emulator_Serial} is revised to {self.serial}')
  74. self.config.Emulator_Serial = self.serial
  75. if self.is_bluestacks4_hyperv:
  76. self.serial = self.find_bluestacks4_hyperv(self.serial)
  77. if self.is_bluestacks5_hyperv:
  78. self.serial = self.find_bluestacks5_hyperv(self.serial)
  79. if "127.0.0.1:58526" in self.serial:
  80. logger.warning('Serial 127.0.0.1:58526 seems to be WSA, '
  81. 'please use "wsa-0" or others instead')
  82. raise RequestHumanTakeover
  83. if self.is_wsa:
  84. self.serial = '127.0.0.1:58526'
  85. if self.config.script.device.screenshot_method != 'uiautomator2' \
  86. or self.config.script.device.control_method != 'uiautomator2':
  87. with self.config.multi_set():
  88. self.config.script.device.screenshot_method = 'uiautomator2'
  89. self.config.script.device.control_method = 'uiautomator2'
  90. if self.is_over_http:
  91. if self.config.script.device.screenshot_method not in ["ADB", "uiautomator2", "aScreenCap"] \
  92. or self.config.script.device.control_method not in ["ADB", "uiautomator2", "minitouch"]:
  93. logger.warning(
  94. f'When connecting to a device over http: {self.serial} '
  95. f'ScreenshotMethod can only use ["ADB", "uiautomator2", "aScreenCap"], '
  96. f'ControlMethod can only use ["ADB", "uiautomator2", "minitouch"]'
  97. )
  98. raise RequestHumanTakeover
  99. @cached_property
  100. def is_bluestacks4_hyperv(self):
  101. return "bluestacks4-hyperv" in self.serial
  102. @cached_property
  103. def is_bluestacks5_hyperv(self):
  104. return "bluestacks5-hyperv" in self.serial
  105. @cached_property
  106. def is_bluestacks_hyperv(self):
  107. return self.is_bluestacks4_hyperv or self.is_bluestacks5_hyperv
  108. @cached_property
  109. def is_wsa(self):
  110. return bool(re.match(r'^wsa', self.serial))
  111. @cached_property
  112. def is_mumu_family(self):
  113. return self.serial == '127.0.0.1:7555'
  114. @cached_property
  115. def is_emulator(self):
  116. return self.serial.startswith('emulator-') or self.serial.startswith('127.0.0.1:')
  117. @cached_property
  118. def is_desktop(self):
  119. """桌面客户端模式:serial 配置为 'desktop'。
  120. 不做异常兜底:读不到配置说明 Device 构造链没走到 ConnectionAttr,
  121. 此时静默返回 False 会把桌面模式当成模拟器模式继续跑,报错指向完全无关的地方。
  122. """
  123. return str(self.config.script.device.serial) == 'desktop'
  124. @cached_property
  125. def is_network_device(self):
  126. return bool(re.match(r'\d+\.\d+\.\d+\.\d+:\d+', self.serial))
  127. @cached_property
  128. def is_over_http(self):
  129. return bool(re.match(r"^https?://", self.serial))
  130. @cached_property
  131. def is_chinac_phone_cloud(self):
  132. # Phone cloud with public ADB connection
  133. # Serial like xxx.xxx.xxx.xxx:301
  134. return bool(re.search(r":30[0-9]$", self.serial))
  135. @staticmethod
  136. def find_bluestacks4_hyperv(serial):
  137. """
  138. Find dynamic serial of BlueStacks4 Hyper-V Beta.
  139. Args:
  140. serial (str): 'bluestacks4-hyperv', 'bluestacks4-hyperv-2' for multi instance, and so on.
  141. Returns:
  142. str: 127.0.0.1:{port}
  143. """
  144. from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
  145. logger.info("Use BlueStacks4 Hyper-V Beta")
  146. logger.info("Reading Realtime adb port")
  147. if serial == "bluestacks4-hyperv":
  148. folder_name = "Android"
  149. else:
  150. folder_name = f"Android_{serial[19:]}"
  151. try:
  152. with OpenKey(HKEY_LOCAL_MACHINE,
  153. rf"SOFTWARE\BlueStacks_bgp64_hyperv\Guests\{folder_name}\Config") as key:
  154. port = QueryValueEx(key, "BstAdbPort")[0]
  155. except FileNotFoundError:
  156. logger.error(rf'Unable to find registry HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_bgp64_hyperv\Guests\{folder_name}\Config')
  157. logger.error('Please confirm that your are using BlueStack 4 hyper-v and not regular BlueStacks 4')
  158. logger.error(r'Please check if there is any other emulator instances under '
  159. r'registry HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_bgp64_hyperv\Guests')
  160. raise RequestHumanTakeover
  161. logger.info(f"New adb port: {port}")
  162. return f"127.0.0.1:{port}"
  163. @staticmethod
  164. def find_bluestacks5_hyperv(serial):
  165. """
  166. Find dynamic serial of BlueStacks5 Hyper-V.
  167. Args:
  168. serial (str): 'bluestacks5-hyperv', 'bluestacks5-hyperv-1' for multi instance, and so on.
  169. Returns:
  170. str: 127.0.0.1:{port}
  171. """
  172. from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
  173. logger.info("Use BlueStacks5 Hyper-V")
  174. logger.info("Reading Realtime adb port")
  175. if serial == "bluestacks5-hyperv":
  176. parameter_name = r"bst\.instance\.(Nougat64|Pie64)\.status\.adb_port"
  177. else:
  178. parameter_name = rf"bst\.instance\.(Nougat64|Pie64)_{serial[19:]}\.status.adb_port"
  179. try:
  180. with OpenKey(HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt") as key:
  181. directory = QueryValueEx(key, 'UserDefinedDir')[0]
  182. except FileNotFoundError:
  183. try:
  184. with OpenKey(HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt_cn") as key:
  185. directory = QueryValueEx(key, 'UserDefinedDir')[0]
  186. except FileNotFoundError:
  187. logger.error('Unable to find registry HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_nxt '
  188. 'or HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks_nxt_cn')
  189. logger.error('Please confirm that you are using BlueStacks 5 hyper-v and not regular BlueStacks 5')
  190. raise RequestHumanTakeover
  191. logger.info(f"Configuration file directory: {directory}")
  192. with open(os.path.join(directory, 'bluestacks.conf'), encoding='utf-8') as f:
  193. content = f.read()
  194. port = re.search(rf'{parameter_name}="(\d+)"', content)
  195. if port is None:
  196. logger.warning(f"Did not match the result: {serial}.")
  197. raise RequestHumanTakeover
  198. port = port.group(2)
  199. logger.info(f"Match to dynamic port: {port}")
  200. return f"127.0.0.1:{port}"
  201. @cached_property
  202. def adb_binary(self):
  203. # Try adb in deploy.yaml
  204. # from module.webui.setting import State
  205. # file = State.deploy_config.AdbExecutable
  206. # file = file.replace('\\', '/')
  207. # if os.path.exists(file):
  208. # return os.path.abspath(file)
  209. #
  210. # # Try existing adb.exe
  211. # for file in self.adb_binary_list:
  212. # if os.path.exists(file):
  213. # return os.path.abspath(file)
  214. # Try adb in python environment
  215. import sys
  216. file = os.path.join(sys.executable, '../Lib/site-packages/adbutils/binaries/adb.exe')
  217. file = os.path.abspath(file).replace('\\', '/')
  218. if os.path.exists(file):
  219. return file
  220. # Use adb in system PATH
  221. file = 'adb'
  222. return file
  223. @cached_property
  224. def adb_client(self) -> AdbClient:
  225. host = '127.0.0.1'
  226. port = 5037
  227. # Trying to get adb port from env
  228. env = os.environ.get('ANDROID_ADB_SERVER_PORT', None)
  229. if env is not None:
  230. try:
  231. port = int(env)
  232. except ValueError:
  233. logger.warning(f'Invalid environ variable ANDROID_ADB_SERVER_PORT={port}, using default port')
  234. logger.attr('AdbClient', f'AdbClient({host}, {port})')
  235. return AdbClient(host, port)
  236. @cached_property
  237. def adb(self) -> AdbDevice:
  238. return AdbDevice(self.adb_client, self.serial)
  239. @cached_property
  240. def u2(self) -> u2.Device:
  241. if self.is_over_http:
  242. # Using uiautomator2_http
  243. device = u2.connect(self.serial)
  244. else:
  245. # Normal uiautomator2
  246. if self.serial.startswith('emulator-') or self.serial.startswith('127.0.0.1:'):
  247. device = u2.connect_usb(self.serial)
  248. else:
  249. device = u2.connect(self.serial)
  250. # Stay alive
  251. device.set_new_command_timeout(604800)
  252. logger.attr('u2.Device', f'Device(atx_agent_url={device._get_atx_agent_url()})')
  253. return device