demo.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <rtthread.h>
  2. #include <wlan_mgnt.h>
  3. #define DBG_TAG "MQTT"
  4. #define DBG_LVL DBG_LOG
  5. #include "mqtt_api.h"
  6. void mqtt_client_start(void)
  7. {
  8. rt_wlan_unregister_event_handler(RT_WLAN_EVT_READY);
  9. rt_thread_t tid = rt_thread_create("mqtt", mqttClientTask,
  10. RT_NULL, 4096, 10, 20);
  11. if (tid != RT_NULL)
  12. {
  13. rt_thread_startup(tid);
  14. MQTT_PRINT("MQTT client thread started\n");
  15. }
  16. else
  17. {
  18. MQTT_PRINT("Failed to create MQTT client thread\n");
  19. }
  20. }
  21. static int mqtt_pub(int argc, char **argv)
  22. {
  23. MQTTStatus_t status;
  24. MQTTPublishInfo_t publishInfo;
  25. if (argc != 2)
  26. {
  27. rt_kprintf("Usage: mqtt_pub <message>\n");
  28. return -RT_ERROR;
  29. }
  30. publishInfo.qos = MQTTQoS0;
  31. publishInfo.pTopicName = MQTT_TOPIC_PUB;
  32. publishInfo.topicNameLength = strlen(MQTT_TOPIC_PUB);
  33. publishInfo.pPayload = argv[1];
  34. publishInfo.payloadLength = strlen(argv[1]);
  35. status = mqttPublish(&publishInfo);
  36. if (status != MQTTSuccess)
  37. {
  38. rt_kprintf("MQTT publish failed: %d\n", status);
  39. return -RT_ERROR;
  40. }
  41. rt_kprintf("Published message: %s to topic: %s\n", argv[1], MQTT_TOPIC_PUB);
  42. return RT_EOK;
  43. }
  44. #ifdef RT_USING_FINSH
  45. MSH_CMD_EXPORT_ALIAS(mqtt_pub, mqtt_pub, Send MQTT message);
  46. #endif
  47. static int mqtt_sub(int argc, char **argv)
  48. {
  49. MQTTStatus_t status;
  50. MQTTSubscribeInfo_t subscribeInfo;
  51. if (argc != 2)
  52. {
  53. rt_kprintf("Usage: mqtt_sub <topic>\n");
  54. return -RT_ERROR;
  55. }
  56. subscribeInfo.qos = MQTTQoS0;
  57. subscribeInfo.pTopicFilter = argv[1];
  58. subscribeInfo.topicFilterLength = strlen(argv[1]);
  59. status = mqttSubscribe(&subscribeInfo);
  60. if (status != MQTTSuccess)
  61. {
  62. rt_kprintf("MQTT subscribe failed: %d\n", status);
  63. return -RT_ERROR;
  64. }
  65. rt_kprintf("Subscribed to topic: %s\n", argv[1]);
  66. return RT_EOK;
  67. }
  68. #ifdef RT_USING_FINSH
  69. MSH_CMD_EXPORT_ALIAS(mqtt_sub, mqtt_sub, Subscribe MQTT message);
  70. #endif