我们在MQTT 到底是什么???这期文章中,有朋友留言:
那么,这期就C++开发和应用MQTT示例代码和大家分享下。
我们整理了各种来源,主要有下面三种C++的库供大家参考:
Eclipse Paho MQTT C++客户端库的源代码,适用于如 Linux、MacOS 和 Windows 等内存管理操作系统。
该代码构建了一个库,使现代 C++应用程序(C++17 及以上版本)能够连接到 MQTT 代理、发布消息、订阅主题并从代理接收消息。
该库具有以下功能:
此代码需要 Ian Craggs 等人编写的 Paho C 库,具体是 1.3.14 版本或可能更晚的版本。
下面贴一个典型应用程序的示例:
int main(int argc, char* argv[])
{
sample_mem_persistence persist;
mqtt::client cli(ADDRESS, CLIENT_ID, &persist);
callback cb;
cli.set_callback(cb);
auto connOpts = mqtt::connect_options_builder()
.keep_alive_interval(20);
.clean_session()
.finalize();
try {
cli.connect(connOpts);
// First use a message pointer.
mqtt::message_ptr pubmsg = mqtt::make_message(PAYLOAD1);
pubmsg->set_qos(QOS);
cli.publish(TOPIC, pubmsg);
// Now try with itemized publish.
cli.publish(TOPIC, PAYLOAD2, strlen(PAYLOAD2)+1, 0, false);
// Disconnect
cli.disconnect();
}
catch (const mqtt::persistence_exception& exc) {
cerr << "Persistence Error: " << exc.what() << " ["
<< exc.get_reason_code() << "]" << endl;
return 1;
}
catch (const mqtt::exception& exc) {
cerr << "Error: " << exc.what() << " ["
<< exc.get_reason_code() << "]" << endl;
return 1;
}
return 0;
}
具体代码地址:
https://github.com/eclipse-paho/paho.mqtt.cpp
官网下载:
https://eclipse.dev/paho/
另一个项目完整地址:
https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-C-paho
libmosquitto
Mosquitto 是 MQTT 协议 5.0、3.1.1 和 3.1 版本的开源实现。它还包含一个C 和C++ 客户端库,以及用于发布和订阅的 mosquitto_pub
和 mosquitto_sub
工具。
以下是一个简单的示例,展示了如何使用Mosquitto C++库来创建一个MQTT客户端,连接到MQTT代理,并订阅主题:
#include <iostream>
#include <mosquittopp.h>
class MyMqttClient : public mosqpp::mosquittopp {
public:
MyMqttClient(const char* id) : mosqpp::mosquittopp(id) {}
void on_connect(int rc) override {
if (rc == 0) {
std::cout << "Connected to MQTT broker" << std::endl;
subscribe(NULL, "test/topic", 1);
} else {
std::cerr << "Failed to connect to MQTT broker" << std::endl;
}
}
void on_message(const struct mosquitto_message* message) override {
std::cout << "Received message: " << message->payloadlen << " bytes" << std::endl;
std::cout << "Payload: " << static_cast<char*>(message->payload) << std::endl;
}
};
int main() {
MyMqttClient client("cpp_client");
client.connect("localhost", 1883, 60);
client.loop_forever();
return 0;
}
另外一个项目演示了使用 MQTT 协议收集环境数据(压力、温度和湿度)的方法,这些 MQTT 客户端分布在多个位置,运行在连接了 Pi Sense HAT 的 Raspberry Pi 上。选择使用 libmosquitto 实现 C/C++中的 MQTT 订阅者和发布者代码,而 Mosquitto 则是用于测试实现的 MQTT 代理。
项目源代码地址:
https://github.com/positronic57/MQTT_examples_with_libmosquito
开源的详细代码仓库地址:
https://github.com/eclipse-mosquitto/mosquitto
Boost.MQTT5
Boost.MQTT5 是一个基于 Boost.Asio 的 C++17 客户端。该客户端用于向 MQTT 5.0 兼容的代理发布或接收消息。Boost.MQTT5 提供了 MQTT 5.0 协议标准的全面实现,支持 QoS 0、1 和 2 级别的消息发布或接收。
关于Boost的详细说明参考:
https://www.boost.org/doc/libs/master/libs/mqtt5/doc/html/mqtt5/intro.html
以下示例说明了配置一个 Client 并发布一条 "Hello World!" 应用消息的场景 QoS
0。
#include <boost/mqtt5/mqtt_client.hpp>
#include <boost/mqtt5/types.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <iostream>
int main() {
boost::asio::io_context ioc;
boost::mqtt5::mqtt_client<boost::asio::ip::tcp::socket> c(ioc);
c.brokers("<your-mqtt-broker>", 1883)
.credentials("<your-client-id>", "<client-username>", "<client-pwd>")
.async_run(boost::asio::detached);
c.async_publish<boost::mqtt5::qos_e::at_most_once>(
"<topic>", "Hello world!",
boost::mqtt5::retain_e::no, boost::mqtt5::publish_props {},
[&c](boost::mqtt5::error_code ec) {
std::cout << ec.message() << std::endl;
c.async_disconnect(boost::asio::detached); // disconnect and close the Client
}
);
ioc.run();
}
更多的示例代码:
https://www.boost.org/doc/libs/master/libs/mqtt5/doc/html/mqtt5/examples.html
GitHub地址:
https://github.com/boostorg/mqtt5
关于C++开发MQTT应用的示例实际上典型的几种我们已经介绍完毕,具体的内容还请参考原文的地址。