data_publish.cpp 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. // data_publish.cpp
  2. //
  3. // This is a Paho MQTT C++ client, sample application.
  4. //
  5. // It's an example of how to collect and publish periodic data to MQTT, as
  6. // an MQTT publisher using the C++ asynchronous client interface.
  7. //
  8. // The sample demonstrates:
  9. // - Connecting to an MQTT server/broker
  10. // - Publishing messages
  11. // - Using a topic object to repeatedly publish to the same topic.
  12. // - Automatic reconnects
  13. // - Off-line buffering
  14. // - Default file-based persistence
  15. //
  16. // This just uses the steady clock to run a periodic loop. Each time
  17. // through, it generates a random number [0-100] as simulated data and
  18. // creates a text, CSV payload in the form:
  19. // <sample #>,<time stamp>,<data>
  20. //
  21. // Note that it uses the steady clock to pace the periodic timing, but then
  22. // reads the system_clock to generate the timestamp for local calendar time.
  23. //
  24. // The sample number is just a counting integer to help test the off-line
  25. // buffering to easily confirm that all the messages got across.
  26. //
  27. /*******************************************************************************
  28. * Copyright (c) 2013-2017 Frank Pagliughi <fpagliughi@mindspring.com>
  29. *
  30. * All rights reserved. This program and the accompanying materials
  31. * are made available under the terms of the Eclipse Public License v1.0
  32. * and Eclipse Distribution License v1.0 which accompany this distribution.
  33. *
  34. * The Eclipse Public License is available at
  35. * http://www.eclipse.org/legal/epl-v10.html
  36. * and the Eclipse Distribution License is available at
  37. * http://www.eclipse.org/org/documents/edl-v10.php.
  38. *
  39. * Contributors:
  40. * Frank Pagliughi - initial implementation and documentation
  41. *******************************************************************************/
  42. #include <random>
  43. #include <string>
  44. #include <thread>
  45. #include <chrono>
  46. #include <iostream>
  47. #include <cstdlib>
  48. #include <cstring>
  49. #include <ctime>
  50. #include "mqtt/async_client.h"
  51. using namespace std;
  52. using namespace std::chrono;
  53. const std::string DFLT_ADDRESS { "tcp://localhost:1883" };
  54. const string TOPIC { "data/rand" };
  55. const int QOS = 1;
  56. const auto PERIOD = seconds(5);
  57. const int MAX_BUFFERED_MSGS = 120; // 120 * 5sec => 10min off-line buffering
  58. const string PERSIST_DIR { "data-persist" };
  59. /////////////////////////////////////////////////////////////////////////////
  60. int main(int argc, char* argv[])
  61. {
  62. string address = (argc > 1) ? string(argv[1]) : DFLT_ADDRESS;
  63. mqtt::async_client cli(address, "", MAX_BUFFERED_MSGS, PERSIST_DIR);
  64. mqtt::connect_options connOpts;
  65. connOpts.set_keep_alive_interval(MAX_BUFFERED_MSGS * PERIOD);
  66. connOpts.set_clean_session(true);
  67. connOpts.set_automatic_reconnect(true);
  68. // Create a topic object. This is a conventience since we will
  69. // repeatedly publish messages with the same parameters.
  70. mqtt::topic top(cli, TOPIC, QOS, true);
  71. // Random number generator [0 - 100]
  72. random_device rnd;
  73. mt19937 gen(rnd());
  74. uniform_int_distribution<> dis(0, 100);
  75. try {
  76. // Connect to the MQTT broker
  77. cout << "Connecting to server '" << address << "'..." << flush;
  78. cli.connect(connOpts)->wait();
  79. cout << "OK\n" << endl;
  80. char tmbuf[32];
  81. unsigned nsample = 0;
  82. // The time at which to reads the next sample, starting now
  83. auto tm = steady_clock::now();
  84. while (true) {
  85. // Pace the samples to the desired rate
  86. this_thread::sleep_until(tm);
  87. // Get a timestamp and format as a string
  88. time_t t = system_clock::to_time_t(system_clock::now());
  89. strftime(tmbuf, sizeof(tmbuf), "%F %T", localtime(&t));
  90. // Simulate reading some data
  91. int x = dis(gen);
  92. // Create the payload as a text CSV string
  93. string payload = to_string(++nsample) + "," +
  94. tmbuf + "," + to_string(x);
  95. cout << payload << endl;
  96. // Publish to the topic
  97. top.publish(std::move(payload));
  98. tm += PERIOD;
  99. }
  100. // Disconnect
  101. cout << "\nDisconnecting..." << flush;
  102. cli.disconnect()->wait();
  103. cout << "OK" << endl;
  104. }
  105. catch (const mqtt::exception& exc) {
  106. cerr << exc.what() << endl;
  107. return 1;
  108. }
  109. return 0;
  110. }