forked from maze-runnar/mqtt-cpp-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.cpp
298 lines (211 loc) · 7.19 KB
/
client.cpp
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <map>
#include <cctype>
#include <thread>
#include <bits/stdc++.h>
#include <chrono>
#include "mqtt/client.h"
using namespace std;
const std::string SERVER_ADDRESS("tcp://broker.emqx.io:1883");
const std::string CLIENT_ID("i_am_true_alpha_1");
const std::string TOPIC("/[email protected]/sundaram");
const std::string PAYLOAD1 { "Hello World!" };
const char* PAYLOAD2 = "Hi there!";
const char* PAYLOAD3 = "Is anyone listening?";
const int QOS = 1;
class sample_mem_persistence : virtual public mqtt::iclient_persistence
{
// Whether the store is open
bool open_;
// Use an STL map to store shared persistence pointers
// against string keys.
std::map<std::string, std::string> store_;
public:
sample_mem_persistence() : open_(false) {}
// "Open" the store
void open(const std::string& clientId, const std::string& serverURI) override {
std::cout << "[Opening persistence store for '" << clientId
<< "' at '" << serverURI << "']" << std::endl;
open_ = true;
}
// Close the persistent store that was previously opened.
void close() override {
std::cout << "[Closing persistence store.]" << std::endl;
open_ = false;
}
// Clears persistence, so that it no longer contains any persisted data.
void clear() override {
std::cout << "[Clearing persistence store.]" << std::endl;
store_.clear();
}
// Returns whether or not data is persisted using the specified key.
bool contains_key(const std::string &key) override {
return store_.find(key) != store_.end();
}
// Returns the keys in this persistent data store.
const mqtt::string_collection& keys() const override {
static mqtt::string_collection ks;
ks.clear();
for (const auto& k : store_)
ks.push_back(k.first);
return ks;
}
// Puts the specified data into the persistent store.
void put(const std::string& key, const std::vector<mqtt::string_view>& bufs) override {
std::cout << "[Persisting data with key '"
<< key << "']" << std::endl;
std::string str;
for (const auto& b : bufs)
str += b.str();
store_[key] = std::move(str);
}
// Gets the specified data out of the persistent store.
mqtt::string_view get(const std::string& key) const override {
std::cout << "[Searching persistence for key '"
<< key << "']" << std::endl;
auto p = store_.find(key);
if (p == store_.end())
throw mqtt::persistence_exception();
std::cout << "[Found persistence data for key '"
<< key << "']" << std::endl;
return mqtt::string_view(p->second);
}
// Remove the data for the specified key.
void remove(const std::string &key) override {
std::cout << "[Persistence removing key '" << key << "']" << std::endl;
auto p = store_.find(key);
if (p == store_.end())
throw mqtt::persistence_exception();
store_.erase(p);
std::cout << "[Persistence key removed '" << key << "']" << std::endl;
}
};
/////////////////////////////////////////////////////////////////////////////
// Class to receive callbacks
class user_callback : public virtual mqtt::callback
{
void connection_lost(const std::string& cause) override {
std::cout << "\nConnection lost" << std::endl;
if (!cause.empty())
std::cout << "\tcause: " << cause << std::endl;
}
void delivery_complete(mqtt::delivery_token_ptr tok) override {
std::cout << "\n\t[Delivery complete for token: "
<< (tok ? tok->get_message_id() : -1) << "]" << std::endl;
}
public:
};
/////////////////////////////////////////////////////////////////////////////
/**
* Local callback & listener class for use with the client connection.
* This is primarily intended to receive messages, but it will also monitor
* the connection to the broker. If the connection is lost, it will attempt
* to restore the connection and re-subscribe to the topic.
*/
class callback : public virtual mqtt::callback
{
mqtt::client& cli_;
void connected(const std::string& cause) override {
std::cout << "\nConnected: " << cause << std::endl;
//cli_.subscribe(TOPIC, QOS);
std::cout << std::endl;
}
// Callback for when the connection is lost.
// This will initiate the attempt to manually reconnect.
void connection_lost(const std::string& cause) override {
std::cout << "\nConnection lost";
if (!cause.empty())
std::cout << ": " << cause << std::endl;
std::cout << std::endl;
}
// Callback for when a message arrives.
void message_arrived(mqtt::const_message_ptr msg) override { // msg -> get_topic()
std::cout << msg->get_payload_str() << std::endl;
}
void delivery_complete(mqtt::delivery_token_ptr token) override {}
public:
callback(mqtt::client& cli) : cli_(cli) {}
};
/////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
/// create publishing connection
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(false);
connOpts.set_automatic_reconnect(true);
mqtt::client cli(SERVER_ADDRESS, CLIENT_ID);
callback cb(cli);
cli.set_callback(cb);
sample_mem_persistence persist;
mqtt::client client(SERVER_ADDRESS, "I_an_alpha_now"); /// will add &persist later
user_callback cb1;
client.set_callback(cb1);
mqtt::connect_options connOpts1;
connOpts1.set_keep_alive_interval(20);
connOpts1.set_clean_session(true);
// Start the connection.
try {
std::cout << "Connecting to the MQTT server..." << std::flush;
cli.connect(connOpts);
cli.subscribe(TOPIC, QOS);
std::cout << "OK" << std::endl;
}
catch (const mqtt::exception& exc) {
std::cerr << "\nERROR: Unable to connect to MQTT server: '"
<< SERVER_ADDRESS << "'" << std::endl;
return 1;
}
// Just block till user tells us to quit.
// // Disconnect
// try {
// std::cout << "\nDisconnecting from the MQTT server..." << std::flush;
// cli.disconnect();
// std::cout << "OK" << std::endl;
// }
// catch (const mqtt::exception& exc) {
// std::cerr << exc.what() << std::endl;
// return 1;
// }
try {
std::cout << "\nConnecting..." << std::endl;
client.connect(connOpts1);
std::cout << "...OK" << std::endl;
// First use a message pointer.
cout << "Enter msg: " << endl;
string msg;
getline(cin, msg);
std::cout << "\nSending message..." << std::endl;
auto pubmsg = mqtt::make_message(TOPIC, msg);
pubmsg->set_qos(QOS);
client.publish(pubmsg);
std::cout << "...OK" << std::endl;
/* other methods to publish message .....
// Now try with itemized publish.
std::cout << "\nSending next message..." << std::endl;
client.publish(TOPIC, PAYLOAD2, strlen(PAYLOAD2)+1);
std::cout << "...OK" << std::endl;
// Now try with a listener, no token, and non-heap message
std::cout << "\nSending final message..." << std::endl;
client.publish(mqtt::message(TOPIC, PAYLOAD3, QOS, false));
std::cout << "OK" << std::endl;
*/
// // Disconnect
// std::cout << "\nDisconnecting..." << std::endl;
// client.disconnect();
// std::cout << "...OK" << std::endl;
}
catch (const mqtt::persistence_exception& exc) {
std::cerr << "Persistence Error: " << exc.what() << " ["
<< exc.get_reason_code() << "]" << std::endl;
return 1;
}
catch (const mqtt::exception& exc) {
std::cerr << exc.what() << std::endl;
return 1;
}
return 0;
}