mqtthelper.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import threading
  2. import paho.mqtt.client as mqtt
  3. from paho.mqtt.properties import Properties
  4. from paho.mqtt.packettypes import PacketTypes
  5. import logging
  6. import time
  7. logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
  8. level=logging.DEBUG,
  9. filename='/var/log/aligenie.log',
  10. filemode='a')
  11. class MQTTHelper():
  12. client = mqtt.Client(client_id="aligenie", protocol=5)
  13. logger = logging.getLogger()
  14. connectProperties = Properties(PacketTypes.CONNECT)
  15. publishProperties = Properties(PacketTypes.PUBLISH)
  16. def __init__(self):
  17. self.logger.info("连接MQTT服务:127.0.0.1")
  18. self.client.on_disconnect = self.on_disconnect
  19. # 定义最大主题别名数
  20. self.connectProperties.TopicAliasMaximum = 65532
  21. t1 = threading.Thread(target=self.connectHost, name='connect-daemon-thread')
  22. t1.start()
  23. def connectHost(self):
  24. self.client.connect("127.0.0.1",1883,0,properties=self.connectProperties)
  25. self.client.loop_start()
  26. while True:
  27. time.sleep(5)
  28. result = self.client.publish("heartbeat","alive")
  29. status = result[0]
  30. if status == 4:
  31. self.logger.info("服务器断线,尝试重新连接")
  32. self.client.loop_stop()
  33. self.client = mqtt.Client(client_id="aligenie", protocol=5)
  34. self.client.connect("127.0.0.1",1883,0,properties=self.connectProperties)
  35. self.logger.info("重连成功")
  36. self.client.loop_start()
  37. def send(self,content):
  38. self.logger.info("使用主题别名发送!")
  39. try:
  40. # 定义主题别名为双字节的1
  41. self.publishProperties.TopicAlias = 1
  42. self.client.publish("pccontrol",payload=content, properties=self.publishProperties)
  43. except Exception as e:
  44. self.logger.info(str(e))
  45. def on_disconnect(self, client, userdata, rc):
  46. self.logger.info("连接断开,5秒后尝试重连")
  47. time.sleep(5)
  48. self.client.reconnect()
  49. my_helper = MQTTHelper()