ota_mqtt-example.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /*
  2. * Copyright (c) 2014-2016 Alibaba Group. All rights reserved.
  3. * License-Identifier: Apache-2.0
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. * not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdarg.h>
  22. #include "iot_import.h"
  23. #include "iot_export.h"
  24. #if defined(MQTT_ID2_AUTH) && defined(TEST_ID2_DAILY)
  25. #define PRODUCT_KEY "OvNmiEYRDSY"
  26. #define DEVICE_NAME "sh_online_sample_mqtt"
  27. #define DEVICE_SECRET "v9mqGzepKEphLhXmAoiaUIR2HZ7XwTky"
  28. #elif defined(TEST_OTA_PRE)
  29. #define PRODUCT_KEY "6RcIOUafDOm"
  30. #define DEVICE_NAME "sh_pre_sample_mqtt"
  31. #define DEVICE_SECRET "R0OTtD46DSalSpGW7SFzFDIA6fksTC2c"
  32. #elif defined(TEST_MQTT_DAILY)
  33. #define PRODUCT_KEY "fR9zCD4oT72"
  34. #define DEVICE_NAME "ota_test"
  35. #define DEVICE_SECRET "67szT5tQNMIu3sbrd3UwLhs7M73wTHXQ"
  36. #else
  37. #define PRODUCT_KEY "yfTuLfBJTiL"
  38. #define DEVICE_NAME "TestDeviceForDemo"
  39. #define DEVICE_SECRET "fSCl9Ns5YPnYN8Ocg0VEel1kXFnRlV6c"
  40. #endif
  41. char g_product_key[PRODUCT_KEY_LEN + 1];
  42. char g_product_secret[PRODUCT_SECRET_LEN + 1];
  43. char g_device_name[DEVICE_NAME_LEN + 1];
  44. char g_device_secret[DEVICE_SECRET_LEN + 1];
  45. /* These are pre-defined topics */
  46. #define TOPIC_UPDATE "/"PRODUCT_KEY"/"DEVICE_NAME"/update"
  47. #define TOPIC_ERROR "/"PRODUCT_KEY"/"DEVICE_NAME"/update/error"
  48. #define TOPIC_GET "/"PRODUCT_KEY"/"DEVICE_NAME"/get"
  49. #define TOPIC_DATA "/"PRODUCT_KEY"/"DEVICE_NAME"/data"
  50. #define OTA_MQTT_MSGLEN (2048)
  51. #define EXAMPLE_TRACE(fmt, ...) \
  52. do { \
  53. HAL_Printf("%s|%03d :: ", __func__, __LINE__); \
  54. HAL_Printf(fmt, ##__VA_ARGS__); \
  55. HAL_Printf("%s", "\r\n"); \
  56. } while(0)
  57. static int user_argc;
  58. static char **user_argv;
  59. void event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
  60. {
  61. uintptr_t packet_id = (uintptr_t)msg->msg;
  62. iotx_mqtt_topic_info_pt topic_info = (iotx_mqtt_topic_info_pt)msg->msg;
  63. switch (msg->event_type) {
  64. case IOTX_MQTT_EVENT_UNDEF:
  65. EXAMPLE_TRACE("undefined event occur.");
  66. break;
  67. case IOTX_MQTT_EVENT_DISCONNECT:
  68. EXAMPLE_TRACE("MQTT disconnect.");
  69. break;
  70. case IOTX_MQTT_EVENT_RECONNECT:
  71. EXAMPLE_TRACE("MQTT reconnect.");
  72. break;
  73. case IOTX_MQTT_EVENT_SUBCRIBE_SUCCESS:
  74. EXAMPLE_TRACE("subscribe success, packet-id=%u", (unsigned int)packet_id);
  75. break;
  76. case IOTX_MQTT_EVENT_SUBCRIBE_TIMEOUT:
  77. EXAMPLE_TRACE("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id);
  78. break;
  79. case IOTX_MQTT_EVENT_SUBCRIBE_NACK:
  80. EXAMPLE_TRACE("subscribe nack, packet-id=%u", (unsigned int)packet_id);
  81. break;
  82. case IOTX_MQTT_EVENT_UNSUBCRIBE_SUCCESS:
  83. EXAMPLE_TRACE("unsubscribe success, packet-id=%u", (unsigned int)packet_id);
  84. break;
  85. case IOTX_MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
  86. EXAMPLE_TRACE("unsubscribe timeout, packet-id=%u", (unsigned int)packet_id);
  87. break;
  88. case IOTX_MQTT_EVENT_UNSUBCRIBE_NACK:
  89. EXAMPLE_TRACE("unsubscribe nack, packet-id=%u", (unsigned int)packet_id);
  90. break;
  91. case IOTX_MQTT_EVENT_PUBLISH_SUCCESS:
  92. EXAMPLE_TRACE("publish success, packet-id=%u", (unsigned int)packet_id);
  93. break;
  94. case IOTX_MQTT_EVENT_PUBLISH_TIMEOUT:
  95. EXAMPLE_TRACE("publish timeout, packet-id=%u", (unsigned int)packet_id);
  96. break;
  97. case IOTX_MQTT_EVENT_PUBLISH_NACK:
  98. EXAMPLE_TRACE("publish nack, packet-id=%u", (unsigned int)packet_id);
  99. break;
  100. case IOTX_MQTT_EVENT_PUBLISH_RECVEIVED:
  101. EXAMPLE_TRACE("topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s",
  102. topic_info->topic_len,
  103. topic_info->ptopic,
  104. topic_info->payload_len,
  105. topic_info->payload);
  106. break;
  107. default:
  108. EXAMPLE_TRACE("Should NOT arrive here.");
  109. break;
  110. }
  111. }
  112. int mqtt_client(void)
  113. {
  114. #define OTA_BUF_LEN (5000)
  115. int rc = 0, ota_over = 0;
  116. void *pclient = NULL, *h_ota = NULL;
  117. iotx_conn_info_pt pconn_info;
  118. iotx_mqtt_param_t mqtt_params;
  119. char *msg_buf = NULL, *msg_readbuf = NULL;
  120. FILE *fp;
  121. char buf_ota[OTA_BUF_LEN];
  122. if (NULL == (fp = fopen("ota.bin", "wb+"))) {
  123. EXAMPLE_TRACE("open file failed");
  124. goto do_exit;
  125. }
  126. if (NULL == (msg_buf = (char *)HAL_Malloc(OTA_MQTT_MSGLEN))) {
  127. EXAMPLE_TRACE("not enough memory");
  128. rc = -1;
  129. goto do_exit;
  130. }
  131. if (NULL == (msg_readbuf = (char *)HAL_Malloc(OTA_MQTT_MSGLEN))) {
  132. EXAMPLE_TRACE("not enough memory");
  133. rc = -1;
  134. goto do_exit;
  135. }
  136. /**< get device info*/
  137. HAL_GetProductKey(g_product_key);
  138. HAL_GetDeviceName(g_device_name);
  139. HAL_GetDeviceSecret(g_device_secret);
  140. /**< end*/
  141. /* Device AUTH */
  142. if (0 != IOT_SetupConnInfo(g_product_key, g_device_name, g_device_secret, (void **)&pconn_info)) {
  143. EXAMPLE_TRACE("AUTH request failed!");
  144. rc = -1;
  145. goto do_exit;
  146. }
  147. /* Initialize MQTT parameter */
  148. memset(&mqtt_params, 0x0, sizeof(mqtt_params));
  149. mqtt_params.port = pconn_info->port;
  150. mqtt_params.host = pconn_info->host_name;
  151. mqtt_params.client_id = pconn_info->client_id;
  152. mqtt_params.username = pconn_info->username;
  153. mqtt_params.password = pconn_info->password;
  154. mqtt_params.pub_key = pconn_info->pub_key;
  155. mqtt_params.request_timeout_ms = 2000;
  156. mqtt_params.clean_session = 0;
  157. mqtt_params.keepalive_interval_ms = 60000;
  158. mqtt_params.pread_buf = msg_readbuf;
  159. mqtt_params.read_buf_size = OTA_MQTT_MSGLEN;
  160. mqtt_params.pwrite_buf = msg_buf;
  161. mqtt_params.write_buf_size = OTA_MQTT_MSGLEN;
  162. mqtt_params.handle_event.h_fp = event_handle;
  163. mqtt_params.handle_event.pcontext = NULL;
  164. /* Construct a MQTT client with specify parameter */
  165. pclient = IOT_MQTT_Construct(&mqtt_params);
  166. if (NULL == pclient) {
  167. EXAMPLE_TRACE("MQTT construct failed");
  168. rc = -1;
  169. goto do_exit;
  170. }
  171. h_ota = IOT_OTA_Init(PRODUCT_KEY, DEVICE_NAME, pclient);
  172. if (NULL == h_ota) {
  173. rc = -1;
  174. EXAMPLE_TRACE("initialize OTA failed");
  175. goto do_exit;
  176. }
  177. if (0 != IOT_OTA_ReportVersion(h_ota, "iotx_ver_1.0.0")) {
  178. rc = -1;
  179. EXAMPLE_TRACE("report OTA version failed");
  180. goto do_exit;
  181. }
  182. HAL_SleepMs(1000);
  183. do {
  184. uint32_t firmware_valid;
  185. EXAMPLE_TRACE("wait ota upgrade command....");
  186. /* handle the MQTT packet received from TCP or SSL connection */
  187. IOT_MQTT_Yield(pclient, 200);
  188. if (IOT_OTA_IsFetching(h_ota)) {
  189. uint32_t last_percent = 0, percent = 0;
  190. char version[128], md5sum[33];
  191. uint32_t len, size_downloaded, size_file;
  192. do {
  193. len = IOT_OTA_FetchYield(h_ota, buf_ota, OTA_BUF_LEN, 1);
  194. if (len > 0) {
  195. if (1 != fwrite(buf_ota, len, 1, fp)) {
  196. EXAMPLE_TRACE("write data to file failed");
  197. rc = -1;
  198. break;
  199. }
  200. } else {
  201. IOT_OTA_ReportProgress(h_ota, IOT_OTAP_FETCH_FAILED, NULL);
  202. EXAMPLE_TRACE("ota fetch fail");
  203. }
  204. /* get OTA information */
  205. IOT_OTA_Ioctl(h_ota, IOT_OTAG_FETCHED_SIZE, &size_downloaded, 4);
  206. IOT_OTA_Ioctl(h_ota, IOT_OTAG_FILE_SIZE, &size_file, 4);
  207. IOT_OTA_Ioctl(h_ota, IOT_OTAG_MD5SUM, md5sum, 33);
  208. IOT_OTA_Ioctl(h_ota, IOT_OTAG_VERSION, version, 128);
  209. last_percent = percent;
  210. percent = (size_downloaded * 100) / size_file;
  211. if (percent - last_percent > 0) {
  212. IOT_OTA_ReportProgress(h_ota, percent, NULL);
  213. IOT_OTA_ReportProgress(h_ota, percent, "hello");
  214. }
  215. IOT_MQTT_Yield(pclient, 100);
  216. } while (!IOT_OTA_IsFetchFinish(h_ota));
  217. IOT_OTA_Ioctl(h_ota, IOT_OTAG_CHECK_FIRMWARE, &firmware_valid, 4);
  218. if (0 == firmware_valid) {
  219. EXAMPLE_TRACE("The firmware is invalid");
  220. } else {
  221. EXAMPLE_TRACE("The firmware is valid");
  222. }
  223. ota_over = 1;
  224. }
  225. HAL_SleepMs(2000);
  226. } while (!ota_over);
  227. HAL_SleepMs(200);
  228. do_exit:
  229. if (NULL != h_ota) {
  230. IOT_OTA_Deinit(h_ota);
  231. }
  232. if (NULL != pclient) {
  233. IOT_MQTT_Destroy(&pclient);
  234. }
  235. if (NULL != msg_buf) {
  236. HAL_Free(msg_buf);
  237. }
  238. if (NULL != msg_readbuf) {
  239. HAL_Free(msg_readbuf);
  240. }
  241. if (NULL != fp) {
  242. fclose(fp);
  243. }
  244. return rc;
  245. }
  246. int main(int argc, char **argv)
  247. {
  248. IOT_OpenLog("mqtt");
  249. IOT_SetLogLevel(IOT_LOG_DEBUG);
  250. user_argc = argc;
  251. user_argv = argv;
  252. /**< set device info*/
  253. HAL_SetProductKey(PRODUCT_KEY);
  254. HAL_SetDeviceName(DEVICE_NAME);
  255. HAL_SetDeviceSecret(DEVICE_SECRET);
  256. /**< end*/
  257. mqtt_client();
  258. IOT_DumpMemoryStats(IOT_LOG_DEBUG);
  259. IOT_CloseLog();
  260. EXAMPLE_TRACE("out of sample!");
  261. return 0;
  262. }