Просмотр исходного кода

feat: 无任务时支持关闭模拟器并预热拉起

- 新增 close_emulator_or_goto_main / close_emulator_or_close_game 策略
- 新增 close_game_limit_time、close_emulator_limit_time、emulator_startup_lead_time 配置
- 引入 _emulator_down 状态追踪,避免关闭后执行无效设备操作
- 当模拟器处于关闭状态时,空闲分支统一走预热拉起流程
- 配置变更后按新的 next_run 重新调度等待

(cherry picked from commit 01e5d7274958e12dc5a6a697dfffeaa4d480dd01)
yuyuyuyuyu 7 месяцев назад
Родитель
Сommit
c88daf38db
2 измененных файлов с 103 добавлено и 5 удалено
  1. 97 5
      script.py
  2. 6 0
      tasks/Script/config_optimization.py

+ 97 - 5
script.py

@@ -47,6 +47,7 @@ class Script:
         logger.hr('Start', level=0)
         self.server = None
         self.state_queue: Queue = None
+        self._emulator_down = False
         self.gui_update_task: Callable = None  # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
         self.config_name = config_name
         # Skip first restart
@@ -326,32 +327,118 @@ class Script:
         :return: True 表示等待成功完成, False 表示等待被中断
         """
         method = self.config.script.optimization.when_task_queue_empty
+        close_game_limit_time = self.config.script.optimization.close_game_limit_time
+        close_emulator_limit_time = self.config.script.optimization.close_emulator_limit_time
         strategy_map = {
             "close_game": self._wait_close_game,
             "goto_main": self._wait_goto_main,
+            "close_emulator_or_goto_main": self._wait_close_emulator_or,
+            "close_emulator_or_close_game": self._wait_close_emulator_or,
         }
         func = strategy_map.get(method)
         if not func:
             logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
             func = self._wait_stay_there
+            return func(next_run)
+
+        if method in ["close_emulator_or_goto_main", "close_emulator_or_close_game"]:
+            return func(next_run, close_game_limit_time, close_emulator_limit_time, method)
+
+        if method == "close_game":
+            return func(next_run, close_game_limit_time)
+
         return func(next_run)
 
-    def _wait_close_game(self, next_run: datetime) -> bool:
-        logger.info("Close game during wait")
-        self.device.app_stop()
+    @staticmethod
+    def _time_to_timedelta(value) -> timedelta:
+        if value is None:
+            return timedelta(0)
+        return timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)
+
+    def _wait_until_with_emulator_preheat(self, next_run: datetime) -> bool:
+        """Wait until next_run; if emulator is down, preheat startup before next task."""
+        if not self._emulator_down:
+            return self.wait_until(next_run)
+
+        startup_lead = self._time_to_timedelta(self.config.script.optimization.emulator_startup_lead_time)
+        wake_time = next_run - startup_lead if startup_lead > timedelta(0) else next_run
+        if wake_time < datetime.now():
+            wake_time = datetime.now()
+
+        if wake_time > datetime.now():
+            logger.info(f"Wait before wake emulator: {wake_time.strftime('%Y-%m-%d %H:%M:%S')}")
+            if not self.wait_until(wake_time):
+                return False
+
+        if self._emulator_down:
+            logger.info("Wake emulator before next task")
+            self.device = Device(self.config)
+            self._emulator_down = False
+
+        if wake_time < next_run:
+            return self.wait_until(next_run)
+        return True
+
+    def _wait_close_game(self, next_run: datetime, close_game_limit_time=None) -> bool:
+        if self._emulator_down:
+            logger.info("Emulator is down, skip close_game/goto_main action and wait with preheat")
+            return self._wait_until_with_emulator_preheat(next_run)
+
+        close_game_limit = self._time_to_timedelta(close_game_limit_time)
+        if close_game_limit > timedelta(0) and next_run > datetime.now() + close_game_limit:
+            logger.info("Close game during wait")
+            self.device.app_stop()
+            self.device.release_during_wait()
+            if not self.wait_until(next_run):
+                return False
+            self.run("Restart")
+            return True
+
+        logger.info("Goto main page during wait (close_game limit time not reached)")
         self.device.release_during_wait()
         if not self.wait_until(next_run):
             return False
-        self.run("Restart")
         return True
 
     def _wait_goto_main(self, next_run: datetime) -> bool:
+        if self._emulator_down:
+            logger.info("Emulator is down, skip goto_main and wait with preheat")
+            return self._wait_until_with_emulator_preheat(next_run)
+
         logger.info("Goto main page during wait")
         self.run("GotoMain")
         self.device.release_during_wait()
         return self.wait_until(next_run)
 
+    def _wait_close_emulator_or(self, next_run: datetime, close_game_limit_time=None,
+                                close_emulator_limit_time=None, method=None) -> bool:
+        close_emulator_limit = self._time_to_timedelta(close_emulator_limit_time)
+
+        if close_emulator_limit > timedelta(0) and next_run > datetime.now() + close_emulator_limit:
+            logger.info("Close emulator during wait")
+            if not self._emulator_down:
+                self.device.emulator_stop()
+            else:
+                logger.info("Emulator already closed")
+
+            self._emulator_down = True
+
+            if not self._wait_until_with_emulator_preheat(next_run):
+                return False
+
+            self.run("Restart")
+            return True
+
+        if method == "close_emulator_or_goto_main":
+            return self._wait_goto_main(next_run)
+
+        return self._wait_close_game(next_run, close_game_limit_time)
+
     def _wait_stay_there(self, next_run: datetime) -> bool:
+        if self._emulator_down:
+            logger.info("Stay_there during wait (emulator is down, with preheat)")
+            return self._wait_until_with_emulator_preheat(next_run)
+
         logger.info("Stay_there (no action) during wait")
         self.device.release_during_wait()
         return self.wait_until(next_run)
@@ -484,7 +571,6 @@ class Script:
 
             # Get task
             task = self.get_next_task()
-            _ = self.device
             # Skip first restart
             if self.is_first_task and task == 'Restart':
                 logger.info('Skip task `Restart` at scheduler start')
@@ -492,6 +578,12 @@ class Script:
                 del_cached_property(self, 'config')
                 continue
 
+            if self._emulator_down:
+                self.device = Device(self.config)
+                self._emulator_down = False
+            else:
+                _ = self.device
+
             # Run
             logger.info(f'Scheduler: Start task `{task}`')
             self.device.stuck_record_clear()

+ 6 - 0
tasks/Script/config_optimization.py

@@ -5,10 +5,13 @@ from enum import Enum
 from pydantic import BaseModel, ValidationError, validator, Field
 
 from module.logger import logger
+from tasks.Component.config_base import Time
 
 class WhenTaskQueueEmpty(str, Enum):
     GOTO_MAIN = 'goto_main'
     CLOSE_GAME = 'close_game'
+    CLOSE_EMULATOR_OR_GOTO_MAIN = 'close_emulator_or_goto_main'
+    CLOSE_EMULATOR_OR_CLOSE_GAME = 'close_emulator_or_close_game'
 
 class ScheduleRule(str, Enum):
     FILTER = 'Filter'  # 默认的基于过滤器,(按照开发者设定的调度规则进行调度)
@@ -24,5 +27,8 @@ class Optimization(BaseModel):
                                           description='task_hoarding_duration_help')
     when_task_queue_empty: WhenTaskQueueEmpty = Field(default=WhenTaskQueueEmpty.GOTO_MAIN,
                                                       description='when_task_queue_empty_help')
+    close_game_limit_time: Time = Field(default=Time(minute=10), description='关闭游戏等待时间')
+    close_emulator_limit_time: Time = Field(default=Time(minute=30), description='关闭模拟器等待时间')
+    emulator_startup_lead_time: Time = Field(default=Time(minute=2), description='模拟器预热时间')
     schedule_rule: ScheduleRule = Field(default=ScheduleRule.FILTER, description='schedule_rule_help')