mqtt.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from time import sleep
  5. import json
  6. from random import randint
  7. from paho.mqtt import client as mqtt_client
  8. from threading import Thread
  9. from queue import Queue
  10. from tasks.GlobalGame.config import TeamFlow, Transport
  11. from module.logger import logger
  12. from module.base.timer import Timer
  13. def on_message(client, userdata, msg):
  14. if msg.topic == 'FirstNotice':
  15. return
  16. logger.info(f"Received `{msg.payload}` from `{userdata}` ")
  17. # ----------------------------------------------------------------------------------------------------------------------
  18. # 使用MQTT是为了做广播,自己手撸的话太麻烦了
  19. # 0. 所有玩家更新自己的策略后必须广播出去, 可以延迟一下
  20. # 1. 当一个玩家启动接入网络后,会向服务器发送FirstNotice,这个时候所有的玩家都要发送一次自己的策略来给新加入的玩家来优化自己的策略
  21. # 2. 当一个玩家退出网络后,会向服务器发送LastNotice,这个时候所有的玩家都要更新自己的策略
  22. # ----------------------------------------------------------------------------------------------------------------------
  23. class Mqtt:
  24. # 队列的结构必须是一个tuple,第一个元素是topic,第二个元素是msg
  25. q_publish: Queue = None
  26. def __init__(self, team_flow: TeamFlow):
  27. def on_connect(client, userdata, flags, rc):
  28. if rc == 0:
  29. logger.info("Connected to MQTT Broker!")
  30. elif rc == 1:
  31. # 协议版本错误
  32. logger.error(f"Connection refused - incorrect protocol version. return code: {rc}")
  33. elif rc == 2:
  34. # 无效的客户端标识
  35. logger.error(f"Connection refused - invalid client identifier. return code: {rc}")
  36. elif rc == 3:
  37. # 服务器不可用
  38. logger.error(f"Connection refused - server unavailable. return code: {rc}")
  39. elif rc == 4:
  40. # 错误的用户名或密码
  41. logger.error(f"Connection refused - bad username or password. return code: {rc}")
  42. elif rc == 5:
  43. # 未授权
  44. logger.error(f"Connection refused - not authorised. return code: {rc}")
  45. else:
  46. logger.info("Failed to connect, return code %d\n", rc)
  47. self.q_publish = Queue()
  48. self.broker = team_flow.broker
  49. self.port = team_flow.port
  50. self.protocol = team_flow.transport
  51. self.ca = team_flow.ca
  52. self.username = team_flow.username
  53. self.password = team_flow.password
  54. self.client_id = f'{self.username}-{randint(0, 1000)}'
  55. # 连接服务器
  56. self.client = mqtt_client.Client(self.client_id, clean_session=True, userdata=self)
  57. if self.protocol == Transport.SSL_TLS:
  58. self.client.tls_set(ca_certs=self.ca)
  59. self.client.username_pw_set(self.username, self.password)
  60. self.client.on_connect = on_connect
  61. self.client.on_message = on_message
  62. self.client.will_set(topic='LastWill', payload=json.dumps({self.username: ""}), qos=2)
  63. self.client.connect(self.broker, self.port)
  64. # 订阅主题: FirstNotice LastWill TaskStart Strategy
  65. self.client.subscribe(topic='FirstNotice', qos=2)
  66. self.client.subscribe(topic='LastWill', qos=2)
  67. self.client.subscribe(topic='TaskStart', qos=0)
  68. self.client.subscribe(topic='Strategy', qos=0)
  69. # publish FirstNotice
  70. self.publish("FirstNotice", {"type": "join"})
  71. # 开启一个线程来处理消息
  72. self.mqtt_timer = Timer(30)
  73. self.mqtt_timer.start()
  74. self.mqtt_thread = Thread(target=self.mqtt_loop, name='mqtt_loop', daemon=True)
  75. self.mqtt_thread.start()
  76. def set_on_message(self, on_msg):
  77. self.client.on_message = on_msg
  78. def publish(self, topic: str, msg: dict) -> bool:
  79. """
  80. :param topic:
  81. :param msg: 必须是一个字典
  82. :return:
  83. """
  84. if not isinstance(msg, dict):
  85. logger.warning(f"Msg must be a dict, but got {type(msg)}")
  86. return False
  87. msg = {self.username: msg}
  88. result = self.client.publish(topic, json.dumps(msg))
  89. # result: [0, 1]
  90. status = result[0]
  91. if status == 0:
  92. logger.info(f"Send `msg` to topic `{topic}`")
  93. return True
  94. else:
  95. logger.info(f"Failed to send message to topic {topic} {status}")
  96. return False
  97. def TaskStart(self, msg):
  98. self.publish('TaskStart', msg)
  99. def Strategy(self, msg):
  100. self.publish('Strategy', msg)
  101. def mqtt_loop(self):
  102. while True:
  103. # sleep(5)
  104. # 官方超级不推荐这种方式来处理消息。 但是不打算开一个线程来处理这个mqtt_timer
  105. try:
  106. self.client.loop(timeout=5)
  107. except Exception as e:
  108. logger.error(e)
  109. if not self.mqtt_timer.reached():
  110. continue
  111. self.mqtt_timer.reset()
  112. publish_strategy_msg = None
  113. while not self.q_publish.empty():
  114. try:
  115. topic, msg = self.q_publish.get(block=False)
  116. except Exception as e:
  117. continue
  118. if topic == 'Strategy':
  119. publish_strategy_msg = msg
  120. continue
  121. self.publish(topic, msg)
  122. if publish_strategy_msg:
  123. # 先进先出 保证只发送一次最新的
  124. self.publish('Strategy', publish_strategy_msg)
  125. if __name__ == '__main__':
  126. team_flow = TeamFlow()
  127. team_flow.broker = 'v96bb091.ala.cn-hangzhou.emqxsl.cn'
  128. team_flow.port = 8883
  129. team_flow.transport = Transport.SSL_TLS
  130. team_flow.ca = './config/emqxsl-ca.crt'
  131. team_flow.username = 'test-publish'
  132. team_flow.password = '12345678'
  133. mqtt = Mqtt(team_flow)
  134. sleep(20)