Files
mqtt5/example/receiver.cpp
T

161 lines
5.5 KiB
C++
Raw Normal View History

2024-05-27 10:35:06 +02:00
//
2025-02-14 13:42:23 +01:00
// Copyright (c) 2023-2025 Ivica Siladic, Bruno Iljazovic, Korina Simicevic
2024-05-27 10:35:06 +02:00
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
//
2024-12-03 15:26:05 +01:00
#include <boost/asio/use_awaitable.hpp>
#ifdef BOOST_ASIO_HAS_CO_AWAIT
//[receiver
2025-01-13 16:11:41 +01:00
#include <boost/mqtt5/logger.hpp>
#include <boost/mqtt5/mqtt_client.hpp>
#include <boost/mqtt5/reason_codes.hpp>
#include <boost/mqtt5/types.hpp>
2024-03-15 09:40:39 +01:00
#include <boost/asio/as_tuple.hpp>
#include <boost/asio/co_spawn.hpp>
2024-12-03 15:26:05 +01:00
#include <boost/asio/deferred.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/io_context.hpp>
2025-01-13 16:11:41 +01:00
#include <boost/asio/ip/tcp.hpp>
2024-03-15 09:40:39 +01:00
#include <boost/asio/signal_set.hpp>
2025-01-13 16:11:41 +01:00
#include <iostream>
#include <string>
2024-12-03 15:26:05 +01:00
struct config {
2025-01-13 16:11:41 +01:00
std::string brokers = "broker.hivemq.com";
uint16_t port = 1883;
2025-02-17 12:31:40 +01:00
std::string client_id = "boost_mqtt5_tester";
2024-12-03 15:26:05 +01:00
};
2023-12-07 09:32:34 +01:00
2024-03-15 09:40:39 +01:00
// Modified completion token that will prevent co_await from throwing exceptions.
2024-12-03 15:26:05 +01:00
constexpr auto use_nothrow_awaitable = boost::asio::as_tuple(boost::asio::deferred);
2024-12-03 15:26:05 +01:00
// client_type with logging enabled
2025-01-13 16:11:41 +01:00
using client_type = boost::mqtt5::mqtt_client<
boost::asio::ip::tcp::socket, std::monostate /* TlsContext */, boost::mqtt5::logger
2024-12-03 15:26:05 +01:00
>;
// client_type without logging
2025-01-13 16:11:41 +01:00
//using client_type = boost::mqtt5::mqtt_client<boost::asio::ip::tcp::socket>;
2024-03-15 09:40:39 +01:00
boost::asio::awaitable<bool> subscribe(client_type& client) {
2025-01-13 16:11:41 +01:00
// Configure the request to subscribe to a Topic.
boost::mqtt5::subscribe_topic sub_topic = boost::mqtt5::subscribe_topic{
"test" /* topic */,
boost::mqtt5::subscribe_options {
boost::mqtt5::qos_e::exactly_once, // All messages will arrive at QoS 2.
boost::mqtt5::no_local_e::no, // Forward message from Clients with same ID.
boost::mqtt5::retain_as_published_e::retain, // Keep the original RETAIN flag.
boost::mqtt5::retain_handling_e::send // Send retained messages when the subscription is established.
}
};
2025-01-13 16:11:41 +01:00
// Subscribe to a single Topic.
auto&& [ec, sub_codes, sub_props] = co_await client.async_subscribe(
sub_topic, boost::mqtt5::subscribe_props {}, use_nothrow_awaitable
);
// Note: you can subscribe to multiple Topics in one mqtt_client::async_subscribe call.
2025-01-13 16:11:41 +01:00
// An error can occur as a result of:
// a) wrong subscribe parameters
// b) mqtt_client::cancel is called while the Client is in the process of subscribing
if (ec)
std::cout << "Subscribe error occurred: " << ec.message() << std::endl;
else
std::cout << "Result of subscribe request: " << sub_codes[0].message() << std::endl;
2024-03-15 09:40:39 +01:00
2025-01-13 16:11:41 +01:00
co_return !ec && !sub_codes[0]; // True if the subscription was successfully established.
2024-03-15 09:40:39 +01:00
}
2024-12-03 15:26:05 +01:00
boost::asio::awaitable<void> subscribe_and_receive(
2025-01-13 16:11:41 +01:00
const config& cfg, client_type& client
2024-12-03 15:26:05 +01:00
) {
2025-01-13 16:11:41 +01:00
// Configure the Client.
// It is mandatory to call brokers() and async_run() to configure the Brokers to connect to and start the Client.
client.brokers(cfg.brokers, cfg.port) // Broker that we want to connect to.
.credentials(cfg.client_id) // Set the Client Identifier. (optional)
.async_run(boost::asio::detached); // Start the client.
2024-03-15 09:40:39 +01:00
2025-01-13 16:11:41 +01:00
// Before attempting to receive an Application Message from the Topic we just subscribed to,
// it is advisable to verify that the subscription succeeded.
// It is not recommended to call mqtt_client::async_receive if you do not have any
// subscription established as the corresponding handler will never be invoked.
if (!(co_await subscribe(client)))
co_return;
2025-01-13 16:11:41 +01:00
for (;;) {
// Receive an Appplication Message from the subscribed Topic(s).
auto&& [ec, topic, payload, publish_props] = co_await client.async_receive(use_nothrow_awaitable);
2025-01-13 16:11:41 +01:00
if (ec == boost::mqtt5::client::error::session_expired) {
// The Client has reconnected, and the prior session has expired.
// As a result, any previous subscriptions have been lost and must be reinstated.
if (co_await subscribe(client))
continue;
else
break;
} else if (ec)
break;
2024-03-15 09:40:39 +01:00
2025-01-13 16:11:41 +01:00
std::cout << "Received message from the Broker" << std::endl;
std::cout << "\t topic: " << topic << std::endl;
std::cout << "\t payload: " << payload << std::endl;
}
2025-01-13 16:11:41 +01:00
co_return;
}
2024-12-03 15:26:05 +01:00
int main(int argc, char** argv) {
2025-01-13 16:11:41 +01:00
config cfg;
2024-12-03 15:26:05 +01:00
2025-01-13 16:11:41 +01:00
if (argc == 4) {
cfg.brokers = argv[1];
cfg.port = uint16_t(std::stoi(argv[2]));
cfg.client_id = argv[3];
}
2024-12-03 15:26:05 +01:00
2025-01-13 16:11:41 +01:00
// Initialise execution context.
boost::asio::io_context ioc;
2024-03-15 09:40:39 +01:00
2025-01-13 16:11:41 +01:00
// Initialise the Client to connect to the Broker over TCP.
client_type client(ioc, {} /* tls_context */, boost::mqtt5::logger(boost::mqtt5::log_level::info));
2024-03-15 09:40:39 +01:00
2025-01-13 16:11:41 +01:00
// Set up signals to stop the program on demand.
boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
signals.async_wait([&client](boost::mqtt5::error_code /* ec */, int /* signal */) {
// After we are done with publishing all the messages, cancel the timer and the Client.
// Alternatively, use mqtt_client::async_disconnect.
client.cancel();
});
2025-01-13 16:11:41 +01:00
// Spawn the coroutine.
co_spawn(
ioc,
subscribe_and_receive(cfg, client),
[](std::exception_ptr e) {
if (e)
std::rethrow_exception(e);
}
);
2025-01-13 16:11:41 +01:00
// Start the execution.
ioc.run();
}
2024-02-13 10:22:39 +01:00
//]
2024-12-03 15:26:05 +01:00
#else
#include <iostream>
int main() {
2025-01-13 16:11:41 +01:00
std::cout << "This example requires C++20 standard to compile and run" << std::endl;
2024-12-03 15:26:05 +01:00
}
#endif