Răsfoiți Sursa

feat(flutter): Save "state" and "schedule" but no test

huangrunheng 3 ani în urmă
părinte
comite
b021712d0a

+ 23 - 0
module/config/config.py

@@ -224,6 +224,29 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
             logger.critical("Please enable at least one task")
             logger.critical("Please enable at least one task")
             raise RequestHumanTakeover
             raise RequestHumanTakeover
 
 
+    def get_schedule_data(self) -> dict[str, dict]:
+        """
+        获取调度器的数据, 但是你必须使用update_scheduler来更新信息
+        :return:
+        """
+        running = {}
+        if self.task is not None and self.task.next_run < datetime.now():
+            running = {"name": self.task.command, "next_run": str(self.task.next_run)}
+
+        pending = []
+        for p in self.pending_task[1:]:
+            item = {"name": p.command, "next_run": str(p.next_run)}
+            pending.append(item)
+
+        waiting = []
+        for w in self.waiting_task:
+            item = {"name": w.command, "next_run": str(w.next_run)}
+            waiting.append(item)
+
+        data = {"running": running, "pending": pending, "waiting": waiting}
+        return data
+
+
     def task_call(self, task: str=None, force_call=True):
     def task_call(self, task: str=None, force_call=True):
         """
         """
         回调任务,这会是在任务结束后调用
         回调任务,这会是在任务结束后调用

+ 21 - 2
module/server/main_manager.py

@@ -2,7 +2,8 @@
 # @author runhey
 # @author runhey
 # 主进程的管理
 # 主进程的管理
 # github https://github.com/runhey
 # github https://github.com/runhey
-from multiprocessing.managers import SyncManager
+from multiprocessing import Queue, Pipe
+from threading import Thread
 
 
 from module.logger import logger
 from module.logger import logger
 from module.config.config import Config
 from module.config.config import Config
@@ -12,15 +13,21 @@ from module.server.config_manager import ConfigManager
 class MainManager(ConfigManager):
 class MainManager(ConfigManager):
     config_cache :Config = None  # 缓存当前切换的配置
     config_cache :Config = None  # 缓存当前切换的配置
     script_process :dict[str: ScriptProcess] = None  # 脚本进程
     script_process :dict[str: ScriptProcess] = None  # 脚本进程
+    push_data_thread: Thread = None  # 数据推送线程
 
 
     def __init__(self) -> None:
     def __init__(self) -> None:
         super().__init__()
         super().__init__()
+        self._all_script_files = self.all_script_files()
+        for script_name in self._all_script_files:
+            self.script_process[script_name] = ScriptProcess(script_name)
+        self.push_data_thread = Thread(target=self.push_data)
+
 
 
 
 
 
 
     def ensure_config_cache(self, config_name):
     def ensure_config_cache(self, config_name):
         if self.config_cache is None:
         if self.config_cache is None:
-            if config_name not in self.all_script_files():
+            if config_name not in self._all_script_files:
                 logger.warning(f'[{config_name}] script file does not exist')
                 logger.warning(f'[{config_name}] script file does not exist')
                 return None
                 return None
             self.config_cache = Config(config_name)
             self.config_cache = Config(config_name)
@@ -28,6 +35,18 @@ class MainManager(ConfigManager):
             self.config_cache = Config(config_name)
             self.config_cache = Config(config_name)
         return self.config_cache
         return self.config_cache
 
 
+    def add_script_file(self, file_name: str):
+        # 当你添加了新的脚本文件后,需要添加缓存的列表
+        if file_name in self._all_script_files:
+            logger.warning(f'[{file_name}] script file already exists')
+            return
+        self._all_script_files = self.all_script_files()
+        self.script_process[file_name] = ScriptProcess(file_name)
+
+
+    def push_data_handle(self):
+
+        pass
 
 
 
 
 
 

+ 24 - 5
module/server/script_process.py

@@ -8,24 +8,27 @@ from enum import Enum
 
 
 from module.logger import logger
 from module.logger import logger
 
 
+from module.server.script_websocket import ScriptWSManager
+
 class ScriptState(int, Enum):
 class ScriptState(int, Enum):
     INACTIVE = 1
     INACTIVE = 1
     RUNNING = 2
     RUNNING = 2
     WARNING = 3
     WARNING = 3
     UPDATING = 4
     UPDATING = 4
 
 
