mqtt-example.c 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. * Copyright (C) 2015-2018 Alibaba Group Holding Limited
  3. *
  4. * Again edit by rt-thread group
  5. * Change Logs:
  6. * Date Author Notes
  7. * 2019-07-21 MurphyZhao first edit
  8. */
  9. #include "rtthread.h"
  10. #include "dev_sign_api.h"
  11. #include "mqtt_api.h"
  12. char DEMO_PRODUCT_KEY[IOTX_PRODUCT_KEY_LEN + 1] = {0};
  13. char DEMO_DEVICE_NAME[IOTX_DEVICE_NAME_LEN + 1] = {0};
  14. char DEMO_DEVICE_SECRET[IOTX_DEVICE_SECRET_LEN + 1] = {0};
  15. void *HAL_Malloc(uint32_t size);
  16. void HAL_Free(void *ptr);
  17. void HAL_Printf(const char *fmt, ...);
  18. int HAL_GetProductKey(char product_key[IOTX_PRODUCT_KEY_LEN + 1]);
  19. int HAL_GetDeviceName(char device_name[IOTX_DEVICE_NAME_LEN + 1]);
  20. int HAL_GetDeviceSecret(char device_secret[IOTX_DEVICE_SECRET_LEN]);
  21. uint64_t HAL_UptimeMs(void);
  22. int HAL_Snprintf(char *str, const int len, const char *fmt, ...);
  23. #define EXAMPLE_TRACE(fmt, ...) \
  24. do { \
  25. HAL_Printf("%s|%03d :: ", __func__, __LINE__); \
  26. HAL_Printf(fmt, ##__VA_ARGS__); \
  27. HAL_Printf("%s", "\r\n"); \
  28. } while(0)
  29. static void example_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
  30. {
  31. iotx_mqtt_topic_info_t *topic_info = (iotx_mqtt_topic_info_pt) msg->msg;
  32. switch (msg->event_type) {
  33. case IOTX_MQTT_EVENT_PUBLISH_RECEIVED:
  34. /* print topic name and topic message */
  35. EXAMPLE_TRACE("Message Arrived:");
  36. EXAMPLE_TRACE("Topic : %.*s", topic_info->topic_len, topic_info->ptopic);
  37. EXAMPLE_TRACE("Payload: %.*s", topic_info->payload_len, topic_info->payload);
  38. EXAMPLE_TRACE("\n");
  39. break;
  40. default:
  41. break;
  42. }
  43. }
  44. static int example_subscribe(void *handle)
  45. {
  46. int res = 0;
  47. const char *fmt = "/%s/%s/user/get";
  48. char *topic = NULL;
  49. int topic_len = 0;
  50. topic_len = strlen(fmt) + strlen(DEMO_PRODUCT_KEY) + strlen(DEMO_DEVICE_NAME) + 1;
  51. topic = HAL_Malloc(topic_len);
  52. if (topic == NULL) {
  53. EXAMPLE_TRACE("memory not enough");
  54. return -1;
  55. }
  56. memset(topic, 0, topic_len);
  57. HAL_Snprintf(topic, topic_len, fmt, DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME);
  58. res = IOT_MQTT_Subscribe(handle, topic, IOTX_MQTT_QOS0, example_message_arrive, NULL);
  59. if (res < 0) {
  60. EXAMPLE_TRACE("subscribe failed");
  61. HAL_Free(topic);
  62. return -1;
  63. }
  64. HAL_Free(topic);
  65. return 0;
  66. }
  67. static int example_publish(void *handle)
  68. {
  69. int res = 0;
  70. const char *fmt = "/%s/%s/user/get";
  71. char *topic = NULL;
  72. int topic_len = 0;
  73. char *payload = "{\"message\":\"hello!\"}";
  74. topic_len = strlen(fmt) + strlen(DEMO_PRODUCT_KEY) + strlen(DEMO_DEVICE_NAME) + 1;
  75. topic = HAL_Malloc(topic_len);
  76. if (topic == NULL) {
  77. EXAMPLE_TRACE("memory not enough");
  78. return -1;
  79. }
  80. memset(topic, 0, topic_len);
  81. HAL_Snprintf(topic, topic_len, fmt, DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME);
  82. res = IOT_MQTT_Publish_Simple(0, topic, IOTX_MQTT_QOS0, payload, strlen(payload));
  83. if (res < 0) {
  84. EXAMPLE_TRACE("publish failed, res = %d", res);
  85. HAL_Free(topic);
  86. return -1;
  87. }
  88. HAL_Free(topic);
  89. return 0;
  90. }
  91. static void example_event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
  92. {
  93. EXAMPLE_TRACE("msg->event_type : %d", msg->event_type);
  94. }
  95. /*
  96. * NOTE: About demo topic of /${productKey}/${deviceName}/user/get
  97. *
  98. * The demo device has been configured in IoT console (https://iot.console.aliyun.com)
  99. * so that its /${productKey}/${deviceName}/user/get can both be subscribed and published
  100. *
  101. * We design this to completely demonstrate publish & subscribe process, in this way
  102. * MQTT client can receive original packet sent by itself
  103. *
  104. * For new devices created by yourself, pub/sub privilege also requires being granted
  105. * to its /${productKey}/${deviceName}/user/get for successfully running whole example
  106. */
  107. static int mqtt_example_main(int argc, char *argv[])
  108. {
  109. void *pclient = NULL;
  110. int res = 0;
  111. int loop_cnt = 0;
  112. iotx_mqtt_param_t mqtt_params;
  113. HAL_GetProductKey(DEMO_PRODUCT_KEY);
  114. HAL_GetDeviceName(DEMO_DEVICE_NAME);
  115. HAL_GetDeviceSecret(DEMO_DEVICE_SECRET);
  116. EXAMPLE_TRACE("mqtt example");
  117. /* Initialize MQTT parameter */
  118. /*
  119. * Note:
  120. *
  121. * If you did NOT set value for members of mqtt_params, SDK will use their default values
  122. * If you wish to customize some parameter, just un-comment value assigning expressions below
  123. *
  124. **/
  125. memset(&mqtt_params, 0x0, sizeof(mqtt_params));
  126. /**
  127. *
  128. * MQTT connect hostname string
  129. *
  130. * MQTT server's hostname can be customized here
  131. *
  132. * default value is ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com
  133. */
  134. /* mqtt_params.host = "something.iot-as-mqtt.cn-shanghai.aliyuncs.com"; */
  135. /**
  136. *
  137. * MQTT connect port number
  138. *
  139. * TCP/TLS port which can be 443 or 1883 or 80 or etc, you can customize it here
  140. *
  141. * default value is 1883 in TCP case, and 443 in TLS case
  142. */
  143. /* mqtt_params.port = 1883; */
  144. /**
  145. *
  146. * MQTT request timeout interval
  147. *
  148. * MQTT message request timeout for waiting ACK in MQTT Protocol
  149. *
  150. * default value is 2000ms.
  151. */
  152. /* mqtt_params.request_timeout_ms = 2000; */
  153. /**
  154. *
  155. * MQTT clean session flag
  156. *
  157. * If CleanSession is set to 0, the Server MUST resume communications with the Client based on state from
  158. * the current Session (as identified by the Client identifier).
  159. *
  160. * If CleanSession is set to 1, the Client and Server MUST discard any previous Session and Start a new one.
  161. *
  162. * default value is 0.
  163. */
  164. /* mqtt_params.clean_session = 0; */
  165. /**
  166. *
  167. * MQTT keepAlive interval
  168. *
  169. * KeepAlive is the maximum time interval that is permitted to elapse between the point at which
  170. * the Client finishes transmitting one Control Packet and the point it starts sending the next.
  171. *
  172. * default value is 60000.
  173. */
  174. /* mqtt_params.keepalive_interval_ms = 60000; */
  175. /**
  176. *
  177. * MQTT write buffer size
  178. *
  179. * Write buffer is allocated to place upstream MQTT messages, MQTT client will be limitted
  180. * to send packet no longer than this to Cloud
  181. *
  182. * default value is 1024.
  183. *
  184. */
  185. /* mqtt_params.write_buf_size = 1024; */
  186. /**
  187. *
  188. * MQTT read buffer size
  189. *
  190. * Write buffer is allocated to place downstream MQTT messages, MQTT client will be limitted
  191. * to recv packet no longer than this from Cloud
  192. *
  193. * default value is 1024.
  194. *
  195. */
  196. /* mqtt_params.read_buf_size = 1024; */
  197. /**
  198. *
  199. * MQTT event callback function
  200. *
  201. * Event callback function will be called by SDK when it want to notify user what is happening inside itself
  202. *
  203. * default value is NULL, which means PUB/SUB event won't be exposed.
  204. *
  205. */
  206. mqtt_params.handle_event.h_fp = example_event_handle;
  207. pclient = IOT_MQTT_Construct(&mqtt_params);
  208. if (NULL == pclient) {
  209. EXAMPLE_TRACE("MQTT construct failed");
  210. return -1;
  211. }
  212. res = example_subscribe(pclient);
  213. if (res < 0) {
  214. IOT_MQTT_Destroy(&pclient);
  215. return -1;
  216. }
  217. while (1) {
  218. if (0 == loop_cnt % 20) {
  219. example_publish(pclient);
  220. }
  221. IOT_MQTT_Yield(pclient, 200);
  222. loop_cnt += 1;
  223. }
  224. return 0;
  225. }
  226. #ifdef FINSH_USING_MSH
  227. MSH_CMD_EXPORT_ALIAS(mqtt_example_main, ali_mqtt_sample, ali coap sample);
  228. #endif