emulator.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import os
  2. import re
  3. import winreg
  4. import subprocess
  5. from adbutils.errors import AdbError
  6. from deploy.emulator import VirtualBoxEmulator
  7. from module.base.decorator import cached_property
  8. from module.device.connection import Connection
  9. from module.device.method.utils import get_serial_pair
  10. from module.exception import RequestHumanTakeover, EmulatorNotRunningError
  11. from module.logger import logger
  12. class EmulatorInstance(VirtualBoxEmulator):
  13. def __init__(self, name, root_path, emu_path,
  14. vbox_path=None, vbox_name=None, kill_para=None, multi_para=None):
  15. """
  16. Args:
  17. name (str): Emulator name in windows uninstall list.
  18. root_path (str): Relative path from uninstall.exe to emulator installation folder.
  19. emu_path (str): Relative path to executable simulator file.
  20. vbox_path (str): Relative path to virtual box folder.
  21. vbox_name (str): Regular Expression to match the name of .vbox file.
  22. kill_para (str): Parameters required by kill emulator.
  23. multi_para (str): Parameters required by start multi open emulator,
  24. #id will be replaced with the real ID.
  25. """
  26. super().__init__(
  27. name=name,
  28. root_path=root_path,
  29. adb_path=None,
  30. vbox_path=vbox_path,
  31. vbox_name=vbox_name,
  32. )
  33. self.emu_path = emu_path
  34. self.kill_para = kill_para
  35. self.multi_para = multi_para
  36. @cached_property
  37. def id_and_serial(self):
  38. """
  39. Returns:
  40. list[str, str]: List of multi_id and serial.
  41. """
  42. vbox = []
  43. for path, folders, files in os.walk(os.path.join(self.root, self.vbox_path)):
  44. for file in files:
  45. if re.match(self.vbox_name, file):
  46. file = os.path.join(path, file)
  47. vbox.append(file)
  48. serial = []
  49. for file in vbox:
  50. with open(file, 'r', encoding='utf-8', errors='ignore') as f:
  51. for line in f.readlines():
  52. # <Forwarding name="port2" proto="1" hostip="127.0.0.1" hostport="62026" guestport="5555"/>
  53. res = re.search('<*?hostport="(.*?)".*?guestport="5555"/>', line)
  54. if res:
  55. serial.append([os.path.basename(file).split(".")[0], f'127.0.0.1:{res.group(1)}'])
  56. return serial
  57. class Bluestacks5Instance(EmulatorInstance):
  58. @cached_property
  59. def root(self):
  60. try:
  61. return super().root
  62. except FileNotFoundError:
  63. self.name = 'BlueStacks_nxt_cn'
  64. return super().root
  65. @cached_property
  66. def id_and_serial(self):
  67. try:
  68. reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt")
  69. except FileNotFoundError:
  70. reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt_cn")
  71. directory = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
  72. with open(os.path.join(directory, 'bluestacks.conf'), encoding='utf-8') as f:
  73. content = f.read()
  74. emulators = re.findall(r'bst.instance.(\w+).status.adb_port="(\d+)"', content)
  75. serial = []
  76. for emulator in emulators:
  77. serial.append([emulator[0], f'127.0.0.1:{emulator[1]}'])
  78. return serial
  79. class EmulatorManager(Connection):
  80. pid = None
  81. SUPPORTED_EMULATORS = {
  82. 'nox_player': EmulatorInstance(
  83. name="Nox",
  84. root_path=".",
  85. emu_path="./Nox.exe",
  86. vbox_path="./BignoxVMS",
  87. vbox_name='.*.vbox$',
  88. kill_para='-quit',
  89. multi_para='-clone:#id',
  90. ),
  91. 'mumu_player': EmulatorInstance(
  92. name="Nemu",
  93. root_path=".",
  94. emu_path="./EmulatorShell/NemuPlayer.exe",
  95. vbox_path="./vms",
  96. vbox_name='.*.nemu$',
  97. ),
  98. 'bluestacks_5': Bluestacks5Instance(
  99. name='BlueStacks_nxt',
  100. root_path='.',
  101. emu_path='./HD-Player.exe',
  102. multi_para='--instance #id',
  103. ),
  104. }
  105. def detect_emulator(self, serial, emulator=None):
  106. """
  107. Args:
  108. serial (str):
  109. emulator (EmulatorInstance):
  110. Returns:
  111. list[EmulatorInstance, str]:Emulator and multi_id
  112. """
  113. if emulator is None:
  114. logger.info('Detect emulator from all emulators installed')
  115. emulators = []
  116. for emulator in self.SUPPORTED_EMULATORS.values():
  117. try:
  118. serials = emulator.id_and_serial
  119. for cur_serial in serials:
  120. if cur_serial[1] == serial:
  121. emulators.append([emulator, cur_serial[0]])
  122. except FileNotFoundError:
  123. pass
  124. logger.info('Detected emulators:')
  125. for emulator in emulators:
  126. logger.info(f'Name: {emulator[0].name}, Multi_id: {emulator[1]}')
  127. if len(emulators) == 1 or \
  128. (len(emulators) > 0 and emulators[0][0] == self.SUPPORTED_EMULATORS['mumu_player']):
  129. logger.info('Find the only emulator, using it')
  130. return emulators[0][0], emulators[0][1]
  131. elif len(emulators) == 0:
  132. logger.warning('The emulator corresponding to serial is not found, '
  133. 'please check the setting or use custom command')
  134. else:
  135. logger.warning('Multiple emulators with the same serial have been found, '
  136. 'please select one manually or use custom command')
  137. raise RequestHumanTakeover
  138. else:
  139. try:
  140. logger.info(f'Detect emulator from {emulator.name}')
  141. serials = emulator.id_and_serial
  142. for cur_serial in serials:
  143. if cur_serial[1] == serial:
  144. logger.info('Find the only emulator, using it')
  145. return emulator, cur_serial[0]
  146. except FileNotFoundError:
  147. pass
  148. logger.warning('The emulator corresponding to serial is not found, '
  149. 'please check the setting or use custom command')
  150. raise RequestHumanTakeover
  151. @staticmethod
  152. def execute(command):
  153. """
  154. Args:
  155. command (str):
  156. Returns:
  157. subprocess.Popen:
  158. """
  159. command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
  160. logger.info(f'Execute: {command}')
  161. return subprocess.Popen(command, close_fds=True) # only work on Windows
  162. @staticmethod
  163. def task_kill(pid=None, name=None):
  164. """
  165. Args:
  166. pid (list, int):
  167. name (list, str):
  168. Returns:
  169. subprocess.Popen:
  170. """
  171. command = 'taskkill '
  172. if pid is not None:
  173. if isinstance(pid, list):
  174. for p in pid:
  175. command += f'/pid {p} '
  176. else:
  177. command += f'/pid {pid} '
  178. elif name is not None:
  179. if isinstance(name, list):
  180. for n in name:
  181. command += f'/im {n} '
  182. else:
  183. command += f'/im {name} '
  184. else:
  185. raise RequestHumanTakeover
  186. command += '/t /f'
  187. return EmulatorManager.execute(command)
  188. def adb_connect(self, serial):
  189. try:
  190. return super(EmulatorManager, self).adb_connect(serial)
  191. except EmulatorNotRunningError:
  192. raise RequestHumanTakeover
  193. def detect_emulator_status(self, serial):
  194. devices = self.list_device()
  195. for device in devices:
  196. if device.serial == serial:
  197. return device.status
  198. return 'offline'
  199. def emulator_start(self, serial, emulator=None, multi_id=None, command=None):
  200. """
  201. Args:
  202. serial (str): Expected serial after simulator starts successfully.
  203. emulator (EmulatorInstance): Emulator to start.
  204. multi_id (str): Emulator ID used by multi open emulator.
  205. command (str): Customized path and parameters of the simulator to start.
  206. Return:
  207. bool: If start successful.
  208. """
  209. if command is None:
  210. command = '\"' + os.path.abspath(os.path.join(emulator.root, emulator.emu_path)) + '\"'
  211. if emulator.multi_para is not None and multi_id is not None:
  212. command += " " + emulator.multi_para.replace("#id", multi_id)
  213. logger.info('Start emulator')
  214. pipe = self.execute(command)
  215. self.pid = pipe.pid
  216. self.sleep(10)
  217. for _ in range(20):
  218. if pipe.poll() is not None:
  219. break
  220. try:
  221. if super().adb_connect(serial):
  222. # Wait until emulator start completely
  223. self.sleep(10)
  224. return True
  225. except EmulatorNotRunningError:
  226. pass
  227. self.sleep(5)
  228. return False
  229. def emulator_kill(self, serial, emulator=None, multi_id=None, command=None):
  230. """
  231. Args:
  232. serial (str): Expected serial after simulator starts successfully.
  233. emulator (EmulatorInstance): Emulator to start.
  234. multi_id (str): Emulator ID used by multi open emulator.
  235. command (str): Customized path and parameters of the simulator to start.
  236. Return:
  237. bool: If kill successful.
  238. """
  239. if command is None and emulator.kill_para is not None:
  240. command = '\"' + os.path.abspath(os.path.join(emulator.root, emulator.emu_path)) + '\"'
  241. if emulator.multi_para is not None and multi_id is not None:
  242. command += " " + emulator.multi_para.replace("#id", multi_id)
  243. command += " " + emulator.kill_para
  244. logger.info('Kill emulator')
  245. if emulator == self.SUPPORTED_EMULATORS['bluestacks_5']:
  246. try:
  247. self.adb_command(['reboot', '-p'], timeout=20)
  248. if self.detect_emulator_status(serial) == 'offline':
  249. self.pid = None
  250. return True
  251. except AdbError:
  252. return False
  253. if emulator == self.SUPPORTED_EMULATORS['mumu_player']:
  254. self.task_kill(pid=None, name=['NemuHeadless.exe', 'NemuPlayer.exe', 'NemuSvc.exe'])
  255. elif command is not None:
  256. self.execute(command)
  257. else:
  258. self.task_kill(pid=self.pid, name=os.path.basename(emulator.emu_path))
  259. self.sleep(5)
  260. for _ in range(10):
  261. if self.detect_emulator_status(serial) == 'offline':
  262. self.pid = None
  263. return True
  264. self.sleep(2)
  265. return False
  266. def emulator_restart(self):
  267. serial, _ = get_serial_pair(self.serial)
  268. if serial is None:
  269. serial = self.serial
  270. if os.name != 'nt':
  271. logger.warning('Restart simulator only works under Windows platform')
  272. return False
  273. logger.hr('Emulator restart')
  274. # if self.config.RestartEmulator_EmulatorType == 'auto':
  275. if self.config.get_arg('Restart', '') == 'auto':
  276. emulator, multi_id = self.detect_emulator(serial)
  277. else:
  278. emulator = self.SUPPORTED_EMULATORS[self.config.RestartEmulator_EmulatorType]
  279. emulator, multi_id = self.detect_emulator(serial, emulator=emulator)
  280. for _ in range(3):
  281. if not self.emulator_kill(serial, emulator, multi_id):
  282. continue
  283. if self.emulator_start(serial, emulator, multi_id):
  284. return True
  285. logger.warning('Restart emulator failed for 3 times, please check your settings')
  286. raise RequestHumanTakeover