Update publisher and receiver examples

Summary:
related to T12804
publisher example will now showcase how to publish a message every 5 seconds
receiver example will now show how to subscribe, indefinitely receive messages and resubscribe if needed

Reviewers: ivica

Reviewed By: ivica

Subscribers: miljen, iljazovic

Differential Revision: https://repo.mireo.local/D28472
This commit is contained in:
Korina Šimičević
2024-03-15 09:40:39 +01:00
parent 4b65ffc194
commit 8dfbdf2d38
4 changed files with 129 additions and 61 deletions

View File

@@ -6,11 +6,11 @@ The following list contains all the examples that showcase how to use the __Clie
[variablelist [variablelist
[ [
[[link async_mqtt5.publisher publisher.cpp]] [[link async_mqtt5.publisher publisher.cpp]]
[Shows how to use the __Client__ as a publisher.] [Shows how to use the __Client__ as a publisher. The __Client__ publishes sensor readings every `5 seconds`.]
] ]
[ [
[[link async_mqtt5.receiver receiver.cpp]] [[link async_mqtt5.receiver receiver.cpp]]
[Shows how to use the __Client__ as a receiver.] [Shows how to use the __Client__ as a receiver. The __Client__ subscribes and indefinitely receives Application Messages from the Broker.]
] ]
[ [
[[link async_mqtt5.hello_world_over_tcp hello_world_over_tcp.cpp]] [[link async_mqtt5.hello_world_over_tcp hello_world_over_tcp.cpp]]

View File

@@ -25,8 +25,8 @@ This example illustrates the process of setting up the Client to connect to the
[endsect] [/hello_world_over_websocket_tls] [endsect] [/hello_world_over_websocket_tls]
[section:publisher The publisher] [section:publisher The publisher]
This example will show how to use __Client__ as a publisher. This example will show how to use __Client__ as a publisher that publishes sensor readings every `5` seconds.
The __Client__ will use TCP to connect to the Broker and __USE_AWAITABLE__ as the completion token. The __Client__ will use TCP to connect to the Broker and modified __USE_AWAITABLE__ as the completion token.
[import ../../../example/publisher.cpp] [import ../../../example/publisher.cpp]
[publisher] [publisher]
@@ -34,7 +34,8 @@ The __Client__ will use TCP to connect to the Broker and __USE_AWAITABLE__ as th
[section:receiver The receiver] [section:receiver The receiver]
This example will show how to use __Client__ as a receiver. This example will show how to use __Client__ as a receiver.
The __Client__ will use TCP to connect to the Broker and __USE_AWAITABLE__ as the completion token. The __Client__ subscribes and indefinitely receives Application Messages from the Broker.
The __Client__ will use TCP to connect to the Broker and modified __USE_AWAITABLE__ as the completion token.
[import ../../../example/receiver.cpp] [import ../../../example/receiver.cpp]
[receiver] [receiver]

View File

@@ -1,9 +1,13 @@
//[publisher //[publisher
#include <cstdlib>
#include <iostream> #include <iostream>
#include <boost/asio/as_tuple.hpp>
#include <boost/asio/co_spawn.hpp> #include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp> #include <boost/asio/detached.hpp>
#include <boost/asio/io_context.hpp> #include <boost/asio/io_context.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/use_awaitable.hpp> #include <boost/asio/use_awaitable.hpp>
#include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/tcp.hpp>
@@ -12,43 +16,80 @@
#ifdef BOOST_ASIO_HAS_CO_AWAIT #ifdef BOOST_ASIO_HAS_CO_AWAIT
namespace asio = boost::asio; // Modified completion token that will prevent co_await from throwing exceptions.
constexpr auto use_nothrow_awaitable = boost::asio::as_tuple(boost::asio::use_awaitable);
asio::awaitable<void> client_publisher(asio::io_context& ioc) { using client_type = async_mqtt5::mqtt_client<boost::asio::ip::tcp::socket>;
// Initialise the Client, establish connection to the Broker over TCP.
async_mqtt5::mqtt_client<asio::ip::tcp::socket> client(ioc);
int next_sensor_reading() {
srand(static_cast<unsigned int>(std::time(0)));
return rand() % 100;
}
boost::asio::awaitable<void> publish_sensor_readings(
client_type& client, boost::asio::steady_timer& timer
) {
// Configure the Client. // Configure the Client.
// It is mandatory to call brokers() and async_run() to configure the Brokers to connect to and start the Client. // It is mandatory to call brokers() and async_run() to configure the Brokers to connect to and start the Client.
client.brokers("mqtt.broker", 1883) // Broker that we want to connect to. 1883 is the default TCP port. client.brokers("<your-mqtt-broker>", 1883) // Broker that we want to connect to. 1883 is the default TCP port.
.async_run(asio::detached); // Start the client. .async_run(boost::asio::detached); // Start the client.
// Publish an Application Message with QoS 1. for (;;) {
auto [rc, props] = co_await client.async_publish<async_mqtt5::qos_e::at_least_once>( // Get the next sensor reading.
"test/mqtt-test", "my application message", auto reading = std::to_string(next_sensor_reading());
async_mqtt5::retain_e::yes, async_mqtt5::publish_props {}, asio::use_awaitable
// Publish the sensor reading with QoS 1.
auto&& [ec, rc, props] = co_await client.async_publish<async_mqtt5::qos_e::at_least_once>(
"<your-mqtt-topic>", reading,
async_mqtt5::retain_e::no, async_mqtt5::publish_props {}, use_nothrow_awaitable
); );
if (rc) // An error can occur as a result of:
std::cout << "MQTT protocol error occurred: " << rc.message() << std::endl; // a) wrong publish parameters
// b) mqtt_client::cancel is called while the Client is publishing the message
// resulting in cancellation.
if (ec) {
std::cout << "Publish error occurred: " << ec.message() << std::endl;
break;
}
// Publish some more messages... // Reason code is the reply from the server presenting the result of the publish operation.
std::cout << "Result of publish request: " << rc.message() << std::endl;
if (!rc)
std::cout << "Published sensor reading: " << reading << std::endl;
// After we are done with publishing all the messages, disconnect the Client. // Wait 5 seconds before publishing the next reading.
// Alternatively, you can also use mqtt_client::cancel. timer.expires_after(std::chrono::seconds(5));
// Regardless, you should ensure all the operations are completed before disconnecting the Client. auto&& [tec] = co_await timer.async_wait(use_nothrow_awaitable);
co_await client.async_disconnect(
async_mqtt5::disconnect_rc_e::normal_disconnection, async_mqtt5::disconnect_props {}, asio::use_awaitable // An error occurred if we cancelled the timer.
); if (tec)
break;
}
co_return; co_return;
} }
int main() { int main() {
// Initialise execution context. // Initialise execution context.
asio::io_context ioc; boost::asio::io_context ioc;
// Initialise the Client to connect to the Broker over TCP.
client_type client(ioc);
// Initialise the timer.
boost::asio::steady_timer timer(ioc);
// Set up signals to stop the program on demand.
boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
signals.async_wait([&client, &timer](async_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.
timer.cancel();
client.cancel();
});
// Spawn the coroutine. // Spawn the coroutine.
co_spawn(ioc.get_executor(), client_publisher(ioc), asio::detached); co_spawn(ioc.get_executor(), publish_sensor_readings(client, timer), boost::asio::detached);
// Start the execution. // Start the execution.
ioc.run(); ioc.run();

View File

@@ -1,9 +1,11 @@
//[receiver //[receiver
#include <iostream> #include <iostream>
#include <boost/asio/as_tuple.hpp>
#include <boost/asio/co_spawn.hpp> #include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp> #include <boost/asio/detached.hpp>
#include <boost/asio/io_context.hpp> #include <boost/asio/io_context.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/asio/use_awaitable.hpp> #include <boost/asio/use_awaitable.hpp>
#include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/tcp.hpp>
@@ -12,20 +14,15 @@
#ifdef BOOST_ASIO_HAS_CO_AWAIT #ifdef BOOST_ASIO_HAS_CO_AWAIT
namespace asio = boost::asio; // Modified completion token that will prevent co_await from throwing exceptions.
constexpr auto use_nothrow_awaitable = boost::asio::as_tuple(boost::asio::use_awaitable);
asio::awaitable<void> client_receiver(asio::io_context& ioc) { using client_type = async_mqtt5::mqtt_client<boost::asio::ip::tcp::socket>;
// Initialise the Client, establish connection to the Broker over TCP.
async_mqtt5::mqtt_client<asio::ip::tcp::socket> client(ioc);
// 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("mqtt.broker", 1883) // Broker that we want to connect to. 1883 is the default TCP port.
.async_run(asio::detached); // Start the client.
boost::asio::awaitable<bool> subscribe(client_type& client) {
// Configure the request to subscribe to a Topic. // Configure the request to subscribe to a Topic.
async_mqtt5::subscribe_topic sub_topic = async_mqtt5::subscribe_topic { async_mqtt5::subscribe_topic sub_topic = async_mqtt5::subscribe_topic{
"test/mqtt-test", "<your-mqtt-topic>",
async_mqtt5::subscribe_options { async_mqtt5::subscribe_options {
async_mqtt5::qos_e::exactly_once, // All messages will arrive at QoS 2. async_mqtt5::qos_e::exactly_once, // All messages will arrive at QoS 2.
async_mqtt5::no_local_e::no, // Forward message from Clients with same ID. async_mqtt5::no_local_e::no, // Forward message from Clients with same ID.
@@ -35,45 +32,74 @@ asio::awaitable<void> client_receiver(asio::io_context& ioc) {
}; };
// Subscribe to a single Topic. // Subscribe to a single Topic.
auto [sub_codes, sub_props] = co_await client.async_subscribe( auto&& [ec, sub_codes, sub_props] = co_await client.async_subscribe(
sub_topic, async_mqtt5::subscribe_props {}, asio::use_awaitable sub_topic, async_mqtt5::subscribe_props {}, use_nothrow_awaitable
); );
// Note: you can subscribe to multiple Topics in one mqtt_client::async_subscribe call. // Note: you can subscribe to multiple Topics in one mqtt_client::async_subscribe call.
// std::vector<async_mqtt5::reason_code> sub_codes contain the result of the subscribe action for every Topic. // 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;
co_return !ec && !sub_codes[0]; // True if the subscription was successfully established.
}
boost::asio::awaitable<void> subscribe_and_receive(client_type& client) {
// 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("<your-mqtt-broker>", 1883) // Broker that we want to connect to. 1883 is the default TCP port.
.async_run(boost::asio::detached); // Start the client.
// Before attempting to receive an Application Message from the Topic we just subscribed to, // 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 advisable to verify that the subscription succeeded.
// It is not recommended to call mqtt_client::async_receive if you do not have any // 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. // subscription established as the corresponding handler will never be invoked.
if (!sub_codes[0]) if (!(co_await subscribe(client)))
auto [topic, payload, publish_props] = co_await client.async_receive(asio::use_awaitable); co_return;
// Receive more messages...
// Unsubscribe from the Topic. for (;;) {
// Similar to mqtt_client::async_subscribe call, std::vector<async_mqtt5::reason_code> unsub_codes contain // Receive an Appplication Message from the subscribed Topic(s).
// the result of the unsubscribe action for every Topic. auto&& [ec, topic, payload, publish_props] = co_await client.async_receive(use_nothrow_awaitable);
auto [unsub_codes, unsub_props] = co_await client.async_unsubscribe(
"test/mqtt-test", async_mqtt5::unsubscribe_props {},
asio::use_awaitable
);
// Note: you can unsubscribe from multiple Topics in one mqtt_client::async_unsubscribe call.
// Disconnect the Client. if (ec == async_mqtt5::client::error::session_expired) {
co_await client.async_disconnect( // The Client has reconnected, and the prior session has expired.
async_mqtt5::disconnect_rc_e::disconnect_with_will_message, // As a result, any previous subscriptions have been lost and must be reinstated.
async_mqtt5::disconnect_props {}, if (co_await subscribe(client))
asio::use_awaitable continue;
); else
break;
} else if (ec)
break;
std::cout << "Received message from the Broker" << std::endl;
std::cout << "\t topic: " << topic << std::endl;
std::cout << "\t payload: " << payload << std::endl;
}
co_return; co_return;
} }
int main() { int main() {
// Initialise execution context. // Initialise execution context.
asio::io_context ioc; boost::asio::io_context ioc;
// Initialise the Client to connect to the Broker over TCP.
client_type client(ioc);
// Set up signals to stop the program on demand.
boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
signals.async_wait([&client](async_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();
});
// Spawn the coroutine. // Spawn the coroutine.
co_spawn(ioc, client_receiver(ioc), asio::detached); co_spawn(ioc, subscribe_and_receive(client), boost::asio::detached);
// Start the execution. // Start the execution.
ioc.run(); ioc.run();