B站: 迷途小书童的Note;微信公众号: Dev_Club;个人微信:xituxiaoshutong100

Python使用paho-mqtt进行MQTT消息通讯

Python进阶 迷途小书童 0评论

软硬件环境

  • ubuntu 18.04 64bit
  • anaconda3 & python3.6.2
  • paho-mqtt

预备知识

参考之前写的一篇博文 https://xugaoxiang.com/2019/12/08/mqtt/,博文测试时mqtt broker采用的是mosquitto,同时在测试发送和接收时采用mosquitto_submosquitto_pub命令行工具。

安装paho-mqtt

conda install paho-mqtt

代码实践

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    '''

    :param client:
    :param userdata:
    :param flags:
    :param rc:
    :return:
    '''

    print('connect with rc: {}'.format(rc))

    if rc != 0:
        print('pub connect failed.')
        client.disconnect()

def on_disconnect(client, userdata, rc=0):
    '''

    :param client:
    :param userdata:
    :param rc:
    :return:
    '''

    print('disconnect with rc: {}'.format(rc))

    client.loop_stop()

def on_publish(client, userdata, mid):
    '''

    :param client:
    :param userdata:
    :param mid:
    :return:
    '''

    print('publish success.')

def do_publish(topic, message):

    '''
    :param topic:
    :param message:
    :return: publish message via mqtt
    '''

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.on_publish = on_publish

    client.connect(host='127.0.0.1', port=1883, keepalive=60)
    client.loop_start()

    try:
        client.publish('{}'.format(topic), '{}'.format(message))
    except:
        print('publish {} exception.'.format(message))
    finally:
        client.disconnect()

上述代码完成的是信息发布,分别实现了客户端连接、发布、断开的回调,在connect之后调用loop_start(),其作用是开启新的后台线程,防止主线程被阻塞,在client断开后要loop_stop杀掉线程。

信息的订阅寄接收的过程跟发布是一样的,publish换成subscribe,接收在on_message回调里进行处理。

参考资料

喜欢 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址