网上找到的mqtt客户端和publish,python代码
上一篇 /
下一篇 2019-10-17 21:33:48
/ 个人分类:python
# !encoding:utf-8
importpaho.mqtt.publishaspublish
importtime
importpaho.mqtt.clientasmqtt
HOST ="127.0.0.1"
mqtt_server='192.168.13.101'
defclient_loop():
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
client = mqtt.Client(client_id)# ClientId不能重复,所以使用当前时间
client.username_pw_set("admin","123456")#必须设置,否则会返回「Connected with result code 4」
client.on_connect = on_connect
client.on_message = on_message
client.connect(mqtt_server,1883,60)
client.loop_forever()
defon_connect(client,userdata,flags,rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
defon_message(client,userdata,msg):
print(msg.topic +" "+ msg.payload.decode("utf-8"))
if__name__ =='__main__':
client_loop()
# !encoding:utf-8
importpaho.mqtt.publishaspublish
importtime
importpaho.mqtt.clientasmqtt
HOST ="127.0.0.1"
PUBLISH_PORT =1883
mqtt_server='192.168.13.101'
defon_connect_publish(client,userdata,flags,rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
defon_message_publish(client,userdata,msg):
print(msg.topic +" "+ msg.payload.decode("utf-8"))
defmqttpublish():
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
# client = mqtt.Client(client_id) # ClientId不能重复,所以使用当前时间
# client.username_pw_set("admin", "123456") #必须设置,否则会返回「Connected with result code 4」
# client.on_connect = on_connect
# client.on_message = on_message
# client.connect(HOST, PORT, 60)
# client.publish("test", "你好MQTT", qos=0, retain=False) #发布消息
publish.single("test","你好MQTT",qos=1,hostname=mqtt_server,port=PUBLISH_PORT,client_id=client_id,
auth={'username':"admin",'password':"123456"})
mqttpublish()
学习用
mosquitto_pub -h 192.168.13.101 -p 1883 -u root -t "test" -m "helloe world iam"
mosquitto_sub -h 192.168.13.101 -p 1883 -t "test" -u admin -P "123456"
收藏
举报
TAG: