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

Merge pull request #1516 from LGG686/dev-e

feat: 无任务时支持关闭模拟器并预热拉起
huangrunheng 6 месяцев назад
Родитель
Сommit
b7fac9a020
3 измененных файлов с 111 добавлено и 6 удалено
  1. 11 1
      assets/i18n/zh-CN.json
  2. 94 5
      script.py
  3. 6 0
      tasks/Script/config_optimization.py

+ 11 - 1
assets/i18n/zh-CN.json

@@ -24,7 +24,17 @@
   "checkin_config": "签到配置",
   "checkin_config": "签到配置",
   "Usage": "使用说明",
   "Usage": "使用说明",
   "checkin_big_god_usage_help": "自动领取网易大神APP的阴阳师福利礼包。\n\n使用前准备:\n1. 开启模拟器的Root模式\n2. 模拟器中安装并登录「网易大神」APP\n3. 在大神APP中绑定阴阳师角色\n\nFrida Server 会自动推送到模拟器并启动,无需手动操作。",
   "checkin_big_god_usage_help": "自动领取网易大神APP的阴阳师福利礼包。\n\n使用前准备:\n1. 开启模拟器的Root模式\n2. 模拟器中安装并登录「网易大神」APP\n3. 在大神APP中绑定阴阳师角色\n\nFrida Server 会自动推送到模拟器并启动,无需手动操作。",
-  "costume_main_14": "雪月华庭"
+  "costume_main_14": "雪月华庭",
+  "goto_main": "前往主界面",
+  "close_game": "关闭游戏",
+  "close_emulator_or_goto_main": "关闭模拟器&前往主界面",
+  "close_emulator_or_close_game": "关闭模拟器&关闭游戏",
+  "close_game_limit_time": "关闭游戏等待时间",
+  "close_game_limit_time_help": "此时间内不会关闭游戏, 防止运行间隔时间短的多个任务导致反复开关游戏",
+  "close_emulator_limit_time": "关闭模拟器等待时间",
+  "close_emulator_limit_time_help": "此时间内不会关闭模拟器, 防止运行间隔时间短的多个任务导致反复开关模拟器",
+  "emulator_startup_lead_time": "模拟器预热时间",
+  "emulator_startup_lead_time_help": "在开始运行任务之前提前启动模拟器的时间"
 }
 }
 
 
 
 

+ 94 - 5
script.py

@@ -47,6 +47,7 @@ class Script:
         logger.hr('Start', level=0)
         logger.hr('Start', level=0)
         self.server = None
         self.server = None
         self.state_queue: Queue = None
         self.state_queue: Queue = None
+        self._emulator_down = False
         self.gui_update_task: Callable = None  # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
         self.gui_update_task: Callable = None  # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
         self.config_name = config_name
         self.config_name = config_name
         # Skip first restart
         # Skip first restart
@@ -329,29 +330,112 @@ class Script:
         strategy_map = {
         strategy_map = {
             "close_game": self._wait_close_game,
             "close_game": self._wait_close_game,
             "goto_main": self._wait_goto_main,
             "goto_main": self._wait_goto_main,
+            "close_emulator_or_goto_main": self._wait_close_emulator_or_goto_main,
+            "close_emulator_or_close_game": self._wait_close_emulator_or_close_game,
         }
         }
         func = strategy_map.get(method)
         func = strategy_map.get(method)
-        if not func:
+        if func is None:
             logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
             logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
             func = self._wait_stay_there
             func = self._wait_stay_there
         return func(next_run)
         return func(next_run)
 
 
+    @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)
+        now = datetime.now()
+        wake_time = next_run - startup_lead if startup_lead > timedelta(0) else next_run
+        if wake_time < now:
+            wake_time = now
+
+        now = datetime.now()
+        if wake_time > 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) -> bool:
     def _wait_close_game(self, next_run: datetime) -> bool:
-        logger.info("Close game during wait")
-        self.device.app_stop()
+        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_time = self.config.script.optimization.close_game_limit_time
+        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("Wait without closing game (close_game limit time not reached)")
         self.device.release_during_wait()
         self.device.release_during_wait()
         if not self.wait_until(next_run):
         if not self.wait_until(next_run):
             return False
             return False
