mqtt.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. from random import randint
  6. from paho.mqtt import client as mqtt_client
  7. from tasks.GlobalGame.config import TeamFlow, Transport
  8. from module.logger import logger
  9. def on_message(client, userdata, msg):
  10. if msg.topic == 'FirstNotice':
  11. return
  12. logger.info(f"Received `{msg.payload}` from `{userdata}` ")
  13. # ----------------------------------------------------------------------------------------------------------------------
  14. # 使用MQTT是为了做广播,自己手撸的话太麻烦了
  15. # 0. 所有玩家更新自己的策略后必须广播出去, 可以延迟一下
  16. # 1. 当一个玩家启动接入网络后,会向服务器发送FirstNotice,这个时候所有的玩家都要发送一次自己的策略来给新加入的玩家来优化自己的策略
  17. # 2. 当一个玩家退出网络后,会向服务器发送LastNotice,这个时候所有的玩家都要更新自己的策略
  18. # ----------------------------------------------------------------------------------------------------------------------
  19. class Mqtt:
  20. def __init__(self, team_flow: TeamFlow):
  21. def on_connect(client, userdata, flags, rc):
  22. if rc == 0:
  23. logger.info("Connected to MQTT Broker!")
  24. else:
  25. logger.info("Failed to connect, return code %d\n", rc)
  26. self.broker = team_flow.broker
  27. self.port = team_flow.port
  28. self.protocol = team_flow.transport
  29. self.ca = team_flow.ca
  30. self.username = team_flow.username
  31. self.password = team_flow.password
  32. self.client_id = f'{self.username}-{randint(0, 1000)}'
  33. # 连接服务器
  34. self.client = mqtt_client.Client(self.client_id, clean_session=True, userdata=self)
  35. if self.protocol == Transport.SSL_TLS:
  36. self.client.tls_set(ca_certs=self.ca)
  37. self.client.username_pw_set(self.username, self.password)
  38. self.client.on_connect = on_connect
  39. self.client.on_message = on_message
  40. self.client.will_set(topic='LastWill', payload=self.username, qos=2)
  41. self.client.connect(self.broker, self.port)
  42. # 订阅主题: FirstNotice LastWill TaskStart Strategy
  43. self.client.subscribe(topic='FirstNotice', qos=2)
  44. self.client.subscribe(topic='LastWill', qos=2)
  45. self.client.subscribe(topic='TaskStart', qos=0)
  46. self.client.subscribe(topic='Strategy', qos=0)
  47. self.client.loop_start()
  48. # publish FirstNotice
  49. self.publish('FirstNotice', {'player': self.username})
  50. def set_on_message(self, on_msg):
  51. self.client.on_message = on_msg
  52. def publish(self, topic: str, msg: dict) -> bool:
  53. """
  54. :param topic:
  55. :param msg: 必须是一个字典
  56. :return:
  57. """
  58. if not isinstance(msg, dict):
  59. logger.warning(f"Msg must be a dict, but got {type(msg)}")
  60. return False
  61. result = self.client.publish(topic, str(msg))
  62. # result: [0, 1]
  63. status = result[0]
  64. if status == 0:
  65. logger.info(f"Send `{msg}` to topic `{topic}`")
  66. return True
  67. else:
  68. logger.info(f"Failed to send message to topic {topic} {status}")
  69. return False
  70. def TaskStart(self, msg):
  71. self.publish('TaskStart', msg)
  72. def Strategy(self, msg):
  73. self.publish('Strategy', msg)
  74. if __name__ == '__main__':
  75. team_flow = TeamFlow()
  76. team_flow.broker = 'v96bb091.ala.cn-hangzhou.emqxsl.cn'
  77. team_flow.port = 8883
  78. team_flow.transport = Transport.SSL_TLS
  79. team_flow.ca = './config/emqxsl-ca.crt'
  80. team_flow.username = 'test-publish'
  81. team_flow.password = '12345678'
  82. mqtt = Mqtt(team_flow)
  83. sleep(20)