main.cpp 2.18 KB
#include <iostream>
#include <string>
#include <vector>

#include "mqttclient.h"

using namespace osdev::components::mqtt;

std::vector<std::string> vecTopics =
{
    "test/publisher/TestPublisher_0",
    "test/publisher/TestPublisher_1",
    "test/publisher/TestPublisher_2",
    "test/publisher/TestPublisher_3",
    "test/publisher/TestPublisher_4",
    "test/publisher/TestPublisher_5",
    "test/publisher/TestPublisher_6",
    "test/publisher/TestPublisher_7",
    "test/publisher/TestPublisher_8",
    "test/publisher/TestPublisher_9",
};

MqttClient oClient("SubscriptionTest");

enum TIME_RES
{
    T_MICRO,
    T_MILLI,
    T_SECONDS
};

std::uint64_t getEpochUSecs()
{
    auto tsUSec = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::system_clock::now());
    return static_cast<std::uint64_t>(tsUSec.time_since_epoch().count());
}

void sleepcp( int number, TIME_RES resolution = T_MILLI )    // Cross-platform sleep function
{
    int factor = 0; // Should not happen..

    switch( resolution )
    {
        case T_MICRO:
            factor = 1;
            break;

        case T_MILLI:
            factor = 1000;
            break;

        case T_SECONDS:
            factor = 1000000;
            break;
    }

    usleep( number * factor );
}

void Subscribe()
{
    for( const auto &message_topic : vecTopics)
    {
        std::cout << "Subscribing to : " << message_topic << std::endl;
        oClient.subscribe(message_topic, 1, [](const osdev::components::mqtt::MqttMessage &message)
        {
            std::cout << "Received Topic : [" << message.topic() << "] Payload : " << message.payload() << std::endl;
        });
    }
}

void Unsubscribe()
{
    for( const auto &message_topic : vecTopics)
    {
        std::cout << "Unsubscribing from : " << message_topic << std::endl;
        oClient.unsubscribe(message_topic, 1);
    }
}

int main(int argc, char* argv[])
{
    (void)argc;
    (void)argv;

    oClient.connect("localhost", 1883, Credentials());

    // First create all subscriptions
    Subscribe();
    sleepcp(1, T_SECONDS);

    while(1)
    {
        Unsubscribe();
        sleepcp(1, T_SECONDS);
        Subscribe();
        sleepcp(10, T_SECONDS);
    }

}