Browse Source

Merge pull request #23 from runhey/dev

Dev
huangrunheng 3 years ago
parent
commit
4269c8788b
65 changed files with 1002 additions and 158 deletions
  1. 42 33
      config/template.json
  2. 0 0
      dev_tools/assets_extract.py
  3. 0 0
      dev_tools/template_update.py
  4. 108 2
      module/config/config.py
  5. 1 0
      module/config/config_manual.py
  6. 2 1
      module/config/config_menu.py
  7. 42 5
      module/config/config_model.py
  8. BIN
      module/config/i18n/zh_CN.qm
  9. 44 1
      module/config/i18n/zh_CN.ts
  10. 58 0
      module/config/utils.py
  11. 1 1
      module/daemon/benchmark.py
  12. 6 6
      module/device/connection_attr.py
  13. 4 3
      module/device/device.py
  14. 1 1
      module/device/method/window.py
  15. 1 1
      module/device/screenshot.py
  16. 6 4
      module/ocr/base_ocr.py
  17. 2 2
      module/ocr/sub_ocr.py
  18. 4 4
      script.py
  19. 3 2
      tasks/Component/GeneralBattle/general_battle.py
  20. 15 1
      tasks/DemonEncounter/config.py
  21. 17 0
      tasks/DemonEncounter/script_task.py
  22. 22 0
      tasks/GlobalGame/assets.py
  23. 8 0
      tasks/GlobalGame/ui/click.json
  24. 65 0
      tasks/GlobalGame/ui/image.json
  25. BIN
      tasks/GlobalGame/ui/ui_ui_award.png
  26. BIN
      tasks/GlobalGame/ui/ui_ui_back_blue.png
  27. BIN
      tasks/GlobalGame/ui/ui_ui_back_red.png
  28. BIN
      tasks/GlobalGame/ui/ui_ui_back_yellow.png
  29. BIN
      tasks/GlobalGame/ui/ui_ui_cancel.png
  30. BIN
      tasks/GlobalGame/ui/ui_ui_confirm.png
  31. BIN
      tasks/GlobalGame/ui/ui_ui_ensure.png
  32. BIN
      tasks/GlobalGame/ui/ui_ui_reward.png
  33. BIN
      tasks/GlobalGame/ui/ui_ui_rewards.png
  34. 15 0
      tasks/GotoMain/script_task.py
  35. 28 0
      tasks/KekkaiActivation/config.py
  36. 17 0
      tasks/KekkaiActivation/script_task.py
  37. 33 0
      tasks/KekkaiUtilize/config.py
  38. 17 0
      tasks/KekkaiUtilize/script_task.py
  39. 6 2
      tasks/Orochi/script_task.py
  40. 42 1
      tasks/Restart/assets.py
  41. 25 2
      tasks/Restart/config.py
  42. 5 18
      tasks/Restart/config_scheduler.py
  43. BIN
      tasks/Restart/harvest/harvest_harvest_jade.png
  44. BIN
      tasks/Restart/harvest/harvest_harvest_mail.png
  45. BIN
      tasks/Restart/harvest/harvest_harvest_mail_all.png
  46. BIN
      tasks/Restart/harvest/harvest_harvest_mail_confirm.png
  47. BIN
      tasks/Restart/harvest/harvest_harvest_mail_open.png
  48. BIN
      tasks/Restart/harvest/harvest_harvest_sign.png
  49. BIN
      tasks/Restart/harvest/harvest_harvest_sign_2.png
  50. BIN
      tasks/Restart/harvest/harvest_harvest_sign_999.png
  51. BIN
      tasks/Restart/harvest/harvest_harvest_soul.png
  52. 83 0
      tasks/Restart/harvest/image.json
  53. BIN
      tasks/Restart/harvest/image_name.png
  54. 146 0
      tasks/Restart/login.py
  55. 47 0
      tasks/Restart/login/image.json
  56. BIN
      tasks/Restart/login/login_login_8.png
  57. BIN
      tasks/Restart/login/login_login_red_close.png
  58. BIN
      tasks/Restart/login/login_login_scrooll_close.png
  59. BIN
      tasks/Restart/login/login_login_scrooll_open.png
  60. BIN
      tasks/Restart/login/login_login_yellow_close.png
  61. 20 0
      tasks/Restart/login/ocr.json
  62. 41 3
      tasks/Restart/script_task.py
  63. 2 1
      tasks/Script/config_optimization.py
  64. 13 0
      tasks/Utils/config_enum.py
  65. 10 64
      tasks/base_task.py

+ 42 - 33
config/template.json

@@ -18,17 +18,25 @@
       "screenshot_interval": 0.3,
       "combat_screenshot_interval": 1.0,
       "task_hoarding_duration": 0,
