device.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. from collections import deque
  2. from datetime import datetime
  3. # Patch pkg_resources before importing adbutils and uiautomator2
  4. from module.device.pkg_resources import get_distribution
  5. # Just avoid being removed by import optimization
  6. _ = get_distribution
  7. from module.device.env import IS_WINDOWS
  8. from module.base.timer import Timer
  9. from module.config.utils import get_server_next_update
  10. from module.device.app_control import AppControl
  11. from module.device.control import Control
  12. from module.device.platform2 import Platform
  13. from module.device.screenshot import Screenshot
  14. from module.exception import (GameNotRunningError,
  15. GameStuckError,
  16. GameTooManyClickError,
  17. RequestHumanTakeover,
  18. EmulatorNotRunningError)
  19. from module.logger import logger
  20. class Device(Platform, Screenshot, Control, AppControl):
  21. _screen_size_checked = False
  22. detect_record = set()
  23. click_record = deque(maxlen=15)
  24. stuck_timer = Timer(60, count=60).start()
  25. stuck_timer_long = Timer(300, count=300).start()
  26. stuck_long_wait_list = ['BATTLE_STATUS_S', 'PAUSE', 'LOGIN_CHECK', 'PREPARE_BEFORE_BATTLE']
  27. def __init__(self, *args, **kwargs):
  28. for trial in range(4):
  29. try:
  30. super().__init__(*args, **kwargs)
  31. break
  32. except EmulatorNotRunningError:
  33. if trial >= 3:
  34. logger.critical('Failed to start emulator after 3 trial')
  35. raise RequestHumanTakeover
  36. # Try to start emulator
  37. if self.emulator_instance is not None:
  38. self.emulator_start()
  39. else:
  40. logger.critical(
  41. f'No emulator with serial "{self.config.Emulator_Serial}" found, '
  42. f'please set a correct serial'
  43. )
  44. raise RequestHumanTakeover
  45. # Auto-fill emulator info
  46. if IS_WINDOWS and self.config.script.device.emulatorinfo_type == 'auto':
  47. _ = self.emulator_instance
  48. self.screenshot_interval_set()
  49. # Auto-select the fastest screenshot method
  50. if self.config.script.device.screenshot_method == 'auto':
  51. self.run_simple_screenshot_benchmark()
  52. def run_simple_screenshot_benchmark(self):
  53. """
  54. Perform a screenshot method benchmark, test 3 times on each method.
  55. The fastest one will be set into config.
  56. """
  57. logger.info('run_simple_screenshot_benchmark')
  58. # Check resolution first
  59. # self.resolution_check_uiautomator2()
  60. # Perform benchmark
  61. from module.daemon.benchmark import Benchmark
  62. bench = Benchmark(config=self.config, device=self)
  63. method = bench.run_simple_screenshot_benchmark()
  64. # Set
  65. self.config.script.device.screenshot_method = method
  66. self.config.save()
  67. def handle_night_commission(self, daily_trigger='21:00', threshold=30):
  68. """
  69. Args:
  70. daily_trigger (int): Time for commission refresh.
  71. threshold (int): Seconds around refresh time.
  72. Returns:
  73. bool: If handled.
  74. """
  75. update = get_server_next_update(daily_trigger=daily_trigger)
  76. now = datetime.now()
  77. diff = (update.timestamp() - now.timestamp()) % 86400
  78. if threshold < diff < 86400 - threshold:
  79. return False
  80. # if GET_MISSION.match(self.image, offset=True):
  81. # logger.info('Night commission appear.')
  82. # self.click(GET_MISSION)
  83. # return True
  84. return False
  85. def screenshot(self):
  86. """
  87. Returns:
  88. np.ndarray:
  89. """
  90. self.stuck_record_check()
  91. try:
  92. super().screenshot()
  93. except RequestHumanTakeover as e:
  94. raise RequestHumanTakeover
  95. if self.handle_night_commission():
  96. super().screenshot()
  97. return self.image
  98. def release_during_wait(self):
  99. # Scrcpy server is still sending video stream,
  100. # stop it during wait
  101. # self.config.script.device.screenshot_method = 'scrcpy'
  102. if self.config.script.device.screenshot_method == 'scrcpy':
  103. self._scrcpy_server_stop()
  104. if self.config.Emulator_ScreenshotMethod == 'nemu_ipc':
  105. self.nemu_ipc_release()
  106. def stuck_record_add(self, button):
  107. """
  108. 当你要设置这个时候检测为长时间的时候,你需要在这里添加
  109. 如果取消后,需要在`stuck_record_clear`中清除
  110. :param button:
  111. :return:
  112. """
  113. self.detect_record.add(str(button))
  114. logger.info(f'Add stuck record: {button}')
  115. def stuck_record_clear(self):
  116. self.detect_record = set()
  117. self.stuck_timer.reset()
  118. self.stuck_timer_long.reset()
  119. def stuck_record_check(self):
  120. """
  121. Raises:
  122. GameStuckError:
  123. """
  124. reached = self.stuck_timer.reached()
  125. reached_long = self.stuck_timer_long.reached()
  126. if not reached:
  127. return False
  128. if not reached_long:
  129. for button in self.stuck_long_wait_list:
  130. if button in self.detect_record:
  131. return False
  132. logger.warning('Wait too long')
  133. logger.warning(f'Waiting for {self.detect_record}')
  134. self.stuck_record_clear()
  135. if self.app_is_running():
  136. raise GameStuckError(f'Wait too long')
  137. else:
  138. raise GameNotRunningError('Game died')
  139. def handle_control_check(self, button):
  140. self.stuck_record_clear()
  141. self.click_record_add(button)
  142. self.click_record_check()
  143. def click_record_add(self, button):
  144. self.click_record.append(str(button))
  145. def click_record_clear(self):
  146. self.click_record.clear()
  147. def click_record_remove(self, button):
  148. """
  149. Remove a button from `click_record`
  150. Args:
  151. button (Button):
  152. Returns:
  153. int: Number of button removed
  154. """
  155. removed = 0
  156. for _ in range(self.click_record.maxlen):
  157. try:
  158. self.click_record.remove(str(button))
  159. removed += 1
  160. except ValueError:
  161. # Value not in queue
  162. break
  163. return removed
  164. def click_record_check(self):
  165. """
  166. Raises:
  167. GameTooManyClickError:
  168. """
  169. count = {}
  170. for key in self.click_record:
  171. count[key] = count.get(key, 0) + 1
  172. count = sorted(count.items(), key=lambda item: item[1], reverse=True)
  173. if count[0][1] >= 10:
  174. logger.warning(f'Too many click for a button: {count[0][0]}')
  175. logger.warning(f'History click: {[str(prev) for prev in self.click_record]}')
  176. self.click_record_clear()
  177. raise GameTooManyClickError(f'Too many click for a button: {count[0][0]}')
  178. if len(count) >= 2 and count[0][1] >= 6 and count[1][1] >= 6:
  179. logger.warning(f'Too many click between 2 buttons: {count[0][0]}, {count[1][0]}')
  180. logger.warning(f'History click: {[str(prev) for prev in self.click_record]}')
  181. self.click_record_clear()
  182. raise GameTooManyClickError(f'Too many click between 2 buttons: {count[0][0]}, {count[1][0]}')
  183. def disable_stuck_detection(self):
  184. """
  185. Disable stuck detection and its handler. Usually uses in semi auto and debugging.
  186. """
  187. logger.info('Disable stuck detection')
  188. def empty_function(*arg, **kwargs):
  189. return False
  190. self.click_record_check = empty_function
  191. self.stuck_record_check = empty_function
  192. def app_start(self):
  193. if not self.config.script.error.handle_error:
  194. logger.critical('No app stop/start, because HandleError disabled')
  195. logger.critical('Please enable Alas.Error.HandleError or manually login to AzurLane')
  196. raise RequestHumanTakeover
  197. super().app_start()
  198. self.stuck_record_clear()
  199. self.click_record_clear()
  200. def app_stop(self):
  201. if not self.config.script.error.handle_error:
  202. logger.critical('No app stop/start, because HandleError disabled')
  203. logger.critical('Please enable Alas.Error.HandleError or manually login to AzurLane')
  204. raise RequestHumanTakeover
  205. super().app_stop()
  206. self.stuck_record_clear()
  207. self.click_record_clear()
  208. if __name__ == "__main__":
  209. device = Device(config="oas1")
  210. # cv2.imshow("imgSrceen", device.screenshot()) # 显示
  211. # cv2.waitKey(0)
  212. # cv2.destroyAllWindows()