mqtt_async.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from paho.mqtt import client as mqtt_client
  2. class MqttAsync(object):
  3. def __init__(self):
  4. self.connected=False
  5. def connect(self,client_id,ip,port,user,password):
  6. self.client_id=client_id
  7. def on_connect(client, userdata, flags, rc):
  8. if rc == 0:
  9. print("Connected to MQTT Broker!")
  10. else:
  11. print("Failed to connect, return code %d\n", rc)
  12. self.client = mqtt_client.Client(self.client_id)
  13. self.client.username_pw_set(user, password)
  14. self.client.on_connect = on_connect
  15. self.client.connect(ip, port)
  16. self.connected=True
  17. def publish(self,topic,msg):
  18. if self.connected==False:
  19. print("mqtt is not connected Failed to send message to topic {topic}")
  20. result = self.client.publish(topic, msg,qos=1)
  21. status = result[0]
  22. if status == 0:
  23. print("Send :%s"%(msg))
  24. else:
  25. print(f"Failed to send message to topic {topic}")
  26. def subscribe(self,topic,callback):
  27. self.client.subscribe(topic)
  28. self.client.on_message = callback
  29. def loop_start(self):
  30. self.client.loop_start()