-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt_sub_example.cpp
executable file
·87 lines (73 loc) · 2.46 KB
/
mqtt_sub_example.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
// async_consume.cpp
//
// This is a Paho MQTT C++ client, sample application.
//
// This application is an MQTT consumer/subscriber using the C++
// asynchronous client interface, employing the to receive messages
// and status updates.
//
// The sample demonstrates:
// - Connecting to an MQTT server/broker.
// - Subscribing to a topic
// - Receiving messages through the synchronous queuing API
//
/*******************************************************************************
* Copyright (c) 2013-2017 Frank Pagliughi <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Frank Pagliughi - initial implementation and documentation
*******************************************************************************/
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cctype>
#include <thread>
#include <chrono>
#include "mqtt/async_client.h"
using namespace std;
const string SERVER_ADDRESS { "tcp://localhost:1883" };
const string CLIENT_ID { "async_consume" };
const string TOPIC { "adc/1" };
const int QOS = 1;
/////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
mqtt::async_client cli(SERVER_ADDRESS, CLIENT_ID);
try {
cout << "Connecting to the MQTT server..." << flush;
cli.connect(connOpts)->wait();
cli.start_consuming();
cli.subscribe(TOPIC, QOS)->wait();
cout << "OK" << endl;
// Consume messages
while (true) {
auto msg = cli.consume_message();
if (!msg) break;
cout << msg->get_topic() << ": " << msg->to_string() << endl;
}
// Disconnect
cout << "\nShutting down and disconnecting from the MQTT server..." << flush;
cli.unsubscribe(TOPIC)->wait();
cli.stop_consuming();
cli.disconnect()->wait();
cout << "OK" << endl;
}
catch (const mqtt::exception& exc) {
cerr << exc.what() << endl;
return 1;
}
return 0;
}