| 1 | // SPDX-License-Identifier: GPL-3.0-only |
| 2 | |
| 3 | #include <unistd.h> |
| 4 | #include <stdio.h> |
| 5 | #include <string.h> |
| 6 | #include <stdlib.h> |
| 7 | |
| 8 | #include "mqtt_wss_client.h" |
| 9 | |
| 10 | int test_exit = 0; |
| 11 | int port = 0; |
| 12 | |
| 13 | void mqtt_wss_log_cb(mqtt_wss_log_type_t log_type, const char* str) |
| 14 | { |
| 15 | (void)log_type; |
| 16 | puts(str); |
| 17 | } |
| 18 | |
| 19 | #define TEST_MSGLEN_MAX 512 |
| 20 | void msg_callback(const char *topic, const void *msg, size_t msglen, int qos) |
| 21 | { |
| 22 | char cmsg[TEST_MSGLEN_MAX]; |
| 23 | size_t len = (msglen < TEST_MSGLEN_MAX - 1) ? msglen : (TEST_MSGLEN_MAX - 1); |
| 24 | memcpy(cmsg, |
| 25 | msg, |
| 26 | len); |
| 27 | cmsg[len] = 0; |
| 28 | |
| 29 | if (!strcmp(cmsg, "shutdown")) |
| 30 | test_exit = 1; |
| 31 | |
| 32 | printf("Got Message From Broker Topic \"%s\" QOS %d MSG: \"%s\"\n", topic, qos, cmsg); |
| 33 | } |
| 34 | |
| 35 | #define TESTMSG "Hello World!" |
| 36 | int client_handle(mqtt_wss_client client) |
| 37 | { |
| 38 | struct mqtt_connect_params params = { |
| 39 | .clientid = "test", |
| 40 | .username = "anon", |
| 41 | .password = "anon", |
| 42 | .keep_alive = 10 |
| 43 | }; |
| 44 | |
| 45 | /* struct mqtt_wss_proxy proxy = { |
| 46 | .host = "127.0.0.1", |
| 47 | .port = 3128, |
| 48 | .type = MQTT_WSS_PROXY_HTTP |
| 49 | };*/ |
| 50 | |
| 51 | while (mqtt_wss_connect(client, "127.0.0.1", port, ¶ms, MQTT_WSS_SSL_ALLOW_SELF_SIGNED, NULL /*&proxy*/)) { |
| 52 | printf("Connect failed\n"); |
| 53 | sleep(1); |
| 54 | printf("Attempting Reconnect\n"); |
| 55 | } |
| 56 | printf("Connection succeeded\n"); |
| 57 | |
| 58 | mqtt_wss_subscribe(client, "test", 1); |
| 59 | |
| 60 | while (!test_exit) { |
| 61 | if(mqtt_wss_service(client, -1) < 0) |
| 62 | return 1; |
| 63 | } |
| 64 | return 0; |
| 65 | } |
| 66 | |
| 67 | int main(int argc, char **argv) |
| 68 | { |
| 69 | if (argc >= 2) |
| 70 | port = atoi(argv[1]); |
| 71 | if (!port) |
| 72 | port = 9002; |
| 73 | printf("Using port %d\n", port); |
| 74 | |
| 75 | mqtt_wss_client client = mqtt_wss_new("main", mqtt_wss_log_cb, msg_callback, NULL); |
| 76 | if (!client) { |
| 77 | printf("Couldn't initialize mqtt_wss\n"); |
| 78 | return 1; |
| 79 | } |
| 80 | while (!test_exit) { |
| 81 | printf("client_handle = %d\n", client_handle(client)); |
| 82 | } |
| 83 | if (test_exit) { |
| 84 | mqtt_wss_disconnect(client, 2000); |
| 85 | } |
| 86 | |
| 87 | mqtt_wss_destroy(client); |
| 88 | return 0; |
| 89 | } |