mqtt_client_test.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * mqtt client
  3. *
  4. * @build make examples
  5. *
  6. * @test bin/mqtt_client_test 127.0.0.1 1883 topic payload
  7. *
  8. */
  9. #include "mqtt_client.h"
  10. using namespace hv;
  11. /*
  12. * @test MQTTS
  13. * #define TEST_SSL 1
  14. *
  15. * @build ./configure --with-mqtt --with-openssl && make clean && make
  16. *
  17. */
  18. #define TEST_SSL 0
  19. #define TEST_AUTH 0
  20. #define TEST_RECONNECT 1
  21. #define TEST_QOS 0
  22. int main(int argc, char** argv) {
  23. if (argc < 5) {
  24. printf("Usage: %s host port topic payload\n", argv[0]);
  25. return -10;
  26. }
  27. const char* host = argv[1];
  28. int port = atoi(argv[2]);
  29. const char* topic = argv[3];
  30. const char* payload = argv[4];
  31. MqttClient cli;
  32. cli.onConnect = [topic, payload](MqttClient* cli) {
  33. printf("connected!\n");
  34. #if TEST_QOS
  35. cli->subscribe(topic, 1, [topic, payload](MqttClient* cli) {
  36. printf("subscribe OK!\n");
  37. cli->publish(topic, payload, 1, 0, [](MqttClient* cli) {
  38. printf("publish OK!\n");
  39. });
  40. });
  41. #else
  42. cli->subscribe(topic);
  43. cli->publish(topic, payload);
  44. #endif
  45. };
  46. cli.onMessage = [](MqttClient* cli, mqtt_message_t* msg) {
  47. printf("topic: %.*s\n", msg->topic_len, msg->topic);
  48. printf("payload: %.*s\n", msg->payload_len, msg->payload);
  49. cli->disconnect();
  50. cli->stop();
  51. };
  52. cli.onClose = [](MqttClient* cli) {
  53. printf("disconnected!\n");
  54. };
  55. #if TEST_AUTH
  56. cli.setAuth("test", "123456");
  57. #endif
  58. #if TEST_RECONNECT
  59. reconn_setting_t reconn;
  60. reconn_setting_init(&reconn);
  61. reconn.min_delay = 1000;
  62. reconn.max_delay = 10000;
  63. reconn.delay_policy = 2;
  64. cli.setReconnect(&reconn);
  65. #endif
  66. cli.setPingInterval(10);
  67. int ssl = 0;
  68. #if TEST_SSL
  69. ssl = 1;
  70. #endif
  71. cli.connect(host, port, ssl);
  72. cli.run();
  73. return 0;
  74. }