Răsfoiți Sursa

feat(team flow): save

runhey 3 ani în urmă
părinte
comite
9c0c9a3a09

+ 1 - 0
module/config/config.py

@@ -317,6 +317,7 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
 
         # 设置
         logger.attr(f'{task}.scheduler.next_run', next_run)
+        # 保证线程安全的
         scheduler.next_run = next_run
         self.save()
 

+ 52 - 14
module/team_flow/host.py

@@ -1,6 +1,8 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+import json
+from time import sleep
 from datetime import datetime, time
 from cached_property import cached_property
 
@@ -13,7 +15,17 @@ from module.team_flow.task import Task
 from module.logger import logger
 
 def on_message(client, userdata, msg):
-    userdata.match_topic[msg.topic](msg.payload)
+    try:
+        data = json.loads(msg.payload)
+    except json.JSONDecodeError:
+        logger.error(f'Get [{msg.topic}]: {msg.payload}')
+        return
+    logger.info(f'Get {msg.topic}: {data}')
+    for username, data in data.items():
+        # 反正只有一项
+        if username == userdata.username:
+            continue
+        userdata.match_topic[msg.topic](username, data)
 
 class Host(Mqtt, Player):
 
@@ -33,16 +45,22 @@ class Host(Mqtt, Player):
             'Strategy': self.on_strategy
         }
 
-    def on_first_notice(self, payload):
-        pass
+    def on_first_notice(self, player: str, data: dict):
+        # 其他人上线,就广播自己的策略出去
+        if 'type' in data:
+            logger.info(f'Player {player} is online')
+        else:
+            # 如果是其他人像
+            pass
+
 
-    def on_last_will(self, payload):
+    def on_last_will(self, player: str, data: dict):
         pass
 
-    def on_task_start(self, payload):
+    def on_task_start(self, player: str, data: dict):
         pass
 
-    def on_strategy(self, payload):
+    def on_strategy(self, player: str, data: dict):
         pass
 
     def update_multi_tasks(self):