-      "when_task_queue_empty": "goto_home"
+      "when_task_queue_empty": "goto_main"
     }
   },
   "restart": {
     "scheduler": {
-      "enable": false,
+      "enable": true,
       "next_run": "2023-01-01 00:00:00",
-      "priority": 5,
+      "priority": 0,
       "success_interval": "01 00:00:00",
       "failure_interval": "01 00:00:00",
-      "server_update": "09:00:00"
+      "server_update": "09:05:00"
+    },
+    "harvest_config": {
+      "enable": true,
+      "enable_jade": true,
+      "enable_sign": true,
+      "enable_sign_999": true,
+      "enable_mail": true,
+      "enable_soul": true
     }
   },
   "global_game": {
@@ -54,13 +62,6 @@
       "preset_enable": false,
       "preset_group": 1,
       "preset_team": 1,
-      "buff_enable": false,
-      "buff_awake_click": false,
-      "buff_soul_click": false,
-      "buff_gold_50_click": false,
-      "buff_gold_100_click": false,
-      "buff_exp_50_click": false,
-      "buff_exp_100_click": false,
       "green_enable": false,
       "green_mark": "green_left1",
       "random_click_swipt_enable": false
@@ -103,7 +104,7 @@
     "scheduler": {
       "enable": false,
       "next_run": "2023-01-01 00:00:00",
-      "priority": 6,
+      "priority": 5,
       "success_interval": "01 00:00:00",
       "failure_interval": "01 00:00:00",
       "server_update": "09:00:00"
@@ -117,13 +118,6 @@
       "preset_enable": false,
       "preset_group": 1,
       "preset_team": 1,
-      "buff_enable": false,
-      "buff_awake_click": false,
-      "buff_soul_click": false,
-      "buff_gold_50_click": false,
-      "buff_gold_100_click": false,
-      "buff_exp_50_click": false,
-      "buff_exp_100_click": false,
       "green_enable": false,
       "green_mark": "green_left1",
       "random_click_swipt_enable": false
@@ -158,13 +152,6 @@
       "preset_enable": false,
       "preset_group": 1,
       "preset_team": 1,
-      "buff_enable": false,
-      "buff_awake_click": false,
-      "buff_soul_click": false,
-      "buff_gold_50_click": false,
-      "buff_gold_100_click": false,
-      "buff_exp_50_click": false,
-      "buff_exp_100_click": false,
       "green_enable": false,
       "green_mark": "green_left1",
       "random_click_swipt_enable": false
@@ -231,13 +218,35 @@
       "preset_enable": false,
       "preset_group": 1,
       "preset_team": 1,
-      "buff_enable": false,
-      "buff_awake_click": false,
-      "buff_soul_click": false,
-      "buff_gold_50_click": false,
-      "buff_gold_100_click": false,
-      "buff_exp_50_click": false,
-      "buff_exp_100_click": false,
+      "green_enable": false,
+      "green_mark": "green_left1",
+      "random_click_swipt_enable": false
+    }
+  },
+  "bondling_fairyland": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 5,
+      "success_interval": "01 00:00:00",
+      "failure_interval": "01 00:00:00",
+      "server_update": "09:00:00"
+    },
+    "bondling_config": {
+      "bondling_mode": "mode_1",
+      "limit_time": "00:30:00",
+      "limit_count": 30,
+      "bondling_stone_enable": false,
+      "bondling_stone_class": "镇墓兽"
+    },
+    "bondling_switch_soul": {
+      "auto_switch_soul": false,
+      "tomb_guard_switch": "-1,-1",
+      "snowball_switch": "-1,-1",
+      "little_kuro_switch": "-1,-1",
+      "azure_basan_switch": "-1,-1"
+    },
+    "battle_config": {
       "green_enable": false,
       "green_mark": "green_left1",
       "random_click_swipt_enable": false

+ 0 - 0
module/dev_tools/assets_extract.py → dev_tools/assets_extract.py


+ 0 - 0
module/dev_tools/template_update.py → dev_tools/template_update.py


+ 108 - 2
module/config/config.py

@@ -206,11 +206,117 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
             logger.critical("Please enable at least one task")
             raise RequestHumanTakeover
 
+    def task_call(self, task: str=None, force_call=True):
+        """
+        回调任务,这会是在任务结束后调用
+        :param task: 调用的任务的大写名称
+        :param force_call:
+        :return:
+        """
+        task = convert_to_underscore(task)
+        if self.model.deep_get(self.model, keys=f'{task}.scheduler.next_run') is None:
+            raise ScriptError(f"Task to call: `{task}` does not exist in user config")
+
+        task_enable = self.model.deep_get(self.model, keys=f'{task}.scheduler.enable')
+        if force_call or task_enable:
+            logger.info(f"Task call: {task}")
+            next_run = datetime.now().replace(
+                microsecond=0
+            )
+            self.model.deep_set(self.model, keys=f'{task}.scheduler.next_run', value=next_run)
+            self.save()
+            return True
+        else:
+            logger.info(f"Task call: {task} (skipped because disabled by user)")
+            return False
+
+    def task_delay(self, task: str, start_time: datetime = None,
+                   success: bool=None, server: bool=True, target: timedelta=None) -> None:
+        """
+        设置下次运行时间  当然这个也是可以重写的
+        :param target: 可以自定义的下次运行时间
+        :param server: True
+        :param success: 判断是成功的还是失败的时间间隔
+        :param task: 任务名称,大驼峰的
+        :param finish: 是完成任务后的时间为基准还是开始任务的时间为基准
+        :return:
+        """
+        # 任务预处理
+        if not task:
+            task = self.task.command
+        task = convert_to_underscore(task)
+        task_object = getattr(self.model, task, None)
+        if not task_object:
+            logger.warning(f'No task named {task}')
+            return
+        scheduler = getattr(task_object, 'scheduler', None)
+        if not scheduler:
+            logger.warning(f'No scheduler in {task}')
+            return
 
+        # 任务开始时间
+        if not start_time:
+            start_time = datetime.now().replace(microsecond=0)
+
+        # 依次判断是否有自定义的下次运行时间
+        run = []
+        if success is not None:
+            interval = (
+                scheduler.success_interval
+                if success
+                else scheduler.failure_interval
+            )
+            run.append(start_time + interval)
+        # if server is not None:
+        #     if server:
+        #         server = scheduler.server_update
+        #         run.append(get_server_next_update(server))
+        if target is not None:
+            target = [target] if not isinstance(target, list) else target
+            target = nearest_future(target)
+            run.append(target)
+
+        next_run = None
+        # 排序
+        if not len(run):
+            raise ScriptError(
+                "Missing argument in delay_next_run, should set at least one"
+            )
+
+        run = min(run).replace(microsecond=0)
+        next_run = run
+        # 将这些连接起来,方便日志输出
+        kv = dict_to_kv(
+            {
+                "success": success,
+                "server_update": server,
+                "target": target,
+            },
+            allow_none=False,
+        )
+        logger.info(f"Delay task `{task}` to {next_run} ({kv})")
+
+        # 强制设定下一次的运行时间
+        if server and scheduler.server_update != time(hour=9):
+            next_run = parse_tomorrow_server(scheduler.server_update)
+
+        # 设置
+        logger.attr(f'{task}.scheduler.next_run', next_run)
+        scheduler.next_run = next_run
+        self.save()
 
 if __name__ == '__main__':
-    config = Config(config_name='oas1')
-    print(config.get_next())
+    # config = Config(config_name='oas1')
+    # print(config.get_next())
+
+    test = {}
+    test['ww1'] = {}
+    test['ww1']['ww2'] = 3
+
+    print(deep_get(test, 'ww1.ww2'))
+    print(test)
+    deep_set(test, 'ww1.ww2', 4)
+    print(deep_get(test, 'ww1.ww2'))
 
 
 

+ 1 - 0
module/config/config_manual.py

@@ -9,6 +9,7 @@ class ConfigManual:
 
     SCHEDULER_PRIORITY = """
         Restart
+        >KekkaiUtilize > KekkaiActivation > DemonEncounter
         > AreaBoss > GoldYoukai > ExperienceYoukai > Nian > RealmRaid
         > Orochi > OrochiMoans > OrochiJudgement > Sougenbi > FallenSun > EternitySea
         > ActivityShikigami

+ 2 - 1
module/config/config_menu.py

@@ -19,7 +19,8 @@ class ConfigMenu:
         # 刷御魂
         self.menu["Soul Zones"] = ['Orochi', 'Sougenbi', 'FallenSun', 'EternitySea']
         # 日常的任务
-        self.menu["Daily Task"] = ['AreaBoss', 'GoldYoukai', 'ExperienceYoukai', 'Nian', 'RealmRaid']
+        self.menu["Daily Task"] = ['AreaBoss', 'GoldYoukai', 'ExperienceYoukai', 'Nian', 'RealmRaid',
+                                   'KekkaiUtilize', 'KekkaiActivation', 'DemonEncounter']
         # 活动的任务
         self.menu["Activity Task"] = ['ActivityShikigami']
         # 很肝的任务

+ 42 - 5
module/config/config_model.py

@@ -14,10 +14,15 @@ from tasks.Component.config_base import ConfigBase
 from tasks.Script.config import Script
 from tasks.Restart.config import Restart
 from tasks.GlobalGame.config import GlobalGame
+# 每日任务-----------------------------------------------------------------------------------------------------
 from tasks.AreaBoss.config import AreaBoss
 from tasks.ExperienceYoukai.config import ExperienceYoukai
 from tasks.GoldYoukai.config import GoldYoukai
 from tasks.Nian.config import Nian
+from tasks.KekkaiUtilize.config import KekkaiUtilize
+from tasks.KekkaiActivation.config import KekkaiActivation
+from tasks.DemonEncounter.config import DemonEncounter
+# ----------------------------------------------------------------------------------------------------------------------
 from tasks.Orochi.config import Orochi
 from tasks.OrochiMoans.config import OrochiMoans
 from tasks.Sougenbi.config import Sougenbi
@@ -45,6 +50,9 @@ class ConfigModel(ConfigBase):
     gold_youkai: GoldYoukai = Field(default_factory=GoldYoukai)
     nian: Nian = Field(default_factory=Nian)
     realm_raid: RealmRaid = Field(default_factory=RealmRaid)
+    kekkai_utilize: KekkaiUtilize = Field(default_factory=KekkaiUtilize)
+    kekkai_activation: KekkaiActivation = Field(default_factory=KekkaiActivation)
+    demon_encounter: DemonEncounter = Field(default_factory=DemonEncounter)
 
     # 这些是刷御魂的
     orochi: Orochi = Field(default_factory=Orochi)
@@ -181,6 +189,38 @@ class ConfigModel(ConfigBase):
     #     logger.info(f'property change auto save')
     #     cls.save()
 
+    @staticmethod
+    def deep_get(obj, keys: str, default=None):
+        """
+        递归获取模型的值
+        :param obj:
+        :param keys:
+        :param default:
+        :return:
+        """
+        if not isinstance(keys, list):
+            keys = keys.split('.')
+        value = obj
+        try:
+            for key in keys:
+                value = getattr(value, key)
+        except AttributeError:
+            return default
+        return value
+
+    @staticmethod
+    def deep_set(obj, keys: str, value) -> bool:
+        if not isinstance(keys, list):
+            keys = keys.split('.')
+        current_obj = obj
+        try:
+            for key in keys[:-1]:
+                current_obj = getattr(current_obj, key)
+            setattr(current_obj, keys[-1], value)
+            return True
+        except (AttributeError, KeyError):
+            return False
+
 
 if __name__ == "__main__":
     try:
@@ -189,10 +229,7 @@ if __name__ == "__main__":
         print(e)
         c = ConfigModel()
 
-    c.gui_args('Nian')
-    print(c.gui_task('Nian'))
-    print(c.gui_task('AreaBoss'))
-    print(c.dict()['nian']['scheduler']['success_interval'])
-    c.save()
+    # c.save()
+    print(c.deep_get(c, 'area_boss.scheduler.success_interval'))
 
 

BIN
module/config/i18n/zh_CN.qm


+ 44 - 1
module/config/i18n/zh_CN.ts

@@ -298,7 +298,7 @@
 	<message><source>screenshot_interval_help</source><translation>执行两次截图之间的最小间隔,限制在 0.1 ~ 0.3,对于高配置电脑能降低 CPU 占用</translation></message>
 	<message><source>combat_screenshot_interval_help</source><translation>执行两次截图之间的最小间隔,限制在 0.1 ~ 1.0,能降低战斗时的 CPU 占用</translation></message>
 	<message><source>task_hoarding_duration_help</source><translation>能在收菜期间降低操作游戏的频率,任务触发后,等待 X 分钟,再一次性执行囤积的任务</translation></message>
-	<message><source>when_task_queue_empty_help</source><translation>无任务时关闭游戏,能在收菜期间降低 CPU 占用</translation></message>
+	<message><source>when_task_queue_empty_help</source><translation>无任务时关闭游戏,能在收菜期间降低 CPU 占用,'goto_home'不可选,这项是为了兼容老代码</translation></message>
 </context>
 <context>
     <name>Args</name>
@@ -443,4 +443,47 @@ mode_3策略是刷到五个契灵后开始结契,选择高级、中级盘来
 	<message><source>azure_basan_switch_help</source><translation> </translation></message>
 	<message><source>bondling_stone_class_help</source><translation> </translation></message>
 </context>	
+<context>
+    <name>Args</name>
+	<message><source>HarvestConfig</source><translation>收获奖励</translation></message>
+	<message><source>harvest_enable_help</source><translation>这个一个部分是为了在登录游戏时,自动点击赠送的奖励。是必选项,列出来是给各位阴阳师大大知道有这个东西。欢迎补充如果缺少</translation></message>
+	<message><source>Enable Jade</source><translation>永久勾玉卡</translation></message>
+	<message><source>Enable Sign</source><translation>每日签到</translation></message>
+	<message><source>Enable Sign 999</source><translation>签到999天后的签到福袋</translation></message>
+	<message><source>Enable Mail</source><translation>邮件</translation></message>
+	<message><source>Enable Soul</source><translation>御魂或者觉醒加成</translation></message>
+</context>	
+<context>
+    <name>Args</name>
+	<message><source>UtilizeScheduler</source><translation>调度</translation></message>
+	<message><source>UtilizeConfig</source><translation>寄养</translation></message>
+	<message><source>Utilize Rule</source><translation>寄养规则</translation></message>
+	<message><source>Auto Switch Sort</source><translation>切换好友列表以游戏刷新高星排序</translation></message>
+	<message><source>Shikigami Class</source><translation>寄养式神类型</translation></message>
+	<message><source>Shikigami Order</source><translation>选中第几个式神寄养</translation></message>
+	<message><source>Guild Ap Enable</source><translation>顺路收取寮补给</translation></message>
+	<message><source>Guild Assets Enable</source><translation>顺路收取寮资金</translation></message>
+	<message><source>Box Ap Enable</source><translation>顺路收取体力盒子</translation></message>
+	<message><source>Box Exp Enable</source><translation>顺路收取经验盒子</translation></message>
+	<message><source>utilize_rule_help</source><translation>挑选结界卡的规则,使用默认auto即可,当然你也可以使用过滤器自定义:
+以auto为例 "太鼓6>太鼓5>斗鱼6>斗鱼5>太鼓4>太鼓3>斗鱼4>斗鱼3"</translation></message>
+	<message><source>auto_switch_sort_help</source><translation>会自动寻找最优的坑位</translation></message>
+	<message><source>shikigami_class_help</source><translation>选择的式神类别(寄养默认选择N卡,且不建议选别的)</translation></message>
+	<message><source>shikigami_order_help</source><translation>从左开始选第几个式神</translation></message>
+	<message><source>guild_ap_enable_help</source><translation>必选项</translation></message>
+	<message><source>guild_assets_enable_help</source><translation>必选项</translation></message>
+	<message><source>box_ap_enable_help</source><translation>必选项</translation></message>
+	<message><source>box_exp_enable_help</source><translation>必选项</translation></message>
+</context>	
+<context>
+    <name>Args</name>
+	<message><source>ActivationScheduler</source><translation>调度</translation></message>
+	<message><source>ActivationConfig</source><translation>寄养</translation></message>
+	<message><source>Card Rule</source><translation>放卡规则</translation></message>
+	<message><source>Exchange Max</source><translation>收取经验后更换下来满级的式神</translation></message>
+	<message><source>Exchange Before</source><translation>收取经验前更换下来满级的式神</translation></message>
+	<message><source>card_rule_help</source><translation>规则还没想好</translation></message>
+	<message><source>exchange_before_help</source><translation>必选项</translation></message>
+	<message><source>exchange_max_help</source><translation>必选项</translation></message>
+</context>		
 </TS>

+ 58 - 0
module/config/utils.py

@@ -255,5 +255,63 @@ def parse_tomorrow_server(server_update: time) -> datetime:
     tomorrow = now + timedelta(days=1)
     return datetime.combine(tomorrow, server_update)
 
+def deep_get(d, keys, default=None):
+    """
+    Get values in dictionary safely.
+    https://stackoverflow.com/questions/25833613/safe-method-to-get-value-of-nested-dictionary
+
+    Args:
+        d (dict):
+        keys (str, list): Such as `Scheduler.NextRun.value`
+        default: Default return if key not found.
+
+    Returns:
+
+    """
+    if isinstance(keys, str):
+        keys = keys.split('.')
+    assert type(keys) is list
+    if d is None:
+        return default
+    if not keys:
+        return d
+    return deep_get(d.get(keys[0]), keys[1:], default)
+
+
+def deep_set(d, keys, value):
+    """
+    Set value into dictionary safely, imitating deep_get().
+    """
+    if isinstance(keys, str):
+        keys = keys.split('.')
+    assert type(keys) is list
+    if not keys:
+        return value
+    if not isinstance(d, dict):
+        d = {}
+    d[keys[0]] = deep_set(d.get(keys[0], {}), keys[1:], value)
+    return d
+
+
+def deep_pop(d, keys, default=None):
+    """
+    Pop value from dictionary safely, imitating deep_get().
+    """
+    if isinstance(keys, str):
+        keys = keys.split('.')
+    assert type(keys) is list
+    if not isinstance(d, dict):
+        return default
+    if not keys:
+        return default
+    elif len(keys) == 1:
+        return d.pop(keys[0], default)
+    return deep_pop(d.get(keys[0]), keys[1:], default)
+
+
+
+
+
+
 if __name__ == '__main__':
     print(parse_tomorrow_server("09:01:00"))

+ 1 - 1
module/daemon/benchmark.py

@@ -199,7 +199,7 @@ class Benchmark(DaemonBase):
 
     def run(self):
         try:
-            self.config.override(Emulator_ScreenshotMethod='ADB')
+            self.config.override(script.device.screenshot_method='ADB')
             self.device.uninstall_minicap()
 
         except RequestHumanTakeover:

+ 6 - 6
module/device/connection_attr.py

@@ -88,14 +88,14 @@ class ConnectionAttr:
             raise RequestHumanTakeover
         if self.is_wsa:
             self.serial = '127.0.0.1:58526'
-            if self.config.Emulator_ScreenshotMethod != 'uiautomator2' \
-                    or self.config.Emulator_ControlMethod != 'uiautomator2':
+            if self.config.script.device.screenshot_method != 'uiautomator2' \
+                    or self.config.script.device.control_method != 'uiautomator2':
                 with self.config.multi_set():
-                    self.config.Emulator_ScreenshotMethod = 'uiautomator2'
-                    self.config.Emulator_ControlMethod = 'uiautomator2'
+                    self.config.script.device.screenshot_method = 'uiautomator2'
+                    self.config.script.device.control_method = 'uiautomator2'
         if self.is_over_http:
-            if self.config.Emulator_ScreenshotMethod not in ["ADB", "uiautomator2", "aScreenCap"] \
-                    or self.config.Emulator_ControlMethod not in ["ADB", "uiautomator2", "minitouch"]:
+            if self.config.script.device.screenshot_method not in ["ADB", "uiautomator2", "aScreenCap"] \
+                    or self.config.script.device.control_method not in ["ADB", "uiautomator2", "minitouch"]:
                 logger.warning(
                     f'When connecting to a device over http: {self.serial} '
                     f'ScreenshotMethod can only use ["ADB", "uiautomator2", "aScreenCap"], '

+ 4 - 3
module/device/device.py

@@ -101,7 +101,8 @@ class Device(Screenshot, Control, AppControl, EmulatorManager):
     def release_during_wait(self):
         # Scrcpy server is still sending video stream,
         # stop it during wait
-        if self.config.Emulator_ScreenshotMethod == 'scrcpy':
+        # self.config.script.device.screenshot_method = 'scrcpy'
+        if self.config.script.device.screenshot_method == 'scrcpy':
             self._scrcpy_server_stop()
 
     def stuck_record_add(self, button):
@@ -207,7 +208,7 @@ class Device(Screenshot, Control, AppControl, EmulatorManager):
         self.stuck_record_check = empty_function
 
     def app_start(self):
-        if not self.config.Error_HandleError:
+        if not self.config.script.error.handle_error:
             logger.critical('No app stop/start, because HandleError disabled')
             logger.critical('Please enable Alas.Error.HandleError or manually login to AzurLane')
             raise RequestHumanTakeover
@@ -216,7 +217,7 @@ class Device(Screenshot, Control, AppControl, EmulatorManager):
         self.click_record_clear()
 
     def app_stop(self):
-        if not self.config.Error_HandleError:
+        if not self.config.script.error.handle_error:
             logger.critical('No app stop/start, because HandleError disabled')
             logger.critical('Please enable Alas.Error.HandleError or manually login to AzurLane')
             raise RequestHumanTakeover

+ 1 - 1
module/device/method/window.py

@@ -144,7 +144,7 @@ class Window(Handle):
         # print(f"我点击的x:{x}, y:{y}")
         emulator_type = len(self.control_handle_list)
         if emulator_type == 2:  # mumu模拟器
-            SendMessage(self.control_handle_list[0], WM_ACTIVATE, WA_ACTIVE, 0)  # 激活窗口
+            # SendMessage(self.control_handle_list[0], WM_ACTIVATE, WA_ACTIVE, 0)  # 激活窗口
             SendMessage(self.control_handle_list[1], WM_ACTIVATE, WA_ACTIVE, 0)  # 激活窗口
             SendMessage(self.control_handle_list[0], WM_LBUTTONDOWN, 0, MAKELONG(x, y+self.mumu_head_height))  # 模拟鼠标按下 先是父窗口 上面的框高度是57
             time.sleep((random.randint(100, 200)) / 1000.0)  # 点击弹起改为随机,时间100ms-200ms

+ 1 - 1
module/device/screenshot.py

@@ -168,7 +168,7 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window):
             raise ScriptError(f'Unknown screenshot interval: {interval}')
         # Screenshot interval in scrcpy is meaningless,
         # video stream is received continuously no matter you use it or not.
-        # if self.config.Emulator_ScreenshotMethod == 'scrcpy':
+        # if self.config.script.device.screenshot_method == 'scrcpy':
         if self.config.script.device.screenshot_method == 'scrcpy':
             interval = 0.1
 

+ 6 - 4
module/ocr/base_ocr.py

@@ -56,7 +56,7 @@ class BaseCor:
         :param area:
         :param keyword:
         """
-        self.name = name
+        self.name = name.upper()
         if isinstance(mode, str):
             self.mode = OcrMode[mode.upper()]
         elif isinstance(mode, OcrMode):
@@ -115,7 +115,7 @@ class BaseCor:
             result = ""
         # after proces
         result = self.after_process(result)
-        logger.info("ocr result score: %s%s" % (result,score))
+        # logger.info("ocr result score: %s%s" % (result,score))
         logger.attr(name='%s %ss' % (self.name, float2str(time.time() - start_time)),
                     text=f'[{result}]')
         return result
@@ -137,7 +137,7 @@ class BaseCor:
             result = ""
         # after proces
         result = self.after_process(result)
-        logger.info("ocr result score: %s" % score)
+        # logger.info("ocr result score: %s" % score)
         logger.attr(name='%s %ss' % (self.name, float2str(time.time() - start_time)),
                     text=f'[{result}]')
         return result
@@ -158,7 +158,7 @@ class BaseCor:
         results = []
         # after proces
         for result in boxed_results:
-            logger.info("ocr result score: %s" % result.score)
+            # logger.info("ocr result score: %s" % result.score)
             if result.score < self.score:
                 continue
             result.ocr_text = self.after_process(result.ocr_text)
@@ -218,3 +218,5 @@ class BaseCor:
             return indices
 
 
+
+

+ 2 - 2
module/ocr/sub_ocr.py

@@ -78,10 +78,10 @@ class Single(BaseCor):
                 return result
 
             # 如果没有识别到,这个时候考虑到可能是竖方向的文本, 使用detect_and_ocr来进行识别
-            logger.info(f"OCR {self.name}: No text detected in ROI, try to detect vertically")
+            logger.info(f"[{self.name}] Try to detect vertically")
             result = self.detect_and_ocr(image)
             if not result:
-                logger.info(f"OCR {self.name}: No text detected in ROI")
+                logger.info(f"[{self.name}]: No text detected in ROI")
                 return ""
             if result[0].ocr_text != "" and result[0].score > self.score:
                 return result[0].ocr_text

+ 4 - 4
script.py

@@ -282,7 +282,7 @@ class Script:
                     self.run('start')
                 elif method == 'goto_main':
                     logger.info('Goto main page during wait')
-                    self.run('goto_main')
+                    self.run('GotoMain')
                     self.device.release_during_wait()
                     if not self.wait_until(task.next_run):
                         del_cached_property(self, 'config')
@@ -300,10 +300,10 @@ class Script:
     def run(self, command: str) -> bool:
         """
 
-        :param command:
+        :param command:  大写驼峰命名的任务名字
         :return:
         """
-        if command == 'start' and command == 'goto_main':
+        if command == 'start' or command == 'goto_main':
             logger.error(f'Invalid command `{command}`')
 
         try:
@@ -392,7 +392,7 @@ class Script:
             # Skip first restart
             if self.is_first_task and task == 'Restart':
                 logger.info('Skip task `Restart` at scheduler start')
-                self.config.task_delay(server_update=True)
+                self.config.task_delay(task='Restart', finish=True, success=True, server=True)
                 del_cached_property(self, 'config')
                 continue
 

+ 3 - 2
tasks/Component/GeneralBattle/general_battle.py

@@ -150,19 +150,20 @@ class GeneralBattle(BaseTask, GeneralBattleAssets):
         # 有的时候是长战斗,需要在设置stuck检测为长战斗
         # 但是无需取消设置,因为如果有点击或者滑动的话 handle_control_check会自行取消掉
         self.device.stuck_record_add('BATTLE_STATUS_S')
+        self.device.click_record_clear()
         # 战斗过程 随机点击和滑动 防封
         logger.info("Start battle process")
         win: bool = False
         while 1:
             self.screenshot()
             # 如果出现赢 就点击
-            if self.appear(self.I_WIN, threshold=0.6):
+            if self.appear(self.I_WIN, threshold=0.8):
                 logger.info("Battle result is win")
                 win = True
                 break
 
             # 如果出现失败 就点击,返回False
-            if self.appear(self.I_FALSE, threshold=0.6):
+            if self.appear(self.I_FALSE, threshold=0.8):
                 logger.info("Battle result is false")
                 win = False
                 break

+ 15 - 1
tasks/DemonEncounter/config.py

@@ -2,5 +2,19 @@
 # @author runhey
 # github https://github.com/runhey
 from pydantic import BaseModel, Field
-from tasks.Component.config_base import ConfigBase
+from enum import Enum
+from datetime import datetime, time
+
+from tasks.Component.config_scheduler import Scheduler
+from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
+from tasks.Utils.config_enum import ShikigamiClass
+
+class UtilizeScheduler(Scheduler):
+    priority = Field(default=2, description='priority_help')
+
+class DemonEncounter(ConfigBase):
+    scheduler: UtilizeScheduler = Field(default_factory=UtilizeScheduler)
+    general_battle_config: GeneralBattleConfig = Field(default_factory=GeneralBattleConfig)
+
 

+ 17 - 0
tasks/DemonEncounter/script_task.py

@@ -0,0 +1,17 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+
+from module.logger import logger
+from module.exception import TaskEnd
+
+from tasks.GameUi.game_ui import GameUi
+
+
+class ScriptTask(GameUi):
+
+    def run(self):
+        pass
+
+

+ 22 - 0
tasks/GlobalGame/assets.py

@@ -25,3 +25,25 @@ class GlobalGameAssets:
 	I_CLIENT_CLEAR = RuleImage(roi_front=(578,369,151,72), roi_back=(578,369,151,72), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/gg/gg_client_clear.png")
 
 
+	# Click Rule Assets
+	# description 
+	C_UI_REWARD = RuleClick(roi_front=(919,160,208,368), roi_back=(72,107,244,503), name="ui_reward")
+
+
+	# Image Rule Assets
+	# description 
+	I_UI_CONFIRM = RuleImage(roi_front=(667,398,179,66), roi_back=(667,398,179,66), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/ui/ui_ui_confirm.png")
+	# description 
+	I_UI_CANCEL = RuleImage(roi_front=(432,403,177,62), roi_back=(432,403,177,62), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/ui/ui_ui_cancel.png")
+	# '获得奖励' 四个大字 
+	I_UI_REWARD = RuleImage(roi_front=(481,185,317,42), roi_back=(464,142,350,129), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/ui/ui_ui_reward.png")
+	# description 
+	I_UI_BACK_RED = RuleImage(roi_front=(1041,111,34,38), roi_back=(834,15,427,200), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/ui/ui_ui_back_red.png")
+	# description 
+	I_UI_BACK_YELLOW = RuleImage(roi_front=(26,17,47,46), roi_back=(0,0,100,100), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/ui/ui_ui_back_yellow.png")
+	# description 
+	I_UI_BACK_BLUE = RuleImage(roi_front=(32,37,51,45), roi_back=(2,1,133,119), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/ui/ui_ui_back_blue.png")
+	# description 
+	I_UI_AWARD = RuleImage(roi_front=(577,499,100,100), roi_back=(530,408,199,220), threshold=0.8, method="Template matching", file="./tasks/GlobalGame/ui/ui_ui_award.png")
+
+

+ 8 - 0
tasks/GlobalGame/ui/click.json

@@ -0,0 +1,8 @@
+[
+  {
+    "itemName": "ui_reward",
+    "roiFront": "919,160,208,368",
+    "roiBack": "72,107,244,503",
+    "description": "description"
+  }
+]

+ 65 - 0
tasks/GlobalGame/ui/image.json

@@ -0,0 +1,65 @@
+[
+  {
+    "itemName": "ui_confirm",
+    "imageName": "ui_ui_confirm.png",
+    "roiFront": "667,398,179,66",
+    "roiBack": "667,398,179,66",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "ui_cancel",
+    "imageName": "ui_ui_cancel.png",
+    "roiFront": "432,403,177,62",
+    "roiBack": "432,403,177,62",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "ui_reward",
+    "imageName": "ui_ui_reward.png",
+    "roiFront": "481,185,317,42",
+    "roiBack": "464,142,350,129",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "'获得奖励' 四个大字"
+  },
+  {
+    "itemName": "ui_back_red",
+    "imageName": "ui_ui_back_red.png",
+    "roiFront": "1041,111,34,38",
+    "roiBack": "834,15,427,200",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "ui_back_yellow",
+    "imageName": "ui_ui_back_yellow.png",
+    "roiFront": "26,17,47,46",
+    "roiBack": "0,0,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "ui_back_blue",
+    "imageName": "ui_ui_back_blue.png",
+    "roiFront": "32,37,51,45",
+    "roiBack": "2,1,133,119",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "ui_award",
+    "imageName": "ui_ui_award.png",
+    "roiFront": "577,499,100,100",
+    "roiBack": "530,408,199,220",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  }
+]

BIN
tasks/GlobalGame/ui/ui_ui_award.png


BIN
tasks/GlobalGame/ui/ui_ui_back_blue.png


BIN
tasks/GlobalGame/ui/ui_ui_back_red.png


BIN
tasks/GlobalGame/ui/ui_ui_back_yellow.png


BIN
tasks/GlobalGame/ui/ui_ui_cancel.png


BIN
tasks/GlobalGame/ui/ui_ui_confirm.png


BIN
tasks/GlobalGame/ui/ui_ui_ensure.png


BIN
tasks/GlobalGame/ui/ui_ui_reward.png


BIN
tasks/GlobalGame/ui/ui_ui_rewards.png


+ 15 - 0
tasks/GotoMain/script_task.py

@@ -0,0 +1,15 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+from tasks.GameUi.game_ui import GameUi
+from tasks.GameUi.page import page_main
+from module.exception import TaskEnd
+
+
+class ScriptTask(GameUi):
+
+    def run(self) -> None:
+        self.ui_get_current_page()
+        self.ui_goto(page_main)
+        raise TaskEnd('Goto main end')

+ 28 - 0
tasks/KekkaiActivation/config.py

@@ -0,0 +1,28 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+from enum import Enum
+from datetime import datetime, time
+
+from tasks.Component.config_scheduler import Scheduler
+from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Utils.config_enum import ShikigamiClass
+
+class ActivationScheduler(Scheduler):
+    priority = Field(default=2, description='priority_help')
+    success_interval: TimeDelta = Field(default=TimeDelta(hours=10), description='success_interval_help')
+    failure_interval: TimeDelta = Field(default=TimeDelta(hours=10), description='failure_interval_help')
+
+class ActivationConfig(BaseModel):
+    card_rule: str = Field(default='auto', description='card_rule_help')
+    exchange_before: bool = Field(default=True, description='exchange_before_help')
+    exchange_max: bool = Field(default=True, description='exchange_max_help')
+    shikigami_class: ShikigamiClass = Field(default=ShikigamiClass.N, description='shikigami_class_help')
+
+
+
+class KekkaiActivation(ConfigBase):
+    scheduler: ActivationScheduler = Field(default_factory=ActivationScheduler)
+    activation_config: ActivationConfig = Field(default_factory=ActivationConfig)
+

+ 17 - 0
tasks/KekkaiActivation/script_task.py

@@ -0,0 +1,17 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+
+from module.logger import logger
+from module.exception import TaskEnd
+
+from tasks.GameUi.game_ui import GameUi
+
+
+class ScriptTask(GameUi):
+
+    def run(self):
+        pass
+
+

+ 33 - 0
tasks/KekkaiUtilize/config.py

@@ -0,0 +1,33 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+from enum import Enum
+from datetime import datetime, time
+
+from tasks.Component.config_scheduler import Scheduler
+from tasks.Component.config_base import ConfigBase, TimeDelta
+from tasks.Utils.config_enum import ShikigamiClass
+
+class UtilizeScheduler(Scheduler):
+    priority = Field(default=2, description='priority_help')
+    success_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='success_interval_help')
+    failure_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='failure_interval_help')
+
+class UtilizeConfig(BaseModel):
+    utilize_rule: str = Field(default='auto', description='utilize_rule_help')
+    auto_switch_sort: bool = Field(default=True, description='auto_switch_sort_help')
+    shikigami_class: ShikigamiClass = Field(default=ShikigamiClass.N, description='shikigami_class_help')
+    shikigami_order: int = Field(default=4, description='shikigami_order_help')
+    guild_ap_enable: bool = Field(default=True, description='guild_ap_enable_help')
+    guild_assets_enable: bool = Field(default=True, description='guild_assets_enable_help')
+    box_ap_enable: bool = Field(default=True, description='box_ap_enable_help')
+    box_exp_enable: bool = Field(default=True, description='box_exp_enable_help')
+
+
+class KekkaiUtilize(ConfigBase):
+    scheduler: UtilizeScheduler = Field(default_factory=UtilizeScheduler)
+    utilize_config: UtilizeConfig = Field(default_factory=UtilizeConfig)
+
+
+

+ 17 - 0
tasks/KekkaiUtilize/script_task.py

@@ -0,0 +1,17 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+
+from module.logger import logger
+from module.exception import TaskEnd
+
+from tasks.GameUi.game_ui import GameUi
+
+
+class ScriptTask(GameUi):
+
+    def run(self):
+        pass
+
+

+ 6 - 2
tasks/Orochi/script_task.py

@@ -262,11 +262,15 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
             # 点击挑战
             while 1:
                 self.screenshot()
+                if not self.appear(self.I_OROCHI_FIRE):
+                    continue
+
+                if self.appear_then_click(self.I_OROCHI_FIRE, interval=1):
+                    pass
+
                 if not self.appear(self.I_OROCHI_FIRE):
                     self.run_general_battle(config=self.config.orochi.general_battle_config)
                     break
-                if self.appear_then_click(self.I_OROCHI_FIRE, interval=1):
-                    continue
 
         # 回去
         while 1:

+ 42 - 1
tasks/Restart/assets.py

@@ -8,5 +8,46 @@ from module.atom.list import RuleList
 # This file was automatically generated by module/dev_tools/assets_extract.py.
 # Don't modify it manually.
 class RestartAssets: 
-	pass
+
+
+	# Image Rule Assets
+	# 点击勾玉 
+	I_HARVEST_JADE = RuleImage(roi_front=(732,489,34,33), roi_back=(177,451,963,100), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_jade.png")
+	# 签到小图标 
+	I_HARVEST_SIGN = RuleImage(roi_front=(295,496,32,43), roi_back=(70,481,889,71), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_sign.png")
+	# description 
+	I_HARVEST_SIGN_2 = RuleImage(roi_front=(592,135,100,252), roi_back=(592,135,100,252), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_sign_2.png")
+	# 999签到福袋 
+	I_HARVEST_SIGN_999 = RuleImage(roi_front=(345,494,23,29), roi_back=(51,459,888,92), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_sign_999.png")
+	# 邮件小图标 
+	I_HARVEST_MAIL = RuleImage(roi_front=(337,505,37,25), roi_back=(38,476,880,78), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_mail.png")
+	# 全部收取 
+	I_HARVEST_MAIL_ALL = RuleImage(roi_front=(80,622,75,64), roi_back=(80,622,75,64), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_mail_all.png")
+	# 有些邮件需要点击一次 
+	I_HARVEST_MAIL_OPEN = RuleImage(roi_front=(157,122,66,62), roi_back=(139,86,100,487), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_mail_open.png")
+	# 确认收取邮件 
+	I_HARVEST_MAIL_CONFIRM = RuleImage(roi_front=(687,543,168,64), roi_back=(687,543,168,64), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_mail_confirm.png")
+	# description 
+	I_HARVEST_SOUL = RuleImage(roi_front=(241,497,38,36), roi_back=(68,480,930,72), threshold=0.8, method="Template matching", file="./tasks/Restart/harvest/harvest_harvest_soul.png")
+
+
+	# Image Rule Assets
+	# 庭院卷轴打开 
+	I_LOGIN_SCROOLL_OPEN = RuleImage(roi_front=(1208,609,33,83), roi_back=(1208,609,33,83), threshold=0.8, method="Template matching", file="./tasks/Restart/login/login_login_scrooll_open.png")
+	# 庭院卷轴关闭 
+	I_LOGIN_SCROOLL_CLOSE = RuleImage(roi_front=(1184,628,35,45), roi_back=(1184,628,35,45), threshold=0.8, method="Template matching", file="./tasks/Restart/login/login_login_scrooll_close.png")
+	# description 
+	I_LOGIN_RED_CLOSE = RuleImage(roi_front=(1158,62,39,37), roi_back=(912,42,309,281), threshold=0.8, method="Template matching", file="./tasks/Restart/login/login_login_red_close.png")
+	# description 
+	I_LOGIN_YELLOW_CLOSE = RuleImage(roi_front=(29,17,46,44), roi_back=(0,0,94,86), threshold=0.8, method="Template matching", file="./tasks/Restart/login/login_login_yellow_close.png")
+	# 用于判断是否出现登录选区的 
+	I_LOGIN_8 = RuleImage(roi_front=(19,572,53,60), roi_back=(19,572,53,60), threshold=0.8, method="Template matching", file="./tasks/Restart/login/login_login_8.png")
+
+
+	# Ocr Rule Assets
+	# 正在连接服务器 
+	O_LOGIN_NETWORK = RuleOcr(roi=(534,649,189,39), area=(210,492,100,100), mode="Single", method="Default", keyword="正在连接服务器", name="login_network")
+	# Ocr-description 
+	O_LOGIN_ENTER_GAME = RuleOcr(roi=(550,567,176,56), area=(558,574,154,49), mode="Single", method="Default", keyword="进入游戏", name="login_enter_game")
+
 

+ 25 - 2
tasks/Restart/config.py

@@ -3,9 +3,32 @@
 # github https://github.com/runhey
 from pydantic import BaseModel, Field
 
-from tasks.Component.config_scheduler import Scheduler
+from tasks.Restart.config_scheduler import RestartScheduler
 from tasks.Component.config_base import ConfigBase
 
+
+
+class HarvestConfig(BaseModel):
+    # 默认启用
+    enable: bool = Field(default=True, description='harvest_enable_help')
+    # 永久勾玉卡
+    enable_jade: bool = Field(default=True)
+    # 签到
+    enable_sign: bool = Field(default=True)
+    # 999天的签到福袋
+    enable_sign_999: bool = Field(default=True)
+    # 邮件
+    enable_mail: bool = Field(default=True)
+    # 御魂加成
+    enable_soul: bool = Field(default=True)
+
+
+
+
+
+
+
 class Restart(ConfigBase):
-    scheduler: Scheduler = Field(default_factory=Scheduler)
+    scheduler: RestartScheduler = Field(default_factory=RestartScheduler)
+    harvest_config: HarvestConfig = Field(default_factory=HarvestConfig)
 

+ 5 - 18
tasks/Restart/config_scheduler.py

@@ -4,25 +4,12 @@
 from enum import Enum
 from datetime import datetime, time
 from pydantic import BaseModel, ValidationError, validator, Field
+from tasks.Component.config_scheduler import Scheduler
 
 from module.logger import logger
 
-class Scheduler(BaseModel):
-    enable: bool = Field(default=True, description='none')
-    next_run: datetime = Field(default="2023-01-01 00:00:00", description='无需手动修改')
-    priority: int = Field(default=0, description='重启的优先级最高,数值为0,保持默认即可')
+class RestartScheduler(Scheduler):
+    enable: bool = Field(default=True, description='enable_help')
+    priority: int = Field(default=0, description='priority_help')
+    server_update: time = Field(default=time(hour=9, minute=5, second=0), description='server_update_help')
 
-    success_interval: float = Field(default=0,
-                                    description='none')
-    failure_interval: float = Field(default=0,
-                                    description='none')
-    server_update: time = Field(default="00:00", description='none')
-
-    @validator('next_run', pre=True, always=True)
-    def parse_next_run(cls, value):
-        if isinstance(value, str):
-            try:
-                return datetime.fromisoformat(value)
-            except ValueError:
-                raise ValueError('Invalid next_run value. Expected format: YYYY-MM-DD HH:MM:SS')
-        return value

BIN
tasks/Restart/harvest/harvest_harvest_jade.png


BIN
tasks/Restart/harvest/harvest_harvest_mail.png


BIN
tasks/Restart/harvest/harvest_harvest_mail_all.png


BIN
tasks/Restart/harvest/harvest_harvest_mail_confirm.png


BIN
tasks/Restart/harvest/harvest_harvest_mail_open.png


BIN
tasks/Restart/harvest/harvest_harvest_sign.png


BIN
tasks/Restart/harvest/harvest_harvest_sign_2.png


BIN
tasks/Restart/harvest/harvest_harvest_sign_999.png


BIN
tasks/Restart/harvest/harvest_harvest_soul.png


+ 83 - 0
tasks/Restart/harvest/image.json

@@ -0,0 +1,83 @@
+[
+  {
+    "itemName": "harvest_jade",
+    "imageName": "harvest_harvest_jade.png",
+    "roiFront": "732,489,34,33",
+    "roiBack": "177,451,963,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "点击勾玉"
+  },
+  {
+    "itemName": "harvest_sign",
+    "imageName": "harvest_harvest_sign.png",
+    "roiFront": "295,496,32,43",
+    "roiBack": "70,481,889,71",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "签到小图标"
+  },
+  {
+    "itemName": "harvest_sign_2",
+    "imageName": "harvest_harvest_sign_2.png",
+    "roiFront": "592,135,100,252",
+    "roiBack": "592,135,100,252",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "harvest_sign_999",
+    "imageName": "harvest_harvest_sign_999.png",
+    "roiFront": "345,494,23,29",
+    "roiBack": "51,459,888,92",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "999签到福袋"
+  },
+  {
+    "itemName": "harvest_mail",
+    "imageName": "harvest_harvest_mail.png",
+    "roiFront": "337,505,37,25",
+    "roiBack": "38,476,880,78",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "邮件小图标"
+  },
+  {
+    "itemName": "harvest_mail_all",
+    "imageName": "harvest_harvest_mail_all.png",
+    "roiFront": "80,622,75,64",
+    "roiBack": "80,622,75,64",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "全部收取"
+  },
+  {
+    "itemName": "harvest_mail_open",
+    "imageName": "harvest_harvest_mail_open.png",
+    "roiFront": "157,122,66,62",
+    "roiBack": "139,86,100,487",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "有些邮件需要点击一次"
+  },
+  {
+    "itemName": "harvest_mail_confirm",
+    "imageName": "harvest_harvest_mail_confirm.png",
+    "roiFront": "687,543,168,64",
+    "roiBack": "687,543,168,64",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "确认收取邮件"
+  },
+  {
+    "itemName": "harvest_soul",
+    "imageName": "harvest_harvest_soul.png",
+    "roiFront": "241,497,38,36",
+    "roiBack": "68,480,930,72",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  }
+]

BIN
tasks/Restart/harvest/image_name.png


+ 146 - 0
tasks/Restart/login.py

@@ -0,0 +1,146 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from tasks.Restart.config_scheduler import Scheduler
+from module.logger import logger
+from module.base.timer import Timer
+
+from tasks.Restart.assets import RestartAssets
+from tasks.base_task import BaseTask
+from module.exception import TaskEnd, RequestHumanTakeover, GameTooManyClickError, GameStuckError
+
+
+class LoginHandler(BaseTask, RestartAssets):
+
+    def _app_handle_login(self) -> bool:
+        """
+        最终是在庭院界面
+        :return:
+        """
+        logger.hr('App login')
+
+        confirm_timer = Timer(1.5, count=2).start()
+        orientation_timer = Timer(10)
+        login_success = False
+
+        while 1:
+            # Watch device rotation
+            if not login_success and orientation_timer.reached():
+                # Screen may rotate after starting an app
+                self.device.get_orientation()
+                orientation_timer.reset()
+
+            self.screenshot()
+
+
+
+            # 确认进入庭院
+            if self.appear_then_click(self.I_LOGIN_SCROOLL_CLOSE, interval=2):
+                logger.info('Open scroll')
+                continue
+            if self.appear(self.I_LOGIN_SCROOLL_OPEN, interval=0.2):
+                if confirm_timer.reached():
+                    logger.info('Login to main confirm')
+                    break
+            else:
+                confirm_timer.reset()
+            # 登录成功
+            if self.appear(self.I_LOGIN_SCROOLL_OPEN, interval=0.5):
+                logger.info('Login success')
+                login_success = True
+
+            # 网络异常
+            # if self.ocr_appear(self.O_LOGIN_NETWORK):
+            #     logger.error('Network error')
+            #     raise RequestHumanTakeover('Network error')
+
+            # 右上角的红色的关闭
+            if self.appear_then_click(self.I_LOGIN_RED_CLOSE, interval=0.6):
+                logger.info('Close red close')
+                continue
+            # 左上角的黄色关闭
+            if self.appear_then_click(self.I_LOGIN_YELLOW_CLOSE, interval=0.6):
+                logger.info('Close yellow close')
+                continue
+
+            # 点击’进入游戏‘
+            if not self.appear(self.I_LOGIN_8):
+                continue
+            if self.ocr_appear_click(self.O_LOGIN_ENTER_GAME, interval=2.5):
+                continue
+
+        return login_success
+
+
+    def app_handle_login(self) -> bool:
+        for _ in range(2):
+            self.device.stuck_record_clear()
+            self.device.click_record_clear()
+            try:
+                self._app_handle_login()
+                if self.config.restart.harvest_config.enable:
+                    self.harvest()
+                return True
+            except (GameTooManyClickError, GameStuckError) as e:
+                logger.warning(e)
+                self.device.app_stop()
+                self.device.app_start()
+                continue
+
+        logger.critical('Login failed more than 3')
+        logger.critical('Azur Lane server may be under maintenance, or you may lost network connection')
+        raise RequestHumanTakeover
+
+
+
+    def harvest(self):
+        """
+        获得奖励
+        :return: 如果没有发现任何奖励后退出
+        """
+        logger.hr('Harvest')
+        timer_harvest = Timer(3)  # 如果连续3秒没有发现任何奖励,退出
+        while 1:
+            self.screenshot()
+
+            # 点击'获得奖励'
+            if self.ui_reward_appear_click():
+                continue
+            # 获得奖励
+            if self.appear_then_click(self.I_UI_AWARD, interval=1):
+                continue
+
+            # 勾玉
+            if self.appear_then_click(self.I_HARVEST_JADE, interval=1):
+                continue
+            # 签到
+            if self.appear_then_click(self.I_HARVEST_SIGN, interval=1):
+                continue
+            if self.appear_then_click(self.I_HARVEST_SIGN_2, interval=1):
+                continue
+            # 999天的签到福袋
+            if self.appear_then_click(self.I_HARVEST_SIGN_999, interval=1):
+                continue
+            # 邮件
+            if self.appear_then_click(self.I_HARVEST_MAIL, interval=1):
+                continue
+            if self.appear_then_click(self.I_HARVEST_MAIL_ALL, interval=1):
+                continue
+            if self.appear_then_click(self.I_HARVEST_MAIL_CONFIRM, interval=1):
+                continue
+            if self.appear_then_click(self.I_HARVEST_MAIL_OPEN, interval=1):
+                continue
+
+
+            # 红色的关闭
+            if self.appear_then_click(self.I_UI_BACK_RED, interval=1):
+                continue
+
+            # 三秒内没有发现任何奖励,退出
+            if not timer_harvest.started():
+                timer_harvest.start()
+            else:
+                if timer_harvest.reached():
+                    logger.info('No more reward')
+                    return
+

+ 47 - 0
tasks/Restart/login/image.json

@@ -0,0 +1,47 @@
+[
+  {
+    "itemName": "login_scrooll_open",
+    "imageName": "login_login_scrooll_open.png",
+    "roiFront": "1208,609,33,83",
+    "roiBack": "1208,609,33,83",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "庭院卷轴打开"
+  },
+  {
+    "itemName": "login_scrooll_close",
+    "imageName": "login_login_scrooll_close.png",
+    "roiFront": "1184,628,35,45",
+    "roiBack": "1184,628,35,45",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "庭院卷轴关闭"
+  },
+  {
+    "itemName": "login_red_close",
+    "imageName": "login_login_red_close.png",
+    "roiFront": "1158,62,39,37",
+    "roiBack": "912,42,309,281",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "login_yellow_close",
+    "imageName": "login_login_yellow_close.png",
+    "roiFront": "29,17,46,44",
+    "roiBack": "0,0,94,86",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "login_8",
+    "imageName": "login_login_8.png",
+    "roiFront": "19,572,53,60",
+    "roiBack": "19,572,53,60",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "用于判断是否出现登录选区的"
+  }
+]

BIN
tasks/Restart/login/login_login_8.png


BIN
tasks/Restart/login/login_login_red_close.png


BIN
tasks/Restart/login/login_login_scrooll_close.png


BIN
tasks/Restart/login/login_login_scrooll_open.png


BIN
tasks/Restart/login/login_login_yellow_close.png


+ 20 - 0
tasks/Restart/login/ocr.json

@@ -0,0 +1,20 @@
+[
+  {
+    "itemName": "login_network",
+    "roiFront": "534,649,189,39",
+    "roiBack": "210,492,100,100",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "正在连接服务器",
+    "description": "正在连接服务器"
+  },
+  {
+    "itemName": "login_enter_game",
+    "roiFront": "550,567,176,56",
+    "roiBack": "558,574,154,49",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "进入游戏",
+    "description": "Ocr-description"
+  }
+]

+ 41 - 3
tasks/Restart/script_task.py

@@ -4,20 +4,58 @@
 
 
 from tasks.Restart.config_scheduler import Scheduler
-from module.logger import logger
+from tasks.Restart.login import LoginHandler
 from tasks.Restart.assets import RestartAssets
 from tasks.base_task import BaseTask
-from module.exception import TaskEnd
+
+from module.logger import logger
+from module.exception import TaskEnd, RequestHumanTakeover
 
 
 
 
-class ScriptTask(BaseTask):
+class ScriptTask(LoginHandler):
 
     def run(self) -> None:
+        """
+        主要就是登录的模块
+        :return:
+        """
+        self.app_restart()
         raise TaskEnd('ScriptTask end')
 
 
+    def app_stop(self):
+        logger.hr('App stop')
+        self.device.app_stop()
+
+    def app_start(self):
+        logger.hr('App start')
+        self.device.app_start()
+        self.app_handle_login()
+        # self.ensure_no_unfinished_campaign()
+
+    def app_restart(self):
+        logger.hr('App restart')
+        self.device.app_stop()
+        self.device.app_start()
+        self.app_handle_login()
+
+        # self.config.task_delay(server_update=True)
+        self.set_next_run(task='Restart', success=True, finish=True, server=True)
+
+
+
+if __name__ == '__main__':
+    from module.config.config import Config
+    from module.device.device import Device
+
+    config = Config('oas1')
+    device = Device(config)
+    task = ScriptTask(config, device)
+    task.harvest()
+
+
 
 
 

+ 2 - 1
tasks/Script/config_optimization.py

@@ -7,6 +7,7 @@ from pydantic import BaseModel, ValidationError, validator, Field
 from module.logger import logger
 
 class WhenTaskQueueEmpty(str, Enum):
+    GOTO_MAIN = 'goto_main'
     GOTO_HOME = 'goto_home'
     CLOSE_GAME = 'close_game'
 
@@ -17,6 +18,6 @@ class Optimization(BaseModel):
                                               description='combat_screenshot_interval_help')
     task_hoarding_duration: float = Field(default=0,
                                           description='task_hoarding_duration_help')
-    when_task_queue_empty: WhenTaskQueueEmpty = Field(default=WhenTaskQueueEmpty.GOTO_HOME,
+    when_task_queue_empty: WhenTaskQueueEmpty = Field(default=WhenTaskQueueEmpty.GOTO_MAIN,
                                                       description='when_task_queue_empty_help')
 

+ 13 - 0
tasks/Utils/config_enum.py

@@ -0,0 +1,13 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+
+class ShikigamiClass(str, Enum):
+    SP = 'SP'
+    SSR = 'SSR'
+    SR = 'SR'
+    R = 'R'
+    N = 'N'
+    # 材料
+    MATERIAL = 'MATERIAL'

+ 10 - 64
tasks/base_task.py

@@ -421,71 +421,17 @@ class BaseTask(GlobalGameAssets):
         :param finish: 是完成任务后的时间为基准还是开始任务的时间为基准
         :return:
         """
-
-        # 任务预处理
-        if not task:
-            task = self.config.task.command
-        task = convert_to_underscore(task)
-        task_object = getattr(self.config.model, task, None)
-        if not task_object:
-            logger.warning(f'No task named {task}')
-            return
-        scheduler = getattr(task_object, 'scheduler', None)
-        if not scheduler:
-            logger.warning(f'No scheduler in {task}')
-            return
-
-        # 任务开始时间
         if finish:
-            start_time = datetime.now()
+            start_time = datetime.now().replace(microsecond=0)
         else:
             start_time = self.start_time
+        self.config.task_delay(task, start_time=start_time, success=success, server=server, target=target)
 
-        # 依次判断是否有自定义的下次运行时间
-        run = []
-        if success is not None:
-            interval = (
-                scheduler.success_interval
-                if success
-                else scheduler.failure_interval
-            )
-            run.append(start_time + interval)
-        # if server is not None:
-        #     if server:
-        #         server = scheduler.server_update
-        #         run.append(get_server_next_update(server))
-        if target is not None:
-            target = [target] if not isinstance(target, list) else target
-            target = nearest_future(target)
-            run.append(target)
-
-
-        next_run = None
-        # 排序
-        if not len(run):
-            raise ScriptError(
-                "Missing argument in delay_next_run, should set at least one"
-            )
-
-        run = min(run).replace(microsecond=0)
-        next_run = run
-        # 将这些连接起来,方便日志输出
-        kv = dict_to_kv(
-            {
-                "success": success,
-                "server_update": server,
-                "target": target,
-            },
-            allow_none=False,
-        )
-        logger.info(f"Delay task `{task}` to {next_run} ({kv})")
-
-        # 强制设定下一次的运行时间
-        if server and scheduler.server_update != time(hour=9):
-            next_run = parse_tomorrow_server(scheduler.server_update)
-
-        # 设置
-        scheduler.next_run = next_run
-        self.config.save()
-
-
+    def ui_reward_appear_click(self, screenshot=False) -> bool:
+        """
+        如果出现 ‘获得奖励’ 就点击
+        :return:
+        """
+        if screenshot:
+            self.screenshot()
+        return self.appear_then_click(self.I_UI_REWARD, action=self.C_UI_REWARD, interval=1)