test.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import paho.mqtt.client as mqtt
  2. import json
  3. class EstimationWeightUpdate(object):
  4. def __init__(self):
  5. self.init_mqtt()
  6. # The callback for when the client receives a CONNACK response from the server.
  7. def on_connect(self, client, userdata, flags, rc):
  8. print("Connected with result code "+str(rc)) #rc的值很重要,为0代表连接成功。
  9. # Subscribing in on_connect() means that if we lose the connection and
  10. # reconnect then subscriptions will be renewed.
  11. self.client.subscribe("$SYS/#") #订阅$SYS/下的所有主题
  12. # The callback for when a PUBLISH message is received from the server.
  13. def on_message(self, client, userdata, msg):
  14. print(msg.topic+" "+str(msg.payload))
  15. def init_mqtt(self):
  16. self.client = mqtt.Client("ADADWWRWFGWERWRWFGTERTER-SUB")
  17. self.client.username_pw_set("admin", password="longruan123")
  18. self.client.on_connect = self.on_connect #连接broker时broker响应的回调
  19. self.client.on_message = self.on_message #接收到订阅消息时的回调
  20. def subscribe_update_topic(self):
  21. self.client.connect("10.71.146.182", 1883, 60) #连接到broker
  22. self.client.subscribe("1/1/1", 0)
  23. self.client.loop_forever()
  24. if __name__ == "__main__":
  25. ew = EstimationWeightUpdate()
  26. ew.subscribe_update_topic()