1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import threading import paho.mqtt.client as mqtt import time
HOST = "xxxxx" PORT = 1883
class Mqtt_subscribe(threading.Thread): """ mqtt thread, 完成订阅功能 """
def __init__(self, subtopic): super(Mqtt_subscribe, self).__init__() self.client_id = time.strftime( '%Y%m%d%H%M%S', time.localtime( time.time())) self.client = mqtt.Client(self.client_id) self.client.user_data_set(subtopic) self.client.username_pw_set("admin", "public") self.message = None
def run(self): self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.connect(HOST, PORT, 60) self.client.loop_forever(timeout=60)
def on_connect(self, client, subtopic, flags, rc): print("Connected with result code " + str(rc)) print("topic:" + subtopic) client.subscribe(subtopic, 2)
def on_message(self, client, userdata, msg): self.mess_age = msg.payload.decode("utf-8") if 'test' in self.mess_age: self.client.disconnect() return self.mess_age
if __name__ == "__main__": subtopic = "test" t = Mqtt_subscribe(subtopic) t.start()
|