test.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * @Author: jiejie
  3. * @Github: https://github.com/jiejieTop
  4. * @Date: 2019-12-11 21:53:07
  5. * @LastEditTime: 2020-06-08 20:40:47
  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 "mqttclient.h"
  14. static void topic1_handler(void* client, message_data_t* msg)
  15. {
  16. (void) client;
  17. MQTT_LOG_I("-----------------------------------------------------------------------------------");
  18. MQTT_LOG_I("%s:%d %s()...\ntopic: %s\nmessage:%s", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char*)msg->message->payload);
  19. MQTT_LOG_I("-----------------------------------------------------------------------------------");
  20. }
  21. void *mqtt_publish_thread(void *arg)
  22. {
  23. mqtt_client_t *client = (mqtt_client_t *)arg;
  24. char buf[100] = { 0 };
  25. mqtt_message_t msg;
  26. memset(&msg, 0, sizeof(msg));
  27. sprintf(buf, "welcome to mqttclient, this is a publish test...");
  28. sleep(2);
  29. mqtt_list_subscribe_topic(client);
  30. msg.payload = (void *) buf;
  31. msg.qos = 0;
  32. while(1) {
  33. sprintf(buf, "welcome to mqttclient, this is a publish test, a rand number: %d ...", random_number());
  34. mqtt_publish(client, "/a1w7XupONEX/test1/user/topic1", &msg);
  35. sleep(4);
  36. }
  37. }
  38. int main(void)
  39. {
  40. int res;
  41. pthread_t thread1;
  42. mqtt_client_t *client = NULL;
  43. printf("\nwelcome to mqttclient test...\n");
  44. mqtt_log_init();
  45. client = mqtt_lease();
  46. mqtt_set_port(client, "1883");
  47. mqtt_set_host(client, "a1w7XupONEX.iot-as-mqtt.cn-shanghai.aliyuncs.com");
  48. mqtt_set_client_id(client, "123456|securemode=3,signmethod=hmacsha1|");
  49. mqtt_set_user_name(client, "test1&a1w7XupONEX");
  50. mqtt_set_password(client, "A9EFF34CCA05EABAE560373CBED3E43AC88956CF");
  51. mqtt_set_clean_session(client, 1);
  52. mqtt_connect(client);
  53. mqtt_subscribe(client, "/a1w7XupONEX/test1/user/topic1", QOS0, topic1_handler);
  54. res = pthread_create(&thread1, NULL, mqtt_publish_thread, client);
  55. if(res != 0) {
  56. MQTT_LOG_E("create mqtt publish thread fail");
  57. exit(res);
  58. }
  59. while (1) {
  60. sleep(100);
  61. }
  62. }