device.py 7.7 KB

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