首页 > 编程语言 >Python 使用 MQTT

Python 使用 MQTT

时间:2023-11-17 21:34:34浏览次数:39  
标签:Python mqtt topic MQTT client connect 使用 msg def

官方参考文档:https://docs.emqx.com/zh/cloud/latest/connect_to_deployments/python_sdk.html

参考文档:https://zhuanlan.zhihu.com/p/187481769

发布消息

首先定义一个 while 循环语句,在循环中我们将设置每秒调用 MQTT 客户端 publish 函数向 /python/mqtt 主题发送消息。

import random
import time

from paho.mqtt import client as mqtt_client


broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'


def connect_mqtt():
    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)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"messages: {msg_count}"
        result = client.publish(topic, msg)
        # result: [0, 1]
        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


def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    run()

 

 

 

消息订阅代码

 

import random

from paho.mqtt import client as mqtt_client


broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'


def connect_mqtt() -> mqtt_client:
    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)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


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():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()


if __name__ == '__main__':
    run()

 

 

标签:Python,mqtt,topic,MQTT,client,connect,使用,msg,def
From: https://www.cnblogs.com/y593216/p/17839712.html

相关文章

  • 在Rider 中使用Entity Framework Core UI 插件创建EFCore 的 Migration迁移文件时报错
    报错信息EFCoretoolsarerequiredtoexecutethisaction在点击报错信息中的发Fix进行安装时,再次出错这次是提示版本不匹配这里我使用的是EFCore7.0.14版本的报错原因没有安装dotnettool点击Fix进行安装时,是安装的最新版,是要是.net7的安装dotnettool直......
  • JAVA中static关键字的使用
    static是静态的意思,是一个修饰符,就像是一个形容词,是用来形容类,变量,方法的。static修饰变量,这个变量就变成了静态变量,修饰方法这个方法就成了静态方法,static关键字方便在没有创建对象的情况下来进行调用(方法/变量)。1.static修饰变量通过static修饰成员变量,我们可以不用创建对象......
  • 燧机AI盒子设备使用体会
    项目急用买了这款设备,个人使用心得。优点:1、网站做的挺不错、散热做的不错。缺点:1、价格贵,识别率一般。2、估计是因为硬件算力低,图像压缩很模糊,后来发现是使用瑞芯微方案。3、除了支持三个事件接口,基本上不支持任何二次开发。......
  • Windows rustup update 速度慢,使用字节跳动Rust镜像加速
    不设置镜像加速rustup更新升级会非常慢RsProxy字节跳动的Rust镜像 Windows想要使用这个镜像需要按照官方提示去设置两个系统变量分别为 RUSTUP_DIST_SERVER RUSTUP_UPDATE_ROOT 之后来到当前用户文件夹下修改cargo的配置文件(没有就创建一个)C:\Users\你PC名\.c......
  • ESLint 的使用
    ESLint是一个语法规则和代码风格的检查工具,可以用来保证写出语法正确、风格统一的代码。首先,安装ESLint。$npmi-geslint然后,安装Airbnb语法规则,以及import、a11y、react插件。$npmi-geslint-config-airbnb$npmi-geslint-plugin-importeslint-plugin-jsx-a11ye......
  • MSYS2学习笔记:基础使用
    本随笔用于记录随笔作者在使用MSYS2工具过程中需要掌握到的基础知识,例如如何查找想要的工具与其下载、如何环境配置等基础操作。本文内容摘录自MSYS2官方文档该随笔会不定时更新。随笔作者还正处于学习阶段,难免出现技术上和书写上的问题,如果发现类似问题,欢迎在评论区或私信与我......
  • Python8days
    如何开启事务介绍常见的字段类型和参数图书管理系统MVC和MTV模式创建多对多表关系的三种方式AJAx的介绍Ajax的案例—————————————————————————————————————————————————————————————————————————......
  • 使用openjdk17编译时报错:Fatal error compiling: 错误: 不支持发行版本 1.17
    1.在linux环境下(docker镜像里面)使用如下命令编译打包时报错mvncleanpackage-Dmaven.test.skip=true[INFO]Scanningforprojects...[INFO][INFO]---------------------<xxx.xxx:pero-xdd>----------------------[INFO]Buildingpero-xdd0.0.1-SNAPSHOT[INFO]-......
  • Python:Pandas中df.iloc和df.loc区别
    1df.iloc官方文档中定义为“基于整数位置的索引,用于按位置选择。”df.iloc就是只根据行列号对数据进行切片或选择。当作数组取数就行。df.iloc[raw,col]:第一个参数raw表示行选,第二个参数表示列选,都必须是整数。importpandasaspdmydict=[{'a':1,'b':2,'d':4},......
  • Java使用HttpClient实现GET和POST请求
    GET请求(带参数)前端exportconstgetRealTimeData=(deviceLabel)=>{returnrequest({url:'/blade-inorganization/Data/realTime-data?deviceLabel='+deviceLabel,method:'get',})}import{getRealTimeData}from"@/api/......