Kaynağa Gözat

feat(module): save team flow 8.15

runhey 3 yıl önce
ebeveyn
işleme
eb90152848

+ 2 - 0
.gitignore

@@ -8,6 +8,7 @@ config/*.yaml
 config/*.json
 config/tmp*
 !config/template*.json
+config/*.crt
 *.pyw
 dev_tools/debug_tools
 .idea
@@ -44,6 +45,7 @@ module/config/argument/setting.json
 
 
 
+
 # Created by .ignore support plugin (hsz.mobi)
 
 ### JetBrains template

+ 65 - 0
module/team_flow/host.py

@@ -0,0 +1,65 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+from cached_property import cached_property
+
+from tasks.GlobalGame.config import TeamFlow, Transport
+
+from module.team_flow.mqtt import Mqtt
+from module.config.config import Config
+from module.team_flow.player import Player
+from module.team_flow.task import Task
+
+def on_message(client, userdata, msg):
+    userdata.match_topic[msg.topic](msg.payload)
+
+class Host(Mqtt, Player):
+
+    def __init__(self, config: Config):
+        Player.__init__(self, config.global_game.team_flow.username)
+        Mqtt.__init__(self, config.global_game.team_flow)
+        self.config = config
+        self.players: list[Player] = []
+        self.set_on_message(on_message)
+
+    @cached_property
+    def match_topic(self):
+        return {
+            'FirstNotice': self.on_first_notice,
+            'LastWill': self.on_last_will,
+            'TaskStart': self.on_task_start,
+            'Strategy': self.on_strategy
+        }
+
+    def on_first_notice(self, payload):
+        pass
+
+    def on_last_will(self, payload):
+        pass
+
+    def on_task_start(self, payload):
+        pass
+
+    def on_strategy(self, payload):
+        pass
+
+    def update_multi_tasks(self):
+        """
+        作为主角, 更新自身的多人任务的缓存
+        也就是从  config -> multi_tasks
+        :return:
+        """
+        for key, value in self.config.model.items():
+            if key == 'orochi':
+                continue
+            elif key == 'fallen_sun':
+                continue
+            elif key == 'eternity_sea':
+                continue
+            elif key == 'evo_zone':
+                continue
+
+
+if __name__ == '__main__':
+    host = Host(Config('oas1'))

+ 103 - 0
module/team_flow/mqtt.py

@@ -0,0 +1,103 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from time import sleep
+from random import randint
+from paho.mqtt import client as mqtt_client
+
+from tasks.GlobalGame.config import TeamFlow, Transport
+
+from module.logger import logger
+
+
+def on_message(client, userdata, msg):
+    if msg.topic == 'FirstNotice':
+        return
+
+    logger.info(f"Received `{msg.payload}` from `{userdata}` ")
+# ----------------------------------------------------------------------------------------------------------------------
+# 使用MQTT是为了做广播,自己手撸的话太麻烦了
+# 0. 所有玩家更新自己的策略后必须广播出去, 可以延迟一下
+# 1. 当一个玩家启动接入网络后,会向服务器发送FirstNotice,这个时候所有的玩家都要发送一次自己的策略来给新加入的玩家来优化自己的策略
+# 2. 当一个玩家退出网络后,会向服务器发送LastNotice,这个时候所有的玩家都要更新自己的策略
+# ----------------------------------------------------------------------------------------------------------------------
+class Mqtt:
+
+    def __init__(self, team_flow: TeamFlow):
+        def on_connect(client, userdata, flags, rc):
+            if rc == 0:
+                logger.info("Connected to MQTT Broker!")
+            else:
+                logger.info("Failed to connect, return code %d\n", rc)
+        self.broker = team_flow.broker
+        self.port = team_flow.port
+        self.protocol = team_flow.transport
+        self.ca = team_flow.ca
+        self.username = team_flow.username
+        self.password = team_flow.password
+        self.client_id = f'{self.username}-{randint(0, 1000)}'
+        # 连接服务器
+        self.client = mqtt_client.Client(self.client_id, clean_session=True, userdata=self)
+        if self.protocol == Transport.SSL_TLS:
+            self.client.tls_set(ca_certs=self.ca)
+        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.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})
+
+
+
+    def set_on_message(self, on_msg):
+        self.client.on_message = on_msg
+
+    def publish(self, topic: str, msg: dict) -> bool:
+        """
+
+        :param topic:
+        :param msg: 必须是一个字典
+        :return:
+        """
+        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))
+        # result: [0, 1]
+        status = result[0]
+        if status == 0:
+            logger.info(f"Send `{msg}` to topic `{topic}`")
+            return True
+        else:
+            logger.info(f"Failed to send message to topic {topic} {status}")
+            return False
+
+    def TaskStart(self, msg):
+        self.publish('TaskStart', msg)
+
+    def Strategy(self, msg):
+        self.publish('Strategy', msg)
+
+
+
+
+
+if __name__ == '__main__':
+    team_flow = TeamFlow()
+    team_flow.broker = 'v96bb091.ala.cn-hangzhou.emqxsl.cn'
+    team_flow.port = 8883
+    team_flow.transport = Transport.SSL_TLS
+    team_flow.ca = './config/emqxsl-ca.crt'
+    team_flow.username = 'test-publish'
+    team_flow.password = '12345678'
+    mqtt = Mqtt(team_flow)
+    sleep(20)
+
+

+ 65 - 0
module/team_flow/mqtt_test.py

@@ -0,0 +1,65 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from time import sleep
+from random import randint
+from paho.mqtt import client as mqtt_client
+
+broker = 'v96bb091.ala.cn-hangzhou.emqxsl.cn'
+port = 8883
+topic = 'python/mqtt'
+client_id = f'python-mqtt-{randint(0, 1000)}'
+# 如果 broker 需要鉴权,设置用户名密码
+username = 'test-publish'
+password = '12345678'
+
+def connect_mqtt():
+    def on_connect(client, userdata, flags, rc):
+        if rc == 0:
+            print("Connected to MQTT Broker!")
+        else:
+            print("Failed to connect, return code %d\n", rc)
+
+    # Set Connecting Client ID
+    client = mqtt_client.Client(client_id)
+    client.tls_set(ca_certs='./emqxsl-ca.crt')
+    client.username_pw_set(username, password)
+    client.on_connect = on_connect
+    client.connect(broker, port)
+    return client
+
+def subscribe(client: mqtt_client):
+    def on_message(client, userdata, msg):
+        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
+
+    client.subscribe(topic=topic, qos=0)
+    client.on_message = on_message
+
+
+def publish(client):
+    msg_count = 0
+    while True:
+        sleep(1)
+        msg = f"messages: {msg_count}"
+        result = client.publish(topic, msg)
+        # result: [0, 1]
+        status = result[0]
+        if status == 0:
+            print(f"Send `{msg}` to topic `{topic}`")
+        else:
+            print(f"Failed to send message to topic {topic} {status}")
+        msg_count += 1
+
+def on_message(client, userdata, msg):
+    print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
+
+def run():
+    client = connect_mqtt()
+    client.loop_start()
+    publish(client)
+
+
+
+if __name__ == '__main__':
+    run()
+

+ 33 - 0
module/team_flow/player.py

@@ -0,0 +1,33 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from time import sleep
+from datetime import datetime, time
+from random import randint
+
+
+from module.config.config import Config
+
+class Player:
+    def __init__(self, username: str):
+        self.username = username
+        self.multi_tasks: list = []  # 缓存多人任务的列表
+
+
+    def publish_data(self) -> list:
+        """
+        提取要 发布的数据
+        :return:
+        """
+        result = []
+        for task in self.multi_tasks:
+            item = {}
+            if not task.team_task:
+                continue
+            item['task_name'] = task.task_name
+            item['next_run'] = task.next_run
+            item['role'] = task.role
+            item['limit_time'] = task.limit_time
+            item['limit_count'] = task.limit_count
+            result.append(item)
+        return result

+ 35 - 0
module/team_flow/task.py

@@ -0,0 +1,35 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from time import sleep
+from datetime import datetime, time
+from random import randint
+
+
+from module.config.config import Config
+
+
+class Task:
+    def __init__(self,
+                 task_name: str,  # 任务名称,必须是大写的
+                 next_run: datetime,
+                 limit_time: time,
+                 target_run: datetime = None,
+                 team_task: bool = False,
+                 role: str = 'leader',
+                 limit_count: int = 0,
+                 ):
+        self.task_name = task_name
+        self.next_run = next_run
+        self.target_run = target_run
+        self.limit_time = limit_time
+        self.team_task = team_task
+        self.role = role
+        self.limit_count = limit_count
+
+
+
+
+
+
+

+ 2 - 1
requirements-in.txt

@@ -16,4 +16,5 @@ pydantic==1.10.7
 inflection==0.5.1
 tqdm==4.65.0
 ppocr-onnx==0.0.3.9
-onepush==1.2.0
+onepush==1.2.0
+paho-mqtt==1.6.1

+ 1 - 0
requirements.txt

@@ -37,6 +37,7 @@ onepush==1.2.0            # via -r requirements-in.txt
 onnxruntime==1.15.0       # via ppocr-onnx
 opencv-python==4.7.0.72   # via -r requirements-in.txt, ppocr-onnx
 packaging==20.9           # via deprecation, onnxruntime, uiautomator2
+paho-mqtt==1.6.1          # via -r requirements-in.txt
 pillow==9.5.0             # via ppocr-onnx, uiautomator2
 ppocr-onnx==0.0.3.9       # via -r requirements-in.txt
 progress==1.6             # via uiautomator2

+ 3 - 3
tasks/DemonEncounter/script_task.py

@@ -346,17 +346,17 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets):
         如果不在17:00到22:00之间,就推迟到下一个 17:30
         :return:
         """
-        now = datetime.datetime.now()
+        now = datetime.now()
         if now.hour < 17:
             # 17点之前,推迟到当天的17点半
             logger.info('Before 17:00, wait to 17:30')
-            target_time = datetime.datetime(now.year, now.month, now.day, 17, 30, 0)
+            target_time = datetime(now.year, now.month, now.day, 17, 30, 0)
             self.set_next_run(task='DemonEncounter', success=False, finish=False, target=target_time)
             return False
         elif now.hour >= 22:
             # 22点之后,推迟到第二天的17:30
             logger.info('After 22:00, wait to 17:30')
-            target_time = datetime.datetime(now.year, now.month, now.day, 17, 30, 0) + datetime.timedelta(days=1)
+            target_time = datetime(now.year, now.month, now.day, 17, 30, 0) + datetime.timedelta(days=1)
             self.set_next_run(task='DemonEncounter', success=False, finish=False, target=target_time)
             return False
         else:

+ 17 - 0
tasks/GlobalGame/config.py

@@ -1,11 +1,28 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+from enum import Enum
 from pydantic import BaseModel, Field
 
 from tasks.GlobalGame.config_emergency import Emergency
 from tasks.Component.config_base import ConfigBase
 
+class Transport(str, Enum):
+    TCP = 'TCP'
+    SSL_TLS = 'SSL/TLS'
+
+
+class TeamFlow(BaseModel):
+    enable: bool = Field(default=False, description='enable_help')
+    broker: str = Field(default='', description='broker_help')
+    port: int = Field(default=8883, description='port_help')
+    transport: Transport = Field(default=Transport.TCP, description='transport_help')
+    ca: str = Field(default='', description='ca_help')
+    username: str = Field(default='', description='username_help')
+    password: str = Field(default='', description='password_help')
+
+
 class GlobalGame(BaseModel):
     emergency: Emergency = Field(default_factory=Emergency)
+    team_flow: TeamFlow = Field(default_factory=TeamFlow)