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