MQTT Wrapper Guide - Hyp-ed/hyped-2024 GitHub Wiki

This page is a guide to the MQTT wrapper class, including an overview how to set up an MQTT node.

Below is an example of how we can set up an MQTT node. We first must specify the client id, the port to communicate over and the host. These can then be used to construct an MQTT instance, as all the details of connecting to the broker are handled by the wrapper. We are then free to publish and subscribe messages to various topics.

We create the payload to publish using RapidJson. We first create a shared_ptr to a rapidjson::Document, then add the data we want to send to this object.

std::shared_ptr message_payload = std::make_unique<rapidjson::Document>();
message_payload->SetObject();
message_payload->AddMember("word", "Hello world!", message_payload->GetAllocator());
message_payload->AddMember("number", 42, message_payload->GetAllocator());

Once we have the payload we can construct an MqttMessage with a header, our payload, and the topic we want to publish the message to. To publish we simply pass the message we have constructed to Mqtt::publish along with a specified MqttMessageQos.

To subscribe to a topic, we simply pass the topic we want to subscribe to into the Mqtt::subcribe method. When we subscribe to a topic it allows us to receive all messages published to that topic. By using Mqtt::consume and Mqtt::get_message we can retrieve the most recent message, processing high priority messages first through the use of a custom priority queue. Mqtt::consume takes messages from the clients queue and adds them to our own custom queue. We then use Mqtt::get_message to pull the next message from this priority queue.

hyped::core::WallClock time;
hyped::core::Timer timer(time);
hyped::core::Logger logger("MQTT", hyped::core::LogLevel::kDebug, time);
const std::string id     = "test";
const std::uint16_t port = 8080;
const std::string host   = "localhost";
auto optional_mqtt       = hyped::core::Mqtt::create(logger, id, host, port);
if (!optional_mqtt) {
 std::cout << "Failed to connect to MQTT broker" << std::endl;
 return;
}
auto mqtt                       = *optional_mqtt;
const auto topic                = hyped::core::MqttTopic::kTest;
std::shared_ptr message_payload = std::make_unique<rapidjson::Document>();
message_payload->SetObject();
message_payload->AddMember("word", "Hello world!", message_payload->GetAllocator());
message_payload->AddMember("number", 42, message_payload->GetAllocator());
hyped::core::MqttMessage::Header header{
  .timestamp = 0, .priority = hyped::core::MqttMessagePriority::kCritical};
const hyped::core::MqttMessage message{topic, header, message_payload};
mqtt->publish(message, hyped::core::MqttMessageQos::kAtLeastOnce);
mqtt->subscribe(hyped::core::MqttTopic::kTest);
⚠️ **GitHub.com Fallback** ⚠️