test.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * @Author: jiejie
  3. * @Github: https://github.com/jiejieTop
  4. * @Date: 2019-12-11 21:53:07
  5. * @LastEditTime : 2022-06-12 17:48:06
  6. * @Description: the code belongs to jiejie, please keep the author information and source code according to the license.
  7. */
  8. #include <stdio.h>
  9. #include <unistd.h>
  10. #include <fcntl.h>
  11. #include <stdlib.h>
  12. #include <pthread.h>
  13. #include "mqtt_config.h"
  14. #include "mqtt_log.h"
  15. #include "mqttclient.h"
  16. // #define TEST_USEING_TLS
  17. // extern const char *test_ca_get();
  18. static void topic1_handler(void* client, message_data_t* msg)
  19. {
  20. (void) client;
  21. MQTT_LOG_I("-----------------------------------------------------------------------------------");
  22. MQTT_LOG_I("%s:%d %s()...\ntopic: %s\nmessage:%s", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char*)msg->message->payload);
  23. MQTT_LOG_I("-----------------------------------------------------------------------------------");
  24. }
  25. void *mqtt_publish_thread(void *arg)
  26. {
  27. mqtt_client_t *client = (mqtt_client_t *)arg;
  28. char buf[100] = { 0 };
  29. mqtt_message_t msg;
  30. memset(&msg, 0, sizeof(msg));
  31. sprintf(buf, "welcome to mqttclient, this is a publish test...");
  32. sleep(2);
  33. mqtt_list_subscribe_topic(client);
  34. msg.payload = (void *) buf;
  35. while(1) {
  36. sprintf(buf, "welcome to mqttclient, this is a publish test, a rand number: %d ...", random_number());
  37. msg.qos = 0;
  38. mqtt_publish(client, "topic1", &msg);
  39. msg.qos = 1;
  40. mqtt_publish(client, "topic2", &msg);
  41. msg.qos = 2;
  42. mqtt_publish(client, "topic3", &msg);
  43. sleep(4);
  44. }
  45. }
  46. int main(void)
  47. {
  48. int res;
  49. pthread_t thread1;
  50. mqtt_client_t *client = NULL;
  51. printf("\nwelcome to mqttclient test...\n");
  52. mqtt_log_init();
  53. client = mqtt_lease();
  54. #ifdef TEST_USEING_TLS
  55. mqtt_set_port(client, "8883");
  56. mqtt_set_ca(client, (char*)test_ca_get());
  57. #else
  58. mqtt_set_port(client, "1883");
  59. #endif
  60. mqtt_set_host(client, "120.25.213.14");
  61. mqtt_set_client_id(client, random_string(10));
  62. mqtt_set_user_name(client, random_string(10));
  63. mqtt_set_password(client, random_string(10));
  64. mqtt_set_clean_session(client, 1);
  65. mqtt_connect(client);
  66. mqtt_subscribe(client, "topic1", QOS0, topic1_handler);
  67. mqtt_subscribe(client, "topic2", QOS1, NULL);
  68. mqtt_subscribe(client, "topic3", QOS2, NULL);
  69. res = pthread_create(&thread1, NULL, mqtt_publish_thread, client);
  70. if(res != 0) {
  71. MQTT_LOG_E("create mqtt publish thread fail");
  72. exit(res);
  73. }
  74. while (1) {
  75. sleep(100);
  76. }
  77. }