main.cpp
2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#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);
}
}