-class ScriptProcess:
+class ScriptProcess(ScriptWSManager):
 
 
     def __init__(self, config_name: str) -> None:
     def __init__(self, config_name: str) -> None:
+        super().__init__()
         self.config_name = config_name  # config_name
         self.config_name = config_name  # config_name
         self.log_pipe_out, self.log_pipe_in = multiprocessing.Pipe(False)
         self.log_pipe_out, self.log_pipe_in = multiprocessing.Pipe(False)
         self.state_queue = multiprocessing.Queue()
         self.state_queue = multiprocessing.Queue()
-        # self.state: ScriptState = ScriptState.INACTIVE
+        self.state: ScriptState = ScriptState.INACTIVE
         self._process = multiprocessing.Process(target=self.func,
         self._process = multiprocessing.Process(target=self.func,
                                                 args=(self.state_queue, self.log_pipe_in,),
                                                 args=(self.state_queue, self.log_pipe_in,),
                                                 name=self.config_name,
                                                 name=self.config_name,
                                                 daemon=True)
                                                 daemon=True)
-        # threading.Condition  可以多用户通知
+
 
 
 
 
 
 
@@ -37,6 +40,7 @@ class ScriptProcess:
             logger.warning(f'Script {self.config_name} is already running and first stop it')
             logger.warning(f'Script {self.config_name} is already running and first stop it')
             self.stop()
             self.stop()
         self._process.start()
         self._process.start()
+        self.state = ScriptState.RUNNING
 
 
     def stop(self):
     def stop(self):
         if self._process is None:
         if self._process is None:
@@ -46,6 +50,7 @@ class ScriptProcess:
             logger.warning(f'Script {self.config_name} is not running')
             logger.warning(f'Script {self.config_name} is not running')
             return
             return
         self._process.terminate()
         self._process.terminate()
+        self.state = ScriptState.INACTIVE
 
 
 
 
 
 
@@ -54,15 +59,19 @@ class ScriptProcess:
         self.start_log(log_pipe_in)
         self.start_log(log_pipe_in)
         try:
         try:
             from script import Script
             from script import Script
-            # script = Script(config_name=self.config_name)
+            script = Script(config_name=self.config_name)
+            script.state_queue = state_queue
             # script.loop()
             # script.loop()
             # 脚本启动
             # 脚本启动
             from time import sleep
             from time import sleep
             logger.info(f'Script {self.config_name} start')
             logger.info(f'Script {self.config_name} start')
             sleep(5)
             sleep(5)
             logger.info(f'Script {self.config_name} end')
             logger.info(f'Script {self.config_name} end')
+            exit(0)
             raise Exception('test')
             raise Exception('test')
-
+        except SystemExit as e:
+            logger.info(f'Script {self.config_name} exit')
+            self.state = ScriptState.WARNING
         except Exception as e:
         except Exception as e:
             logger.exception(f'Run script {self.config_name} error')
             logger.exception(f'Run script {self.config_name} error')
             logger.error(f'Error: {e}')
             logger.error(f'Error: {e}')
@@ -79,6 +88,16 @@ class ScriptProcess:
             raise
             raise
 
 
 
 
+    async def broadcast_state_log(self):
+        try:
+            state = self.state_queue.get_nowait()
+            if not state:
+                pass
+            await self.broadcast_state(state)
+        except Exception as e:
+            pass
+
+
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
     p = ScriptProcess('oas1')
     p = ScriptProcess('oas1')

+ 34 - 0
module/server/script_router.py

@@ -4,6 +4,7 @@
 import asyncio
 import asyncio
 from fastapi import APIRouter, HTTPException
 from fastapi import APIRouter, HTTPException
 from fastapi.responses import StreamingResponse
 from fastapi.responses import StreamingResponse
+from fastapi import WebSocket, WebSocketDisconnect
 from datetime import datetime
 from datetime import datetime
 from module.config.config import Config
 from module.config.config import Config
 
 
@@ -128,3 +129,36 @@ async def script_task_log(script_name: str):
     response.headers["Cache-Control"] = "no-cache"
     response.headers["Cache-Control"] = "no-cache"
     return response
     return response
 
 
