Skip to content
Takatoshi Kondo edited this page Aug 5, 2018 · 6 revisions

Offline Publish

When you set Clean Session = false, you can publish both before the first connection and after disconnection.

Here is the code example:

#include <iostream>
#include <mqtt_client_cpp.hpp>

int main() {
    boost::asio::io_context ioc;
    auto c = mqtt::make_client(ioc, "test.mosquitto.org", 1883);

    c->set_client_id("cid1");
    c->set_clean_session(false);

    c->set_connack_handler(
        [&c](bool sp, std::uint8_t connack_return_code) {
            std::cout << "Connack handler called" << std::endl;
            std::cout << "Session Present: " << std::boolalpha << sp << std::endl;
            std::cout << "Connack Return Code: "
                      << mqtt::connect_return_code_to_str(connack_return_code) << std::endl;
            if (connack_return_code == mqtt::connect_return_code::accepted) {
                c->subscribe("mqtt_cpp_topic1", mqtt::qos::at_most_once);
            }
            return true;
        }
    );
    c->set_close_handler(
        [] {
            std::cout << "closed" << std::endl;
        }
    );
    c->set_puback_handler(
        [](std::uint16_t packet_id) {
            std::cout << "puback" << std::endl;
            return true;
        }
    );

    c->set_publish_handler(
        [&c]
        (std::uint8_t header,
         boost::optional<std::uint16_t> packet_id,
         std::string topic_name,
         std::string contents) {
            std::cout << "publish received. "
                      << "dup: " << std::boolalpha << mqtt::publish::is_dup(header)
                      << " pos: " << mqtt::qos::to_str(mqtt::publish::get_qos(header))
                      << " retain: " << mqtt::publish::is_retain(header) << std::endl;
            if (packet_id)
                std::cout << "packet_id: " << *packet_id << std::endl;
            std::cout << "topic_name: " << topic_name << std::endl;
            std::cout << "contents: " << contents << std::endl;
            c->disconnect();
            return true;
        }
    );

    c->publish_at_least_once("mqtt_cpp_topic1", "test1");

    c->connect();

    ioc.run();
}