What is the usage of MQTT in C++?

In C++, utilizing MQTT is achieved through the use of MQTT client libraries. These libraries provide a set of APIs for connecting to an MQTT broker and communicating with it. Some popular MQTT client libraries include the Paho MQTT C++ library and the Mosquitto MQTT C++ library. These libraries can assist you in implementing MQTT publish and subscribe functionality, as well as communicating with an MQTT broker.

Here is a simple example code using the Paho MQTT C++ library:

#include <iostream>
#include "mqtt/async_client.h"

int main() {
    const std::string address = "tcp://iot.eclipse.org:1883";
    const std::string client_id = "cpp_mqtt_client";
    mqtt::async_client client(address, client_id);

    mqtt::connect_options connOpts;
    connOpts.set_keep_alive_interval(20);
    connOpts.set_clean_session(true);

    client.set_callback([](const mqtt::message_ptr msg) {
        std::cout << "Received message: " << msg->get_payload_str() << std::endl;
    });

    try {
        client.connect(connOpts)->wait();
        client.subscribe("topic/test", 1)->wait();
        client.publish("topic/test", "Hello, MQTT from C++")->wait();
    } catch (const mqtt::exception& exc) {
        std::cerr << "Error: " << exc.what() << std::endl;
    }

    client.disconnect()->wait();

    return 0;
}

In this example, we used the Paho MQTT C++ library to create an MQTT client and connect to a public MQTT broker (iot.eclipse.org). We then subscribe to a topic named “topic/test” and publish a message to this topic. When we receive a message from the broker, we print it out in a callback function.

You can further customize and expand this sample code to implement more complex MQTT functionality based on your needs.

bannerAds