+# -------------------------------------- websocket --------------------------------------
+
+@script_app.websocket("/ws/{script_name}")
+async def websocket_endpoint(websocket: WebSocket, script_name: str):
+    if script_name not in mm.script_process:
+        mm.script_process[script_name] = ScriptProcess(script_name)
+    script_process = mm.script_process[script_name]
+    await script_process.connect(websocket)
+    await script_process.broadcast_state({"state": script_process.state})
+    await script_process.broadcast_state({"schedule": mm.config_cache.get_schedule_data()})
+
+    try:
+        while True:
+            # 初次进入,广播state schedule
+            data = await websocket.receive_text()
+            if data == 'get_sate':
+                await script_process.broadcast_state({"state":script_process.state})
+            elif data == 'get_schedule':
+                mm.ensure_config_cache(script_name)
+                await script_process.broadcast_state({"schedule":mm.config_cache.get_schedule_data()})
+            elif data == 'start':
+                script_process.start()
+            elif data == 'stop':
+                script_process.stop()
+
+    except WebSocketDisconnect:
+        script_process.disconnect(websocket)
+
+
+
+
+
+

+ 38 - 0
module/server/script_websocket.py

@@ -0,0 +1,38 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+
+class ScriptWSManager:
+
+    def __init__(self):
+        self.active_connections: list[WebSocket] = []
+
+    async def connect(self, ws: WebSocket):
+        # 等待连接
+        await ws.accept()
+        self.active_connections.append(ws)
+
+    def disconnect(self, ws: WebSocket):
+        # 关闭时 移除ws对象
+        self.active_connections.remove(ws)
+
+    async def broadcast(self, message: str):
+        # 广播消息
+        for connection in self.active_connections:
+            await connection.send_text(message)
+
+    async def broadcast_state(self, data: dict):
+        # 广播自身的状态
+        for connection in self.active_connections:
+            await connection.send_json(data)
+
+    async def broadcast_log(self, log: str):
+        # 广播日志
+        for connection in self.active_connections:
+            await connection.send_text(log)
+
+
+
+
+

+ 5 - 10
script.py

@@ -1,6 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
+
 import zerorpc
 import zerorpc
 import zmq
 import zmq
 import msgpack
 import msgpack
@@ -18,8 +19,8 @@ from datetime import datetime, timedelta
 from pathlib import Path
 from pathlib import Path
 from cached_property import cached_property
 from cached_property import cached_property
 from pydantic import BaseModel, ValidationError
 from pydantic import BaseModel, ValidationError
-from PySide6.QtGui import QImage
 from threading import Thread
 from threading import Thread
+from multiprocessing.queues import Queue
 
 
 
 
 from module.config.utils import convert_to_underscore
 from module.config.utils import convert_to_underscore
@@ -35,6 +36,7 @@ class Script:
     def __init__(self, config_name: str ='oas') -> None:
     def __init__(self, config_name: str ='oas') -> None:
         logger.hr('Start', level=0)
         logger.hr('Start', level=0)
         self.server = None
         self.server = None
+        self.state_queue: Queue = None
         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
@@ -238,7 +240,6 @@ class Script:
         if self.gui_update_task is not None:
         if self.gui_update_task is not None:
             self.gui_update_task(data)
             self.gui_update_task(data)
 
 
-
     def gui_task_list(self) -> str:
     def gui_task_list(self) -> str:
         """
         """
         获取给gui显示的任务列表
         获取给gui显示的任务列表
@@ -263,13 +264,6 @@ class Script:
 
 
 
 
 
 
-
-
-
-
-
-
-
     def wait_until(self, future):
     def wait_until(self, future):
         """
         """
         Wait until a specific time.
         Wait until a specific time.
@@ -304,7 +298,8 @@ class Script:
         while 1:
         while 1:
             task = self.config.get_next()
             task = self.config.get_next()
             self.config.task = task
             self.config.task = task
-            self._gui_update_tasks()
+            if self.state_queue:
+                self.state_queue.put({"schedule": self.config.get_schedule_data()})
 
 
             # from module.base.resource import release_resources
             # from module.base.resource import release_resources
             # if self.config.task.command != 'Alas':
             # if self.config.task.command != 'Alas':