from paho.mqtt import client as mqtt_client class MqttAsync(object): def __init__(self,client_id): self.client_id=client_id self.connected=False def connect(self,ip,port,user,password): def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) self.client = mqtt_client.Client(self.client_id) self.client.username_pw_set(user, password) self.client.on_connect = on_connect self.client.connect(ip, port) self.connected=True def publish(self,topic,msg): if self.connected==False: print("mqtt is not connected Failed to send message to topic {topic}") result = self.client.publish(topic, msg,qos=1) status = result[0] if status == 0: print("Send :%s"%{msg}) else: print(f"Failed to send message to topic {topic}")