-        self.run("Restart")
         return True
         return True
 
 
     def _wait_goto_main(self, next_run: datetime) -> bool:
     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")
         logger.info("Goto main page during wait")
         self.run("GotoMain")
         self.run("GotoMain")
         self.device.release_during_wait()
         self.device.release_during_wait()
         return self.wait_until(next_run)
         return self.wait_until(next_run)
 
 
+    def _wait_close_emulator_or_goto_main(self, next_run: datetime) -> bool:
+        return self._wait_close_emulator_or(next_run, self._wait_goto_main)
+
+    def _wait_close_emulator_or_close_game(self, next_run: datetime) -> bool:
+        return self._wait_close_emulator_or(next_run, self._wait_close_game)
+
+    def _wait_close_emulator_or(self, next_run: datetime, fallback_waiter: Callable[[datetime], bool]) -> bool:
+        close_emulator_limit_time = self.config.script.optimization.close_emulator_limit_time
+        close_emulator_limit = self._time_to_timedelta(close_emulator_limit_time)
+
+        now = datetime.now()
+        if close_emulator_limit > timedelta(0) and next_run > 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
+
+        return fallback_waiter(next_run)
+
     def _wait_stay_there(self, next_run: datetime) -> bool:
     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")
         logger.info("Stay_there (no action) during wait")
         self.device.release_during_wait()
         self.device.release_during_wait()
         return self.wait_until(next_run)
         return self.wait_until(next_run)
@@ -484,7 +568,6 @@ class Script:
 
 
             # Get task
             # Get task
             task = self.get_next_task()
             task = self.get_next_task()
-            _ = self.device
             # Skip first restart
             # Skip first restart
             if self.is_first_task and task == 'Restart':
             if self.is_first_task and task == 'Restart':
                 logger.info('Skip task `Restart` at scheduler start')
                 logger.info('Skip task `Restart` at scheduler start')
@@ -492,6 +575,12 @@ class Script:
                 del_cached_property(self, 'config')
                 del_cached_property(self, 'config')
                 continue
                 continue
 
 
+            if self._emulator_down:
+                self.device = Device(self.config)
+                self._emulator_down = False
+            else:
+                _ = self.device
+
             # Run
             # Run
             logger.info(f'Scheduler: Start task `{task}`')
             logger.info(f'Scheduler: Start task `{task}`')
             self.device.stuck_record_clear()
             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 pydantic import BaseModel, ValidationError, validator, Field
 
 
 from module.logger import logger
 from module.logger import logger
+from tasks.Component.config_base import Time
 
 
 class WhenTaskQueueEmpty(str, Enum):
 class WhenTaskQueueEmpty(str, Enum):
     GOTO_MAIN = 'goto_main'
     GOTO_MAIN = 'goto_main'
     CLOSE_GAME = 'close_game'
     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):
 class ScheduleRule(str, Enum):
     FILTER = 'Filter'  # 默认的基于过滤器,(按照开发者设定的调度规则进行调度)
     FILTER = 'Filter'  # 默认的基于过滤器,(按照开发者设定的调度规则进行调度)
@@ -24,5 +27,8 @@ class Optimization(BaseModel):
                                           description='task_hoarding_duration_help')
                                           description='task_hoarding_duration_help')
     when_task_queue_empty: WhenTaskQueueEmpty = Field(default=WhenTaskQueueEmpty.GOTO_MAIN,
     when_task_queue_empty: WhenTaskQueueEmpty = Field(default=WhenTaskQueueEmpty.GOTO_MAIN,
                                                       description='when_task_queue_empty_help')
                                                       description='when_task_queue_empty_help')
+    close_game_limit_time: Time = Field(default=Time(minute=10),description='close_game_limit_time_help')
+    close_emulator_limit_time: Time = Field(default=Time(minute=30),description='close_emulator_limit_time_help')
+    emulator_startup_lead_time: Time = Field(default=Time(minute=2),description='emulator_startup_lead_time_help')
     schedule_rule: ScheduleRule = Field(default=ScheduleRule.FILTER, description='schedule_rule_help')
     schedule_rule: ScheduleRule = Field(default=ScheduleRule.FILTER, description='schedule_rule_help')