Bladeren bron

feat(gui): 6.14 update

runhey 3 jaren geleden
bovenliggende
commit
4ca2c81c06

+ 1 - 2
module/config/config.py

@@ -20,8 +20,7 @@ from module.config.utils import *
 from module.exception import RequestHumanTakeover, ScriptError
 from module.logger import logger
 
-class TaskEnd(Exception):
-    pass
+
 
 class Function:
     def __init__(self, key: str, data: dict):

+ 3 - 3
module/config/config_state.py

@@ -9,6 +9,6 @@ class ConfigState:
     """
     def __init__(self, config_name: str) -> None:
         self.config_name = config_name
-        self.pending_task = []
-        self.waiting_task = []
-        self.task = None
+        self.pending_task: list["Function"] = []
+        self.waiting_task: list["Function"] = []
+        self.task: str = None  # 任务名大驼峰

+ 3 - 0
module/exception.py

@@ -57,3 +57,6 @@ class RequestHumanTakeover(Exception):
     # Request human takeover
     # Alas is unable to handle such error, probably because of wrong settings.
     pass
+
+class TaskEnd(Exception):
+    pass

+ 44 - 7
module/gui/context/process_manager.py

@@ -4,10 +4,12 @@
 import socket
 import random
 import zerorpc
+import asyncio
 import cv2
 import msgpack
 import numpy as np
 import io
+import json
 
 from typing import Union, Any, Dict
 from cached_property import cached_property
@@ -50,6 +52,9 @@ class ProcessManager(QObject):
     进程管理
     """
     log_signal = Signal(str, str)  # 日志信号
+    sig_update_task = Signal(str, str)  # 更新当前运行的任务任务信号
+    sig_update_pending = Signal(str, str)  # 更新等待运行的任务信号
+    sig_update_waiting = Signal(str, str)  # 更新等待运行的任务信号
 
     def __init__(self) -> None:
         """
@@ -69,6 +74,8 @@ class ProcessManager(QObject):
         self.update_thread: Thread = None  # 更新线程
         self.start_update_tasks()  # 启动更新线程
 
+        self.event_loop = asyncio.get_event_loop()  # 事件循环
+
     @Slot()
     def create_all(self) -> None:
         """
@@ -136,10 +143,9 @@ class ProcessManager(QObject):
         :return:
         """
         if config in self.processes:
-            if not self.processes[config].is_alive():
-                self.processes[config].start()
+            if not self.processes[config].is_alive():  # 如果进程已经死亡,那么就重新启动
                 logger.info(f'restart script {config}')
-                return None
+
 
             self.processes[config].terminate()  # 强制结束进程
             if self.ports[config] is None:
@@ -355,9 +361,8 @@ class ProcessManager(QObject):
             logger.info(f'Script {config_name} is not running')
             return
 
-        console = Console()
         # while self.processes[config_name].is_alive():
-        while True:
+        while self.log_thread[config_name].is_alive():
             try:
                 log = q.get(timeout=1)
                 if log is None:
@@ -370,7 +375,6 @@ class ProcessManager(QObject):
                 logger.error(f'Log thread of {config_name} error: {e}')
                 break
 
-
     def start_update_tasks(self) -> None:
         """
         启动更新任务的线程
@@ -383,7 +387,6 @@ class ProcessManager(QObject):
         self.update_thread = Thread(target=self.update_thread_func, daemon=True)
         self.update_thread.start()
 
