Paho MQTT Python 客户端使用

Paho MQTT Python 客户端使用

1. 安装mqtt for python库

# 安装 paho-mqtt 2.X
pip install paho-mqtt

2. 一个简单的示例

import paho.mqtt.client as mqtt
import json

# 连接服务器应答回调
def on_connect(client, userdata, flags, reason_code, properties):
    # 打印连接状态码
    print(f"Connected with result code {reason_code}")
    # 订阅主题 "TEST/#",这里订阅前缀为TEST/的所有主题
    client.subscribe('TEST/#')

# 收到服务器消息回调
def on_message(client, userdata, msg):
    # 打印订阅的主题消息
    print(msg.topic + " " + str(msg.payload))
    # 解析json
    obj = json.loads(msg.payload)
    print(f"parse json:{obj}")
    # 遍历字典(dict)
    for k, v in obj.items():
        print(f"key = {k}, value = {v}")

# 创建MQTT使用V2版本API
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

# 注册回调
mqttc.on_connect = on_connect
mqttc.on_message = on_message

# 连接服务器,指定服务器地址和端口,这里我们使用公共服务器
mqttc.connect('mqtt.eclipseprojects.io', 1883, 60)
print('mqtt client start loop......')

# 这里是堵塞循环
mqttc.loop_forever()
mqtt client start loop......
Connected with result code Success
TEST/CLIENTS/DATA b'{"adress":"123456","name":"null","type":"LCD_THERMOSTATE","t_01":"0.00","t_02":"0.00","t_03":"0.00","t_04":"0.00","h_01":"0","p_01":"0","co2":"0","ip":"192.168.0.100","mask":"255.255.255.0","mac":"F0-F5-BD-10-29-68","state":"offline"}'
parse json:{'adress': '123456', 'name': 'null', 'type': 'LCD_THERMOSTATE', 't_01': '0.00', 't_02': '0.00', 't_03': '0.00', 't_04': '0.00', 'h_01': '0', 'p_01': '0', 'co2': '0', 'ip': '192.168.0.100', 'mask': '255.255.255.0', 'mac': 'F0-F5-BD-10-29-68', 'state': 'offline'}
key = adress, value = 123456
key = name, value = null
key = type, value = LCD_THERMOSTATE
key = t_01, value = 0.00
key = t_02, value = 0.00
key = t_03, value = 0.00
key = t_04, value = 0.00
key = h_01, value = 0
key = p_01, value = 0
key = co2, value = 0
key = ip, value = 192.168.0.100
key = mask, value = 255.255.255.0
key = mac, value = F0-F5-BD-10-29-68
key = state, value = offline

3. 一个完整的例子

创建MQTT连接(TCP连接)
指定MQTT连接的服务器地址、端口号、主题,生成随机客户端ID。
from paho.mqtt import client as mqtt_client
import random
import time
import logging
import json

broker = 'broker.emqx.io'
port = 1883
topic = "python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = 'emqx'
password = 'public'
创建连接到服务器的客户端对象,并注册连接回调函数 on_connect
def connect_mqtt():
    def on_connect(client, userdata, flags, rc, properties):
        if rc == 0:
            print("connected to MQTT Broker!")
        else:
            print(f"failed to connect, return code {rc}")
    # 设置连接客户端ID
    client = mqtt_client.Client(client_id = client_id, callback_api_version=mqtt_client.CallbackAPIVersion.VERSION2)
    # 设置用户名和密码
    # client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port, keepalive=120)
    return client
自动重连
FIRST_RECONNECT_DELAY = 1
RECONNECT_RATE = 2
MAX_RECONNECT_COUNT = 12
MAX_RECONNECT_DELAY = 60

FLAG_EXIT = False

def on_disconnect(client, userdata, rc):
    logging.info(f"disconnected with result code: {rc}")
    reconnect_count, reconnect_delay = 0, FIRST_RECONNECT_DELAY
    while reconnect_count < MAX_RECONNECT_COUNT:
        logging.info(f"reconnecting in {reconnect_count} seconds...")
        time.sleep(reconnect_delay)

        try:
            client.reconnect()
            logging.info("reconnected successfully!")
            return
        except Exception as err:
            logging.error(f"{err}. reconnect failed, retrying...")

        reconnect_delay *= RECONNECT_RATE
        reconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY)
        reconnect_count += 1
    logging.info(f"reconnect failed after {reconnect_count} attempts.Exiting...")
    global FLAG_EXIT
    FLAG_EXIT = True
发布消息
def publish(client):
    msg_count = 1
    while not FLAG_EXIT:
        msg_dict = {'msg':msg_count}
        msg = json.dumps(msg_dict)
        if not client.is_connected():
            logging.error("publish:MQTT client is not connected!")
            time.sleep(1)
            continue
        result = client.publish(topic, msg)
        status = result[0]
        if status == 0:
            print(f"send '{msg}' to topic '{topic}'")
        else:
            print(f"failed to send message to topic {topic}")
        
        msg_count += 1
        if msg_count > 5:
            break
        
        time.sleep(1)

订阅
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"received '{msg.payload.decode()}' from '{msg.topic}' topic")
    
    client.subscribe(topic)
    client.on_message = on_message

测试代码
def run():
    logging.basicConfig(format='%(asctimes - %(levelname)s:%(message)s)',level=logging.DEBUG)
    client = connect_mqtt()
    client.on_disconnect = on_disconnect
    subscribe(client)
    client.loop_start()
    time.sleep(1)
    if client.is_connected():
        publish(client)
    else:
        client.loop_stop()

    client.loop_stop()

if __name__ == '__main__':
    run()
connected to MQTT Broker!
send '{"msg": 1}' to topic 'python/mqtt'
received '{"msg": 1}' from 'python/mqtt' topic
send '{"msg": 2}' to topic 'python/mqtt'
received '{"msg": 2}' from 'python/mqtt' topic
send '{"msg": 3}' to topic 'python/mqtt'
received '{"msg": 3}' from 'python/mqtt' topic
send '{"msg": 4}' to topic 'python/mqtt'
received '{"msg": 4}' from 'python/mqtt' topic
send '{"msg": 5}' to topic 'python/mqtt'

关注公众号 “搏哥聊技术” 了解更多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搏哥聊技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值