一、基本介绍
在Python中使用MQTT,通常会使用paho-mqtt
这个库,它是一个广泛使用的MQTT客户端库,支持MQTT v3.1和v3.1.1协议。
二、基本步骤
安装paho-mqtt库:
使用pip安装paho-mqtt库:
bash
pip3 install paho-mqtt
创建MQTT连接:
设置MQTT代理(Broker)的地址、端口和主题(topic),并生成一个随机的客户端ID。
python
from paho.mqtt import client as mqtt_client
import random
broker = 'broker.emqx.io' # MQTT代理地址
port = 1883 # MQTT代理端口
topic = "/python/mqtt" # 订阅的主题
client_id = f'python-mqtt-{random.randint(0, 1000)}' # 客户端ID
编写连接回调函数:
当客户端成功连接到MQTT代理时,会调用on_connect
回调函数。
python
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
创建客户端并连接:
创建一个MQTT客户端对象,并设置连接回调函数,然后连接到MQTT代理。
python
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
发布消息:
使用publish
方法向指定的主题发布消息。
python
def publish(client):
msg_count = 0
while True:
msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
if result[0] == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
msg_count += 1
time.sleep(1)
订阅消息:
设置on_message
回调函数来处理接收到的消息,并使用subscribe
方法订阅主题。
python
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
def subscribe(client):
client.subscribe(topic)
client.on_message = on_message
启动网络循环:
使用loop_forever
或loop_start
方法启动网络循环,以处理网络事件。
python
client.loop_forever() # 或者使用 client.loop_start() 在不同的线程中运行
三、完整代码示例
以下是一个完整的代码示例,展示了如何连接MQTT代理、发布消息和订阅消息。
python
# python 3.6
import random
import time
from paho.mqtt import client as mqtt_client
broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
def publish(client):
msg_count = 0
while True:
msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
if result[0] == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
msg_count += 1
time.sleep(1)
def subscribe(client):
client.subscribe(topic)
client.on_message = on_message
def run():
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker, port)
client.loop_start()
publish(client)
if __name__ == '__main__':
run()