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

fix(Config): Config files cannot be synchronized correctly in multiple processes

ryland 2 лет назад
Родитель
Сommit
3568a87ffb
3 измененных файлов с 28 добавлено и 31 удалено
  1. 17 13
      module/server/main_manager.py
  2. 10 17
      module/server/script_router.py
  3. 1 1
      tasks/Pets/assets.py

+ 17 - 13
module/server/main_manager.py

@@ -7,7 +7,6 @@ import sys
 import os
 import signal
 from asyncio.tasks import Task
-from multiprocessing import Queue, Pipe
 from threading import Thread
 
 from module.logger import logger
@@ -17,7 +16,7 @@ from module.server.config_manager import ConfigManager
 
 
 class MainManager(ConfigManager):
-    config_cache: Config = None  # 缓存当前切换的配置
+    # config_cache: Config = None  # 缓存当前切换的配置
     script_process: dict[str: ScriptProcess] = None  # 脚本进程
     push_data_thread: Thread = None  # 数据推送线程
     signal_kill_server: bool = False
@@ -31,17 +30,17 @@ class MainManager(ConfigManager):
         self.push_data_thread = Thread(target=self.start_push_data_thread, daemon=True)
         self.push_data_thread.start()
 
-    def ensure_config_cache(self, config_name: str, reload: bool = False):
-        if self.config_cache is None:
-            if config_name not in self._all_script_files:
-                logger.warning(f'[{config_name}] script file does not exist')
-                return None
-            self.config_cache = Config(config_name)
-        elif self.config_cache.config_name != config_name:
-            self.config_cache = Config(config_name)
-        if reload:
-            self.config_cache = Config(config_name)
-        return self.config_cache
+    # def ensure_config_cache(self, config_name: str, reload: bool = False):
+    #     if self.config_cache is None:
+    #         if config_name not in self._all_script_files:
+    #             logger.warning(f'[{config_name}] script file does not exist')
+    #             return None
+    #         self.config_cache = Config(config_name)
+    #     elif self.config_cache.config_name != config_name:
+    #         self.config_cache = Config(config_name)
+    #     if reload:
+    #         self.config_cache = Config(config_name)
+    #     return self.config_cache
 
     def add_script_file(self, file_name: str):
         # 当你添加了新的脚本文件后,需要添加缓存的列表
@@ -95,3 +94,8 @@ class MainManager(ConfigManager):
                 if coroutine_log_name not in tasks:
                     tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
                                                                     name=coroutine_log_name)
+
+    @staticmethod
+    def config_cache(name: str) -> Config:
+        return Config(name)
+

+ 10 - 17
module/server/script_router.py

@@ -24,9 +24,7 @@ async def script_test():
 
 @script_app.get('/script_menu')
 async def script_menu():
-    if mm.config_cache is None:
-        mm.config_cache = Config('template')
-    return mm.config_cache.gui_menu_list
+    return mm.config_cache('template').gui_menu_list
 # ----------------------------------   配置文件管理   ----------------------------------
 @script_app.get('/config_list')
 async def config_list():
@@ -64,14 +62,10 @@ async def script_stop(script_name: str):
 
 @script_app.get('/{script_name}/{task}/args')
 async def script_task(script_name: str, task: str):
-    if not mm.ensure_config_cache(script_name):
-        raise Exception(f'[{script_name}] script file does not exist')
-    return mm.config_cache.model.script_task(task)
+    return mm.config_cache(script_name).model.script_task(task)
 
 @script_app.put('/{script_name}/{task}/{group}/{argument}/value')
-async def script_task(script_name: str, task: str, group: str, argument: str, types: str ,value):
-    if not mm.ensure_config_cache(script_name):
-        raise HTTPException(status_code=404, detail=f'[{script_name}] script file does not exist')
+async def script_task(script_name: str, task: str, group: str, argument: str, types: str, value):
     try:
         match types:
             case 'integer':
@@ -101,8 +95,7 @@ async def script_task(script_name: str, task: str, group: str, argument: str, ty
     except Exception as e:
         # 类型不正确
         raise HTTPException(status_code=400, detail=f'Argument type error: {e}')
-    mm.config_cache.model.config_name = script_name
-    return mm.config_cache.model.script_set_arg(task, group, argument, value)
+    return mm.config_cache(script_name).model.script_set_arg(task, group, argument, value)
 
 # --------------------------------------  SSE  --------------------------------------
 @script_app.get('/{script_name}/state')
@@ -144,9 +137,9 @@ async def websocket_endpoint(websocket: WebSocket, script_name: str):
     script_process = mm.script_process[script_name]
     await script_process.connect(websocket)
     await script_process.broadcast_state({"state": script_process.state})
-    mm.ensure_config_cache(script_name, reload=True)
-    mm.config_cache.update_scheduler()
-    await script_process.broadcast_state({"schedule": mm.config_cache.get_schedule_data()})
+    config = mm.config_cache(script_name)
+    config.update_scheduler()
+    await script_process.broadcast_state({"schedule": config.get_schedule_data()})
 
     try:
         while True:
@@ -155,9 +148,9 @@ async def websocket_endpoint(websocket: WebSocket, script_name: str):
             if data == 'get_state':
                 await script_process.broadcast_state({"state": script_process.state})
             elif data == 'get_schedule':
-                mm.ensure_config_cache(script_name, reload=True)
-                mm.config_cache.update_scheduler()
-                await script_process.broadcast_state({"schedule":mm.config_cache.get_schedule_data()})
+                config = mm.config_cache(script_name)
+                config.update_scheduler()
+                await script_process.broadcast_state({"schedule": config.get_schedule_data()})
             elif data == 'start':
                 await script_process.start()
             elif data == 'stop':

+ 1 - 1
tasks/Pets/assets.py

@@ -12,7 +12,7 @@ class PetsAssets:
 
 	# Image Rule Assets
 	# 宠物小屋 
-	I_PET_HOUSE = RuleImage(roi_front=(1015,431,27,31), roi_back=(952,412,144,60), threshold=0.7, method="Template matching", file="./tasks/Pets/pet/pet_pet_house.png")
+	I_PET_HOUSE = RuleImage(roi_front=(1055,434,27,31), roi_back=(952,412,144,60), threshold=0.7, method="Template matching", file="./tasks/Pets/pet/pet_pet_house.png")
 	# 爪印 
 	I_PET_CLAW = RuleImage(roi_front=(1171,625,55,56), roi_back=(1171,625,55,56), threshold=0.8, method="Template matching", file="./tasks/Pets/pet/pet_pet_claw.png")
 	# 其乐融融