cpp mqtt paho 使用_paho-mqtt 回调方法的一次封装

本文介绍了如何使用Paho MQTT C++库,并通过回调方法封装成API,重点在于如何处理回调参数,使用户仅关注业务逻辑。示例代码展示了如何创建client,设置回调,接收和发送消息。
摘要由CSDN通过智能技术生成

先来看一下一个正常的使用示例:

# coding:utf-8

# filename:mqttDemo.py

#------------------Imports-------------------

import paho.mqtt.client as mqtt

import paho.mqtt.publish as publish

#--------------------------------------------

#----------------全局变量定义----------------

HOST = "localhost"

PORT = 1883

Username = 'username'

Password = 'password'

#--------------------------------------------

# 连接服务器

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

print("Connected with result code "+str(rc))

client.subscribe(client._topic)

# 发送消息

def send_message(topic, msg):

global HOST, PORT

try:

publish.single(topic, msg, hostname=HOST, port=PORT)

except:

print('[exception]: mqtt message send failed.')

# 回调方法

def on_message_callbak(client, userdata, msg):

try:

msg = msg.payload.decode('utf-8')

print(msg)

except:

print('[exception]: on_message callback exception. [API_mqtt.py -> on_message]')

# 获取client

def get_client(topic, func):

global Username, Password

client = mqtt.Client()

client._topic = topic

client.username_pw_set(Username, Password)

client.on_connect = on_connect

client.on_message = func

return client

# 消息接收

def receive_message(topic, func):

client = get_client(topic, func)

client.connect(HOST, PORT, 60)

client.loop_forever()

if __name__ == '__main__':

receive_message('testTopic', on_message_callback)

简单讲解一下:

<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值