-
     def update_thread_func(self) -> None:
         """
         更新 任务的 线程函数
@@ -396,7 +399,16 @@ class ProcessManager(QObject):
                 update = self.update_queue.get(timeout=1)
                 if update is None:
                     continue
+                if not isinstance(update, dict):
+                    continue
+
                 logger.info(f'Update thread get')
+                print(update)
+                for key, value in update.items():
+                    if "task" and "pending" and "waiting" in value:
+                        self.sig_update_task.emit(key, json.dumps(value["task"]))
+                        self.sig_update_pending.emit(key, json.dumps(value["pending"]))
+                        self.sig_update_waiting.emit(key, json.dumps(value["waiting"]))
 
             except Empty:
                 continue
@@ -404,6 +416,31 @@ class ProcessManager(QObject):
                 logger.error(f'Update thread error: {e}')
                 break
 
+    @Slot(str)
+    def start_script(self, config: str) -> None:
+        """
+        启动脚本的loop
+        :param config:
+        :return:
+        """
+        if not self.processes[config].is_alive():
+            logger.info(f'Start script {config}')
+            return self.restart(config)
+
+        logger.info(f'Script {config} is already running')
 
+        self.clients[config].start_loop()
 
+    @Slot(str)
+    def stop_script(self, config: str) -> None:
+        """
+        停止脚本的loop
+        :param config:
+        :return:
+        """
+        if config in self.processes:
+            logger.info(f'Stop script {config}')
+            self.processes[config].stop()
+        else:
+            logger.info(f'Script {config} is not running')
 

+ 1 - 1
module/gui/process/script_process.py

@@ -89,5 +89,5 @@ class ScriptProcess(Process):
         """
         msg = {self.config: data}
         self.update_queue.put(msg)
-        logger.info(f'update tasks {self.config}')
+        logger.info(f'Update tasks {self.config}')
 

+ 21 - 14
module/gui/qml/Component/OverStatus.qml

@@ -8,6 +8,10 @@ Item{
 
 //    width: 200
     height: 40
+
+    id: root
+    property int runStatus: MainEvent.RunStatus.Init
+
     RowLayout{
         anchors.fill: parent
         spacing: 0
@@ -21,24 +25,27 @@ Item{
             id: runStatusIcon
             Layout.alignment: Qt.AlignVCenter
             Layout.leftMargin: 20
-            runStatus: MainEvent.runStatus
+            runStatus: root.runStatus
         }
         FluText{
             id:runStatusText
-            property int runStatus: MainEvent.runStatus
             Layout.alignment: Qt.AlignVCenter
-            text: ""
-            onRunStatusChanged: {
-                if(runStatus === MainEvent.RunStatus.Empty){
-                    text= ""
-                }else if(runStatus === MainEvent.RunStatus.Free){
-                    text= "闲置"
-                }else if(runStatus === MainEvent.RunStatus.Run){
-                    text= "运行中"
-                }else if(runStatus === MainEvent.RunStatus.Error){
-                    text= "发生错误"
-                }
-            }
+            text: "初始化"
+
+        }
+    }
+
+    onRunStatusChanged: {
+        if(root.runStatus === MainEvent.RunStatus.Empty){
+            runStatusText.text= ""
+        }else if(root.runStatus === MainEvent.RunStatus.Free){
+            runStatusText.text= "闲置"
+        }else if(root.runStatus === MainEvent.RunStatus.Run){
+            runStatusText.text= "运行中"
+        }else if(root.runStatus === MainEvent.RunStatus.Error){
+            runStatusText.text= "发生错误"
+        }else if(root.runStatus === MainEvent.RunStatus.Init){
+            runStatusText.text= "初始化"
         }
     }
 }

+ 41 - 1
module/gui/qml/Component/Overview.qml

@@ -49,9 +49,11 @@ Item {
                         if(selected){
                             text = "Start"
                             textLog.text = ""
+                            process_manager.stop_script(root.configName)
                         }else{
+                            // 如果按键颜色变灰色
                             text = "Stop"
-
+                            process_manager.start_script(root.configName)
                         }
                     }
                 }
@@ -80,6 +82,7 @@ Item {
                     radius: 2
                 }
                 Taskmini{
+                    id: task_running
                     Layout.leftMargin: 16
                 }
             }
@@ -169,6 +172,9 @@ Item {
                 font: FluTextStyle.Subtitle
                 Layout.alignment: Qt.AlignVCenter | Qt.AlignLeft
             }