@@ -51,7 +69,13 @@ class Host(Mqtt, Player):
         也就是从  config -> multi_tasks
         :return:
         """
-        for key, value in self.config.model.items():
+        tasks = {'orochi': self.config.model.orochi,
+                 'fallen_sun': self.config.model.fallen_sun,
+                 'eternity_sea': self.config.model.eternity_sea,
+                 'evo_zone': self.config.model.evo_zone,
+                 'exploration': self.config.model.exploration
+                 }
+        for key, value in tasks.items():
             task_name: str = key
             limit_time: time = None
             limit_count: int = None
@@ -76,7 +100,7 @@ class Host(Mqtt, Player):
                 # TODO 等待探索完成
                 limit_time = time(minute=30)
                 limit_count = 50
-                role = str(value.evo_zone_config.user_status)
+                role = 'leader'
                 continue
             else:
                 continue
@@ -84,10 +108,10 @@ class Host(Mqtt, Player):
                 continue
             if task_name not in self.multi_tasks:
                 # 第一次
-                logger.info(f'First time to add {task_name} to multi_tasks')
+                logger.info(f'First time to add [{task_name}] to multi_tasks')
                 self.multi_tasks[task_name] = Task(
                     next_run=value.scheduler.next_run,
-                    target_run=value.scheduler.target_run,
+                    target_run=value.scheduler.next_run,
                     limit_time=limit_time,
                     team_task=True,
                     role=role,
@@ -96,14 +120,28 @@ class Host(Mqtt, Player):
             else:
                 # 更新
                 logger.info(f'Update {task_name} to multi_tasks')
-                self.multi_tasks[task_name].next_run = value.scheduler.next_run
-                self.multi_tasks[task_name].limit_time = limit_time
-                self.multi_tasks[task_name].role = role
-                self.multi_tasks[task_name].limit_count = limit_count
+                self.multi_tasks[task_name].update_info(next_run=value.scheduler.next_run,
+                                                        limit_time=limit_time,
+                                                        role=role,
+                                                        limit_count=limit_count)
 
+    def update_strategy(self):
+        """
+        更新策略
+        :return:
+        """
+        pass
 
 
 
 
 if __name__ == '__main__':
     host = Host(Config('oas1'))
+    sleep(20)
+    # 更新config -> multi_tasks -> publish_data
+    host.update_multi_tasks()
+    host.q_publish.put(['Strategy' ,host.publish_data()])
+    host.q_publish.put(['Strategy' ,host.publish_data()])
+    host.q_publish.put(['Strategy' ,host.publish_data()])
+    sleep(46)
+

+ 52 - 6
module/team_flow/mqtt.py

@@ -2,18 +2,22 @@
 # @author runhey
 # github https://github.com/runhey
 from time import sleep
+
+import json
 from random import randint
 from paho.mqtt import client as mqtt_client
+from threading import Thread
+from queue import Queue
 
 from tasks.GlobalGame.config import TeamFlow, Transport
 
 from module.logger import logger
+from module.base.timer import Timer
 
 
 def on_message(client, userdata, msg):
     if msg.topic == 'FirstNotice':
         return
-
     logger.info(f"Received `{msg.payload}` from `{userdata}` ")
 # ----------------------------------------------------------------------------------------------------------------------
 # 使用MQTT是为了做广播,自己手撸的话太麻烦了
@@ -22,13 +26,31 @@ def on_message(client, userdata, msg):
 # 2. 当一个玩家退出网络后,会向服务器发送LastNotice,这个时候所有的玩家都要更新自己的策略
 # ----------------------------------------------------------------------------------------------------------------------
 class Mqtt:
+    # 队列的结构必须是一个tuple,第一个元素是topic,第二个元素是msg
+    q_publish: Queue = None
 
     def __init__(self, team_flow: TeamFlow):
         def on_connect(client, userdata, flags, rc):
             if rc == 0:
                 logger.info("Connected to MQTT Broker!")
+            elif rc == 1:
+                # 协议版本错误
+                logger.error(f"Connection refused - incorrect protocol version. return code: {rc}")
+            elif rc == 2:
+                # 无效的客户端标识
+                logger.error(f"Connection refused - invalid client identifier. return code: {rc}")
+            elif rc == 3:
+                # 服务器不可用
+                logger.error(f"Connection refused - server unavailable. return code: {rc}")
+            elif rc == 4:
+                # 错误的用户名或密码
+                logger.error(f"Connection refused - bad username or password. return code: {rc}")
+            elif rc == 5:
+                # 未授权
+                logger.error(f"Connection refused - not authorised. return code: {rc}")
             else:
                 logger.info("Failed to connect, return code %d\n", rc)
+        self.q_publish = Queue()
         self.broker = team_flow.broker
         self.port = team_flow.port
         self.protocol = team_flow.transport
@@ -43,16 +65,20 @@ class Mqtt:
         self.client.username_pw_set(self.username, self.password)
         self.client.on_connect = on_connect
         self.client.on_message = on_message
-        self.client.will_set(topic='LastWill', payload=self.username, qos=2)
+        self.client.will_set(topic='LastWill', payload=json.dumps({self.username: ""}), qos=2)
         self.client.connect(self.broker, self.port)
         # 订阅主题: FirstNotice LastWill TaskStart Strategy
         self.client.subscribe(topic='FirstNotice', qos=2)
         self.client.subscribe(topic='LastWill', qos=2)
         self.client.subscribe(topic='TaskStart', qos=0)
         self.client.subscribe(topic='Strategy', qos=0)
-        self.client.loop_start()
         # publish FirstNotice
-        self.publish('FirstNotice', {'player': self.username})
+        self.publish("FirstNotice", {"type": "join"})
+        # 开启一个线程来处理消息
+        self.mqtt_timer = Timer(60)
+        self.mqtt_timer.start()
+        self.mqtt_thread = Thread(target=self.mqtt_loop, name='mqtt_loop', daemon=True)
+        self.mqtt_thread.start()
 
 
 
@@ -69,11 +95,12 @@ class Mqtt:
         if not isinstance(msg, dict):
             logger.warning(f"Msg must be a dict, but got {type(msg)}")
             return False
-        result = self.client.publish(topic, str(msg))
+        msg = {self.username: msg}
+        result = self.client.publish(topic, json.dumps(msg))
         # result: [0, 1]
         status = result[0]
         if status == 0:
-            logger.info(f"Send `{msg}` to topic `{topic}`")
+            logger.info(f"Send `msg` to topic `{topic}`")
             return True
         else:
             logger.info(f"Failed to send message to topic {topic} {status}")
@@ -85,6 +112,25 @@ class Mqtt:
     def Strategy(self, msg):
         self.publish('Strategy', msg)
 
+    def mqtt_loop(self):
+        while True:
+            # sleep(5)
+            # 官方超级不推荐这种方式来处理消息。 但是不打算开一个线程来处理这个mqtt_timer
+            try:
+                self.client.loop(timeout=5)
+            except Exception as e:
+                logger.error(e)
+
+            if not self.mqtt_timer.reached():
+                continue
+            self.mqtt_timer.reset()
+            while not self.q_publish.empty():
+                try:
+                    topic, msg = self.q_publish.get(block=False)
+                except Exception as e:
+                    continue
+                self.publish(topic, msg)
+
 
 
 

+ 4 - 4
module/team_flow/player.py

@@ -25,9 +25,9 @@ class Player:
             item = {}
             if not task.team_task:
                 continue
-            item['next_run'] = task.next_run
-            item['role'] = task.role
-            item['limit_time'] = task.limit_time
-            item['limit_count'] = task.limit_count
+            item['next_run'] = str(task.next_run)
+            item['role'] = str(task.role)
+            item['limit_time'] = str(task.limit_time)
+            item['limit_count'] = int(task.limit_count)
             result[name] = item
         return result

+ 31 - 1
module/team_flow/task.py

@@ -25,7 +25,37 @@ class Task:
         self.role = role
         self.limit_count = limit_count
 
-
+    def update_info(self,
+                    next_run: datetime,
+                    limit_time: time,
+                    limit_count: int,
+                    role: str):
+        # next_run
+        if isinstance(next_run, datetime):
+            self.next_run = next_run
+        elif isinstance(next_run, str):
+            self.next_run = datetime.fromisoformat(next_run)
+        else:
+            raise TypeError(f'next_run must be datetime or str, not {type(next_run)}')
+        # limit_count
+        if isinstance(limit_count, int):
+            self.limit_count = limit_count
+        elif isinstance(limit_count, str):
+            self.limit_count = int(limit_count)
+        else:
+            raise TypeError(f'limit_count must be int or str, not {type(limit_count)}')
+        # limit_time
+        if isinstance(limit_time, time):
+            self.limit_time = limit_time
+        elif isinstance(limit_time, str):
+            self.limit_time = time.fromisoformat(limit_time)
+        else:
+            raise TypeError(f'limit_time must be time or str, not {type(limit_time)}')
+        # role
+        if isinstance(role, str):
+            self.role = role
+        else:
+            raise TypeError(f'role must be str, not {type(role)}')