python实现mqtt订阅、发布
发布
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
import time
HOST = "xxxxxx"
PORT = 1883
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
if __name__ == '__main__':
client = mqtt.Client(client_id)
client.username_pw_set("test", "test")
client.connect(HOST, PORT, 60)
msg = input("please input you send message:")
client.publish("利川", msg, qos=0) # 发送消息
订阅
#coding=utf-8
import paho.mqtt.client as mqtt
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
HOST = "xxxx"
PORT = 1883
def client_loop():
client_id = "0bd981c5-a055-4196-8b7f-efb9f7a4d6ac"
client = mqtt.Client(client_id) # ClientId不能重复,所以使用当前时间
client.username_pw_set("test", "test") # 必须设置,否则会返回「Connected with result code 4」
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, 60)
client.loop_forever()
def on_connect(client, userdata, flags, rc):
client.subscribe("test")
def trun(a):
if(a == "打开"):
print("我要开灯了")
else:
print("我要关灯了")
def on_message(client, userdata, msg):
print(msg.topic+" "+msg.payload.decode("utf-8"))
trun(msg.payload.decode("utf-8"))
if __name__ == '__main__':
global a
a = -1
client_loop()
注意:用户id不能重复,所以要随机生成。