test.c 2.1 KB

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