序号 | 名称 | 功能 | 地址 |
---|---|---|---|
1 | time | 获取时间和延时 | |
2 | paho-mqtt | MQTT—client端 | https://github.com/eclipse/paho.mqtt.python |
3 | time | 获取时间和延时 |
import time
timestring = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
time.sleep(0.1)
This document describes the source code for the Eclipse Paho MQTT Python client library, which implements versions 3.1 and 3.1.1 of the MQTT protocol.
import paho.mqtt.client as mqtt
import json
import time
#mqtt 代理器的端口和地址
HOST = "184.170.220.88"
PORT = 1883
#建立连接 确定订阅的话题,同时发布一条话题消息
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("/World")
client.publish("/World", json.dumps({"user": "user", "say": "Hello,anyone!"}))
#接收到订阅的话题消息
def on_message(client, userdata, msg):
print(msg.topic+" :"+str(msg.payload))
#print(msg.topic+":"+str(msg.payload.decode()))
#print(msg.topic+":"+msg.payload.decode())
## payload = json.loads(msg.payload.decode())
## print(payload.get("user")+":"+payload.get("say"))
#循环
def client_loop():
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
client = mqtt.Client(client_id)
client.username_pw_set("admin", "123456")
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, 60)
print("connecy success")
client.loop_forever()
if __name__ == '__main__':
client_loop()