+            OverStatus{
+                Layout.alignment: Qt.AlignVCenter | Qt.AlignRight
+            }
             FluToggleButton{
                 Layout.alignment: Qt.AlignVCenter | Qt.AlignRight
                 Layout.rightMargin: 16
@@ -218,4 +224,38 @@ Item {
         }}
     }
 
+    Component.onCompleted:{
+        process_manager.sig_update_task.connect(update_task)
+        process_manager.sig_update_pending.connect(update_pending)
+        process_manager.sig_update_waiting.connect(update_waiting)
+    }
+    function update_task(config, data){
+        if(typeof data !== "string"){
+            console.error("Pass an incorrect type")
+            return
+        }
+
+        if(config !== configName){
+            return
+        }
+        task_running.setData(data)
+    }
+    function update_pending(config, data){
+        if(typeof data !== "string"){
+            console.error("Pass an incorrect type")
+            return
+        }
+        if(config !== configName){
+            return
+        }
+    }
+    function update_waiting(config, data){
+        if(typeof data !== "string"){
+            console.error("Pass an incorrect type")
+            return
+        }
+        if(config !== configName){
+            return
+        }
+    }
 }

+ 4 - 0
module/gui/qml/Component/RunStatusIcon.qml

@@ -60,6 +60,10 @@ Item {
             runError.visible = true
             runProgress.visible = false
             runProgress.progress = 0
+        }else if(runStatus === MainEvent.RunStatus.Init){
+            runError.visible = false
+            runProgress.visible = true
+            runProgress.progress = 0.25
         }
     }
 

+ 17 - 0
module/gui/qml/Component/Taskmini.qml

@@ -5,8 +5,14 @@ import FluentUI
 // 任务的名称 + 时间 以及一个设置的入口
 
 Item {
+    id: root
     width: 225
     height: 40
+    visible: true
+
+    property alias name: taskName.text
+    property alias nextRun: taskTime.text
+
     FluText{
         id: taskName
         anchors{
@@ -41,4 +47,15 @@ Item {
              showSuccess("setting")
         }
     }
+    // 使用这个的前提是 data 是字符串
+    function  setData(data){
+        if(data === "{}"){  // 这个表示没有数据,是空的
+            root.visible = false
+            return
+        }
+        root.visible = true
+        const d = JSON.parse(data)
+        task_running.name = d["name"]
+        task_running.nextRun = d["next_run"]
+    }
 }

+ 2 - 1
module/gui/qml/Global/MainEvent.qml

@@ -11,7 +11,8 @@ QtObject {
         Error,
         Run,
         Free, //空闲
-        Empty //不显示
+        Empty, //不显示
+        Init  //初始化
     }
 
     // 界面的自定义设置

+ 6 - 6
module/gui/qml/MainWindow.qml

@@ -23,12 +23,12 @@ FluWindow {
        z:9
        width: parent.width
     }
-    OverStatus{
-        anchors{
-            top: parent.top
-            horizontalCenter: parent.horizontalCenter
-        }
-    }
+//    OverStatus{
+//        anchors{
+//            top: parent.top
+//            horizontalCenter: parent.horizontalCenter
+//        }
+//    }
 
 
 // 任务栏的右边边系统图标

+ 4 - 1
module/logger.py

@@ -47,6 +47,9 @@ class LogStream(TextIOBase):
             msg = msg.decode("utf-8")
         self._func(msg)
         return len(msg)
+    
+class RichStreamHandler(RichHandler):
+    pass
 
 
 class RichRenderableHandler(RichHandler):
@@ -279,7 +282,7 @@ def set_func_logger(func):
         highlight=False,
         width=160,
     )
