python与c++程序通过mqtt通信

本文介绍了如何让Python和C++程序通过MQTT进行通信。首先讲解了MQTT的安装与基本测试,然后分别展示了Python和C++部分的实现。在C++部分,提到了使用paho.mqtt.c库,并给出了下载、编译和安装的步骤。最后,说明了通信流程,即先运行C++程序,再运行Python程序,可以成功接收数据。
摘要由CSDN通过智能技术生成

mqtt安装与基本测试

#安装mosquitto mqtt
#引入仓库
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
#更新源
sudo apt-get update
#安装mosquitto
sudo apt install mosquitto
#安装客户端
sudo apt-get install mosquitto-clients
######测试
#一个终端开启sub mqtt
mosquitto_sub -h localhost -t "test_local" -v
#另一个终端发布信息,看能否收到
mosquitto_pub -h localhost -t "test_local" -m "HELLO MQTT"

若sub的中端收到,那么mqtt安装成功。

python部分

#api参考网站
https://pypi.org/project/paho-mqtt/#usage-and-api
#安装pip
sudo apt install python-pip
#安装python 的mqtt包
pip install paho-mqtt
publish.single("MQTT Examples", 2); 第一个参数为mqtt的topic第二个是内容。
import paho.mqtt.publish as publish

publish.single("MQTT Examples", 2)

c++部分

#paho.mqtt.c 库
https://github.com/eclipse/paho.mqtt.c

#下载oaho c库
git clone https://github.com/eclipse/paho.mqtt.c.git
#编译安装
make
sudo make install

#编译sub程序
g++ MQTTClient_subscribe.c -o sub -lpaho-mqtt3c

/*******************************************************************************
 * Copyright (c) 2012, 2020 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v2.0
 * and Eclipse Distribution License v1.0 which accompany this distribution. 
 *
 * The Eclipse Public License is available at 
 *   https://www.eclipse.org/legal/epl-2.0/
 * and the Eclipse Distribution License is available at 
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Ian Craggs - initial contribution
 *******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值