system_mqtt.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * @Author:
  3. * @Github:
  4. * @Date:
  5. * @LastEditTime :
  6. * @Description:
  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. #include <sys/types.h>
  17. #include <sys/ipc.h>
  18. #include <sys/msg.h>
  19. int msgQueueID;
  20. static void topic1_handler(void* client, message_data_t* msg);
  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, "topic1", &msg);
  35. sleep(4);
  36. }
  37. }
  38. /*
  39. * mqtt初始化IP:36.134.213.14 1883
  40. * */
  41. int mqtt_init_connect(mqtt_client_t *client,char *client_id,char *user_name,char *password,char *ip,char *port)
  42. {
  43. mqtt_set_port(client, port);
  44. mqtt_set_host(client, ip);
  45. mqtt_set_client_id(client, client_id);
  46. mqtt_set_user_name(client, user_name);
  47. mqtt_set_password(client, password);
  48. mqtt_set_clean_session(client, 1);
  49. return mqtt_connect(client);
  50. }
  51. //创建mqtt任务
  52. void create_mqtt_task()
  53. {
  54. mqtt_client_t *client = NULL;
  55. pthread_t thread1;
  56. client = mqtt_lease();
  57. mqtt_log_init();
  58. if(NULL==client)
  59. {
  60. MQTT_LOG_E("client malloc memory error");
  61. exit(1);
  62. }
  63. int rc=mqtt_init_connect(client,"hisi_test",NULL,NULL,"36.134.23.11","1883");
  64. if(rc!=0)
  65. {
  66. MQTT_LOG_E("mqtt connect error please check config");
  67. exit(rc);
  68. }
  69. mqtt_subscribe(client, "rec_mqtt", QOS0, topic1_handler);
  70. rc = pthread_create(&thread1, NULL, mqtt_publish_thread, client);
  71. if(rc != 0) {
  72. MQTT_LOG_E("create mqtt publish thread fail");
  73. exit(rc);
  74. }
  75. }
  76. /*
  77. * 所订阅消息的处理函数
  78. */
  79. static void topic1_handler(void* client, message_data_t* msg)
  80. {
  81. (void) client;
  82. MQTT_LOG_I("-----------------------------------------------------------------------------------");
  83. MQTT_LOG_I("%s:%d %s()...\ntopic: %s\nmessage:%s", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char*)msg->message->payload);
  84. MQTT_LOG_I("-----------------------------------------------------------------------------------");
  85. }