-    hdlr = RichFileHandler(
+    hdlr = RichStreamHandler(
         console=file_console,
         show_path=False,
         show_time=False,

+ 50 - 4
script.py

@@ -10,6 +10,7 @@ import cv2
 import time
 import os
 import inflection
+import asyncio
 
 from typing import Callable
 from datetime import datetime, timedelta
@@ -17,10 +18,11 @@ from pathlib import Path
 from cached_property import cached_property
 from pydantic import BaseModel, ValidationError
 from PySide6.QtGui import QImage
+from threading import Thread
 
 
 from module.config.utils import convert_to_underscore
-from module.config.config import Config, TaskEnd
+from module.config.config import Config
 from module.device.device import Device
 from module.base.utils import load_module
 from module.base.decorator import del_cached_property
@@ -38,6 +40,8 @@ class Script:
         # Failure count of tasks
         # Key: str, task name, value: int, failure count
         self.failure_record = {}
+        # 运行loop的线程
+        self.loop_thread: Thread = None
 
     @cached_property
     def config(self) -> "Config":
@@ -123,8 +127,6 @@ class Script:
         启动zerorpc服务
         :return:
         """
-        if self.gui_update_task:
-            self.gui_update_task("yyyy")
         self.server.run()
 
     def gui_args(self, task: str) -> str:
@@ -187,6 +189,38 @@ class Script:
         ret, buffer = cv2.imencode('.jpg', img)
         yield buffer.tobytes()
 
+    def _gui_update_tasks(self) -> None:
+        """
+        获取更新任务后 pending waiting 的任务 和 当前的任务的数据。打包给gui显示
+        :return:
+        """
+        data = {}
+        pending = []
+        waiting = []
+        task = {}
+        if self.config.task is not None and self.config.task.next_run < datetime.now():
+            task["name"] = self.config.task.command
+            task["next_run"] = str(self.config.task.next_run)
+        data["task"] = task
+
+        for p in self.config.pending_task:
+            item = {"name": p.command, "next_run": str(p.next_run)}
+            pending.append(item)
+
+        for w in self.config.waiting_task:
+            item = {"name": w.command, "next_run": str(w.next_run)}
+            waiting.append(item)
+
+
+        data["pending"] = pending
+        data["waiting"] = waiting
+
+        if self.gui_update_task is not None:
+            self.gui_update_task(data)
+
+
+
+
     def wait_until(self, future):
         """
         Wait until a specific time.
@@ -221,6 +255,7 @@ class Script:
         while 1:
             task = self.config.get_next()
             self.config.task = task
+            self._gui_update_tasks()
 
             # from module.base.resource import release_resources
             # if self.config.task.command != 'Alas':
@@ -344,6 +379,7 @@ class Script:
 
             # Get task
             task = self.get_next_task()
+            # 更新 gui的任务
             # Init device and change server
             _ = self.device
             # Skip first restart
@@ -358,7 +394,7 @@ class Script:
             self.device.stuck_record_clear()
             self.device.click_record_clear()
             logger.hr(task, level=0)
-            success = self.run(inflection.underscore(task))
+            success = self.run(inflection.camelize(task))
             logger.info(f'Scheduler: End task `{task}`')
             self.is_first_task = False
 
@@ -388,6 +424,16 @@ class Script:
             else:
                 break
 
+    def start_loop(self) -> None:
+        """
+        创建一个线程,运行loop
+        :return:
+        """
+        if self.loop_thread is None:
+            self.loop_thread = Thread(target=self.loop, name='Script_loop')
+            self.loop_thread.start()
+
+
 if __name__ == "__main__":
     script = Script("oas1")
     print(script.get_next_task())

+ 4 - 1
tasks/AreaBoss/script_task.py

@@ -7,6 +7,7 @@ from tasks.base_task import BaseTask
 from tasks.GeneralBattle.general_battle import GeneralBattle
 from tasks.AreaBoss.assets import AreaBossAssets
 from module.logger import logger
+from module.exception import TaskEnd
 
 
 class ScriptTask(GeneralBattle, AreaBossAssets):
@@ -165,7 +166,9 @@ class ScriptTask(GeneralBattle, AreaBossAssets):
 
         # 退出
         self.go_back()
-        return True
+
+        # 以抛出异常的形式结束
+        raise TaskEnd
 
     def go_back(self) -> None:
         """