pthon对emqtt的简单操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pthon对emqtt的简单操作相关的知识,希望对你有一定的参考价值。
需要先下载外部包
pip install paho-mqtt
发布者
import paho.mqtt.client as mqtt
HOST = "192.168.44.31"
PORT = 1883
def Publish_Message():
client = mqtt.Client()
client.username_pw_set(username=‘admin‘, password=‘public‘) # 用于添加了插件认证方式后
client.connect(HOST, PORT, 60)
for x in range(10):
Message = "hello" + str(x)
client.publish("services", Message, 0) # 发布一个主题为‘services‘,内容为‘hello x’的信息
# time.sleep(10)
client.loop_forever() # 保持连接状态
if __name__ == ‘__main__‘:
Publish_Message()
发布者,主要内容:publish("topic_name","utf8_message",Qos)
- Qos:0 --> 发送者只发送一次消息,不进行重试,Broker不会返回确认消息。Broker可能没有接收到消息。(默认)
- Qos:1 --> 发送者最少发送一次消息,确保消息达到Broker,Broker需要返回确认消息PUBACK。Broker可能接收到重复消息。
- Qos:2 --> 使用两阶段确认来保证消息的不丢失和不重复。Broker肯定会接收到消息,且只收到一次。
订阅者
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc)) # rc表示返回来的状态值
client.subscribe("services")
def on_message(client, userdata, msg):
print(msg.topic+" " + ":" + str(msg.payload))
if __name__ == "__main__":
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username=‘admin‘, password=‘public‘) # 用于添加了插件认证方式后
client.connect("192.168.44.31", 1883, 60)
client.loop_forever()
订阅者,信息的产出在msg.payload
rc值代表的含义:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.
以上是关于pthon对emqtt的简单操作的主要内容,如果未能解决你的问题,请参考以下文章