fota_basic_demo.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. /*
  2. * 这个例程适用于不支持通过pthread函数在主线程外开独立的固件下载线程的设备
  3. * 它演示了用SDK配置MQTT参数并建立连接, 并在接收到OTA的mqtt消息后开始下载升级固件的过程
  4. * 同时, 它演示了如何将固件的大小分为两半, 每次下载一半的做法. 用户可以进一步将固件分成更多更小的分段
  5. *
  6. * 需要用户关注或修改的部分, 已用 `TODO` 在注释中标明
  7. *
  8. */
  9. /* TODO: 本例子用到了sleep函数, 所以包含了unistd.h. 如果用户自己的库中有可以替代的函数, 则可以将unistd.h替换掉
  10. *
  11. * 本例子用到了malloc/free函数, 所以用到了stdlib.h, 用户如果自己库中有可以替代的函数, 则需要将stdlib.h替换掉
  12. *
  13. */
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <stdlib.h>
  17. #include "aiot_state_api.h"
  18. #include "aiot_sysdep_api.h"
  19. #include "aiot_mqtt_api.h"
  20. #include "aiot_ota_api.h"
  21. #include "ali_demo.h"
  22. #include "ql_api_osi.h"
  23. #include "ql_api_nw.h"
  24. #include "ali_demo.h"
  25. #include "ql_log.h"
  26. #include "ql_api_datacall.h"
  27. #include "sockets.h"
  28. #include "lwip/ip_addr.h"
  29. #include "lwip/ip6_addr.h"
  30. #include "lwip/netdb.h"
  31. #include "lwip/netif.h"
  32. #include "lwip/inet.h"
  33. #include "lwip/tcp.h"
  34. #include "ql_fs.h"
  35. #include "ql_power.h"
  36. #include "ql_api_fota.h"
  37. #define QL_SOCKET_LOG_LEVEL QL_LOG_LEVEL_INFO
  38. #define uart_printf(msg, ...) QL_LOG(QL_SOCKET_LOG_LEVEL, "linkSDK ", msg, ##__VA_ARGS__)
  39. #define fota_model_profile_idx 1
  40. /* TODO: 替换为自己设备的三元组 */
  41. static char *product_key = "a1TSu2F29co";
  42. static char *device_name = "000001";
  43. static char *device_secret = "bd220c3a9c6a5b3f5921485d091497e1";
  44. int fotafile_handle = 0;
  45. static char *cur_version = "1.0.0";
  46. char fota_file_name[100] = "UFS:/fota.pack";
  47. /* 位于external/ali_ca_cert.c中的服务器证书 */
  48. extern const char *ali_ca_cert;
  49. static void *g_ota_handle = NULL;
  50. static void *g_dl_handle = NULL;
  51. static uint32_t g_firmware_size = 0;
  52. ql_task_t ql_alisdk_fota_task_ref;
  53. /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
  54. extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
  55. int fota_basic_image_verify( char *fotaFilePath);
  56. static int datacall_satrt(void)
  57. {
  58. int ret = 0;
  59. int i = 0;
  60. ql_data_call_info_s info;
  61. char ip4_addr_str[16] = {0};
  62. uint8_t nSim = 0;
  63. ql_rtos_task_sleep_s(10);
  64. uart_printf("========== socket demo start ==========");
  65. uart_printf("wait for network register done");
  66. while ((ret = ql_network_register_wait(nSim, 120)) != 0 && i < 10)
  67. {
  68. i++;
  69. ql_rtos_task_sleep_s(1);
  70. }
  71. if (ret == 0)
  72. {
  73. i = 0;
  74. uart_printf("====network registered!!!!====");
  75. }
  76. else
  77. {
  78. uart_printf("====network register failure!!!!!====");
  79. goto exit;
  80. }
  81. ql_set_data_call_asyn_mode(nSim, fota_model_profile_idx, 0);
  82. uart_printf("===start data call====");
  83. ret = ql_start_data_call(nSim, fota_model_profile_idx, QL_PDP_TYPE_IP, "uninet", NULL, NULL, 0);
  84. uart_printf("===data call result:%d", ret);
  85. if (ret != 0)
  86. {
  87. uart_printf("====data call failure!!!!=====");
  88. }
  89. memset(&info, 0x00, sizeof(ql_data_call_info_s));
  90. ret = ql_get_data_call_info(nSim, fota_model_profile_idx, &info);
  91. if (ret != 0)
  92. {
  93. uart_printf("ql_get_data_call_info ret: %d", ret);
  94. ql_stop_data_call(nSim, fota_model_profile_idx);
  95. goto exit;
  96. }
  97. uart_printf("info->mqtt_profile_idx: %d", info.profile_idx);
  98. uart_printf("info->ip_version: %d", info.ip_version);
  99. uart_printf("info->v4.state: %d", info.v4.state);
  100. inet_ntop(AF_INET, &info.v4.addr.ip, ip4_addr_str, sizeof(ip4_addr_str));
  101. uart_printf("info.v4.addr.ip: %s\r\n", ip4_addr_str);
  102. inet_ntop(AF_INET, &info.v4.addr.pri_dns, ip4_addr_str, sizeof(ip4_addr_str));
  103. uart_printf("info.v4.addr.pri_dns: %s\r\n", ip4_addr_str);
  104. inet_ntop(AF_INET, &info.v4.addr.sec_dns, ip4_addr_str, sizeof(ip4_addr_str));
  105. uart_printf("info.v4.addr.sec_dns: %s\r\n", ip4_addr_str);
  106. return 0;
  107. exit:
  108. return -1;
  109. }
  110. /* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印
  111. *
  112. * 例如: [1578463098.611][LK-0309] pub: /ota/device/upgrade/a13FN5TplKq/ota_demo
  113. *
  114. * 上面这条日志的code就是0309(十六进制), code值的定义见core/aiot_state_api.h
  115. *
  116. */
  117. /* 日志回调函数, SDK的日志会从这里输出 */
  118. static int32_t demo_state_logcb(int32_t code, char *message)
  119. {
  120. /* 下载固件的时候会有大量的HTTP收包日志, 通过code筛选出来关闭 */
  121. if (STATE_HTTP_LOG_RECV_CONTENT != code) {
  122. uart_printf("%s", message);
  123. }
  124. return 0;
  125. }
  126. /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */
  127. static void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *const event, void *userdata)
  128. {
  129. switch (event->type) {
  130. /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */
  131. case AIOT_MQTTEVT_CONNECT: {
  132. uart_printf("AIOT_MQTTEVT_CONNECT\r\n");
  133. /* TODO: 处理SDK建连成功, 不可以在这里调用耗时较长的阻塞函数 */
  134. }
  135. break;
  136. /* SDK因为网络状况被动断连后, 自动发起重连已成功 */
  137. case AIOT_MQTTEVT_RECONNECT: {
  138. uart_printf("AIOT_MQTTEVT_RECONNECT\r\n");
  139. /* TODO: 处理SDK重连成功, 不可以在这里调用耗时较长的阻塞函数 */
  140. }
  141. break;
  142. /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */
  143. case AIOT_MQTTEVT_DISCONNECT: {
  144. char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") :
  145. ("heartbeat disconnect");
  146. uart_printf("AIOT_MQTTEVT_DISCONNECT: %s\r\n", cause);
  147. /* TODO: 处理SDK被动断连, 不可以在这里调用耗时较长的阻塞函数 */
  148. }
  149. break;
  150. default: {
  151. }
  152. }
  153. }
  154. /* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时, 且无对应用户回调处理时被调用 */
  155. static void demo_mqtt_default_recv_handler(void *handle, const aiot_mqtt_recv_t *const packet, void *userdata)
  156. {
  157. switch (packet->type) {
  158. case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: {
  159. uart_printf("heartbeat response\r\n");
  160. /* TODO: 处理服务器对心跳的回应, 一般不处理 */
  161. }
  162. break;
  163. case AIOT_MQTTRECV_SUB_ACK: {
  164. uart_printf("suback, res: -0x%04X, packet id: %d, max qos: %d\r\n",
  165. -packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos);
  166. /* TODO: 处理服务器对订阅请求的回应, 一般不处理 */
  167. }
  168. break;
  169. case AIOT_MQTTRECV_PUB: {
  170. uart_printf("pub, qos: %d, topic: %d %s\r\n", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
  171. uart_printf("pub, payload: %d %s\r\n", packet->data.pub.payload_len, packet->data.pub.payload);
  172. /* TODO: 处理服务器下发的业务报文 */
  173. }
  174. break;
  175. case AIOT_MQTTRECV_PUB_ACK: {
  176. uart_printf("puback, packet id: %d\r\n", packet->data.pub_ack.packet_id);
  177. /* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */
  178. }
  179. break;
  180. default: {
  181. }
  182. }
  183. }
  184. /* 下载收包回调, 用户调用 aiot_download_recv() 后, SDK收到数据会进入这个函数, 把下载到的数据交给用户 */
  185. /* TODO: 一般来说, 设备升级时, 会在这个回调中, 把下载到的数据写到Flash上 */
  186. static void user_download_recv_handler(void *handle, const aiot_download_recv_t *packet, void *userdata)
  187. {
  188. int32_t percent = 0;
  189. int32_t last_percent = 0;
  190. uint32_t data_buffer_len = 0;
  191. int64 file_free_size = 0;
  192. /* 目前只支持 packet->type 为 AIOT_DLRECV_HTTPBODY 的情况 */
  193. if (!packet || AIOT_DLRECV_HTTPBODY != packet->type) {
  194. return;
  195. }
  196. percent = packet->data.percent;
  197. /* 如果 percent 为负数, 说明发生了收包异常或者digest校验错误 */
  198. if (percent < 0) {
  199. /* digest校验错误 */
  200. uart_printf("exception happend, percent is %d\r\n", percent);
  201. if (userdata) {
  202. free(userdata);
  203. }
  204. return;
  205. }
  206. /* userdata可以存放 demo_download_recv_handler() 的不同次进入之间, 需要共享的数据 */
  207. /* 这里用来存放上一次进入本回调函数时, 下载的固件进度百分比 */
  208. if (userdata) {
  209. last_percent = *((uint32_t *)(userdata));
  210. }
  211. data_buffer_len = packet->data.len;
  212. /*
  213. * TODO: 下载一段固件成功, 这个时候, 用户应该将
  214. * 起始地址为 packet->data.buffer, 长度为 packet->data.len 的内存, 保存到flash上
  215. *
  216. * 如果烧写flash失败, 还应该调用 aiot_download_report_progress(handle, -4) 将失败上报给云平台
  217. * 备注:协议中, 与云平台商定的错误码在 aiot_ota_protocol_errcode_t 类型中, 例如
  218. * -1: 表示升级失败
  219. * -2: 表示下载失败
  220. * -3: 表示校验失败
  221. * -4: 表示烧写失败
  222. *
  223. * 详情可见 https://help.aliyun.com/document_detail/85700.html
  224. */
  225. file_free_size = ql_fs_free_size(fota_file_name);
  226. if(file_free_size > packet->data.len)
  227. {
  228. ql_rtos_task_sleep_ms(1);
  229. int ret = ql_fwrite(packet->data.buffer, packet->data.len,1,fotafile_handle);
  230. if(ret < 0)//-2: 表示下载失败
  231. {
  232. aiot_download_report_progress(handle, AIOT_OTAERR_FETCH_FAILED);
  233. }
  234. }
  235. /* percent 入参的值为 100 时, 说明SDK已经下载固件内容全部完成 */
  236. if (percent == 100)
  237. {
  238. int ret = fota_basic_image_verify(fota_file_name);
  239. if(QL_FOTA_SUCCESS != ret)//-3: 表示校验失败
  240. {
  241. aiot_download_report_progress(handle, AIOT_OTAERR_CHECKSUM_MISMATCH);
  242. }
  243. /* 上报版本号 */
  244. /*
  245. * TODO: 这个时候, 一般用户就应该完成所有的固件烧录, 保存当前工作, 重启设备, 切换到新的固件上启动了
  246. * 并且, 新的固件必须要以
  247. *
  248. * aiot_ota_report_version(g_ota_handle, new_version);
  249. *
  250. * 这样的操作, 将升级后的新版本号(比如1.0.0升到1.1.0, 则new_version的值是"1.1.0")上报给云平台
  251. * 云平台收到了新的版本号上报后, 才会判定升级成功, 否则会认为本次升级失败了
  252. *
  253. */
  254. }
  255. /* 简化输出, 只有距离上次的下载进度增加5%以上时, 才会打印进度, 并向服务器上报进度 */
  256. if (percent - last_percent >= 5 || percent == 100) {
  257. uart_printf("download %03d%% done, +%d bytes\r\n", percent, data_buffer_len);
  258. aiot_download_report_progress(handle, percent);
  259. if (userdata)
  260. {
  261. *((uint32_t *)(userdata)) = percent;
  262. }
  263. if (percent == 100 && userdata) {
  264. free(userdata);
  265. }
  266. }
  267. }
  268. /* 用户通过 aiot_ota_setopt() 注册的OTA消息处理回调, 如果SDK收到了OTA相关的MQTT消息, 会自动识别, 调用这个回调函数 */
  269. static void user_ota_recv_handler(void *ota_handle, aiot_ota_recv_t *ota_msg, void *userdata)
  270. {
  271. switch (ota_msg->type) {
  272. case AIOT_OTARECV_FOTA: {
  273. uint16_t port = 443;
  274. uint32_t max_buffer_len = 2048;
  275. aiot_sysdep_network_cred_t cred;
  276. void *dl_handle = NULL;
  277. void *last_percent = NULL;
  278. int res;
  279. int pdp;
  280. if (NULL == ota_msg->task_desc) {
  281. break;
  282. }
  283. dl_handle = aiot_download_init();
  284. if (NULL == dl_handle) {
  285. break;
  286. }
  287. /* 指明下载时建立http连接的pdp通道,quectel平台须执行此操作*/
  288. pdp = fota_model_profile_idx;
  289. res= aiot_download_setopt(dl_handle, AIOT_DLOPT_PROFILE_IDX, (void *)&pdp);
  290. if (res != STATE_SUCCESS)
  291. {
  292. uart_printf("%s : line : %d aiot_download_setopt failed!!\r\n", __func__, __LINE__);
  293. aiot_download_deinit(&dl_handle);
  294. free(last_percent);
  295. break;
  296. }
  297. last_percent = malloc(sizeof(uint32_t));
  298. if (NULL == last_percent) {
  299. aiot_download_deinit(&dl_handle);
  300. break;
  301. }
  302. memset(last_percent, 0, sizeof(uint32_t));
  303. uart_printf("OTA target firmware version: %s, size: %u Bytes\r\n", ota_msg->task_desc->version,
  304. ota_msg->task_desc->size_total);
  305. cur_version = ota_msg->task_desc->version;
  306. g_firmware_size = ota_msg->task_desc->size_total;
  307. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  308. cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA;
  309. cred.max_tls_fragment = 16384;
  310. cred.x509_server_cert = ali_ca_cert;
  311. cred.x509_server_cert_len = strlen(ali_ca_cert);
  312. uint32_t end = g_firmware_size / 2;
  313. /* 设置下载时为TLS下载 */
  314. if ((STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_NETWORK_CRED, (void *)(&cred)))
  315. /* 设置下载时访问的服务器端口号 */
  316. || (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_NETWORK_PORT, (void *)(&port)))
  317. /* 设置下载的任务信息, 通过输入参数 ota_msg 中的 task_desc 成员得到, 内含下载地址, 固件大小, 固件签名等 */
  318. || (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_TASK_DESC, (void *)(ota_msg->task_desc)))
  319. /* 设置下载内容到达时, SDK将调用的回调函数 */
  320. || (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_RECV_HANDLER, (void *)(user_download_recv_handler)))
  321. /* 设置单次下载最大的buffer长度, 每当这个长度的内存读满了后会通知用户 */
  322. || (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_BODY_BUFFER_MAX_LEN, (void *)(&max_buffer_len)))
  323. /* 设置 AIOT_DLOPT_RECV_HANDLER 的不同次调用之间共享的数据, 比如例程把进度存在这里 */
  324. || (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_USERDATA, (void *)last_percent))
  325. /* 指明下载方式是按照range下载, 并且当前只下载一半 */
  326. || (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_RANGE_END, (void *)&end))
  327. /* 发送http的GET请求给http服务器 */
  328. || (STATE_SUCCESS != aiot_download_send_request(dl_handle))) {
  329. uart_printf("%s : line : %d aiot_download_setopt failed!!\r\n",__func__, __LINE__);
  330. aiot_download_deinit(&dl_handle);
  331. free(last_percent);
  332. break;
  333. }
  334. g_dl_handle = dl_handle;
  335. break;
  336. }
  337. default:
  338. break;
  339. }
  340. }
  341. static void ql_alisdk_fota_task(void *arg)
  342. {
  343. int32_t res = STATE_SUCCESS;
  344. void *mqtt_handle = NULL;
  345. char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
  346. char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
  347. uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
  348. aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
  349. void *ota_handle = NULL;
  350. uint32_t timeout_ms = 0;
  351. if (fotafile_handle <= 0)
  352. {
  353. fotafile_handle = ql_fopen(fota_file_name, "w+");
  354. if(fotafile_handle < 0)
  355. {
  356. uart_printf("open file:[%s] fail fd:[%d]\r\n",fota_file_name,fotafile_handle);
  357. return ;
  358. }
  359. }
  360. /*执行拨号操作,设备联网*/
  361. if(datacall_satrt() != 0)
  362. goto exit;
  363. /* 配置SDK的底层依赖 */
  364. aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
  365. /* 配置SDK的日志输出 */
  366. aiot_state_set_logcb(demo_state_logcb);
  367. /* 创建SDK的安全凭据, 用于建立TLS连接 */
  368. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  369. cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
  370. cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
  371. cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
  372. cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
  373. cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
  374. /* 创建1个MQTT客户端实例并内部初始化默认参数 */
  375. mqtt_handle = aiot_mqtt_init();
  376. if (mqtt_handle == NULL) {
  377. goto exit;
  378. }
  379. snprintf(host, 100, "%s.%s", product_key, url);
  380. /* 配置MQTT服务器地址 */
  381. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
  382. /* 配置MQTT服务器端口 */
  383. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
  384. /* 配置设备productKey */
  385. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
  386. /* 配置设备deviceName */
  387. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
  388. /* 配置设备deviceSecret */
  389. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
  390. /* 配置网络连接的安全凭据, 上面已经创建好了 */
  391. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
  392. /* 配置MQTT默认消息接收回调函数 */
  393. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)demo_mqtt_default_recv_handler);
  394. /* 配置MQTT事件回调函数 */
  395. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
  396. /* 配置MQTT连接超时时间 */
  397. int time_delay_ms = 5000;
  398. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CONNECT_TIMEOUT_MS, (void *)&time_delay_ms);
  399. /* 配置拨号profile_idx信息(quectel平台必须执行此操作)*/
  400. int pdp = fota_model_profile_idx;
  401. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PROFILE_IDX, (void *)&pdp);
  402. /* 与MQTT例程不同的是, 这里需要增加创建OTA会话实例的语句 */
  403. ota_handle = aiot_ota_init();
  404. if (NULL == ota_handle) {
  405. goto exit;
  406. }
  407. /* 用以下语句, 把OTA会话和MQTT会话关联起来 */
  408. aiot_ota_setopt(ota_handle, AIOT_OTAOPT_MQTT_HANDLE, mqtt_handle);
  409. /* 用以下语句, 设置OTA会话的数据接收回调, SDK收到OTA相关推送时, 会进入这个回调函数 */
  410. aiot_ota_setopt(ota_handle, AIOT_OTAOPT_RECV_HANDLER, user_ota_recv_handler);
  411. g_ota_handle = ota_handle;
  412. /* 与服务器建立MQTT连接 */
  413. res = aiot_mqtt_connect(mqtt_handle);
  414. if (res < STATE_SUCCESS) {
  415. uart_printf("aiot_mqtt_connect failed: -0x%04X\r\n", -res);
  416. /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
  417. goto exit;
  418. }
  419. /*
  420. * 如果烧写flash失败, 还应该调用 aiot_download_report_progress(handle, -4) 将失败上报给云平台
  421. * 备注:协议中, 与云平台商定的错误码在 aiot_ota_protocol_errcode_t 类型中, 例如
  422. * -1: 表示升级失败
  423. * -2: 表示下载失败
  424. * -3: 表示校验失败
  425. * -4: 表示烧写失败
  426. */
  427. ql_fota_result_e p_fota_result = 0;
  428. if( QL_FOTA_SUCCESS == ql_fota_get_result(&p_fota_result) && QL_FOTA_READY == p_fota_result )//-1: 表示升级失败
  429. {
  430. uart_printf("Upgrade failed");
  431. aiot_download_report_progress(ota_handle, AIOT_OTAERR_UPGRADE_FAILED);
  432. }
  433. /* TODO: 非常重要!!!
  434. *
  435. * cur_version 要根据用户实际情况, 改成从设备的配置区获取, 要反映真实的版本号, 而不能像示例这样写为固定值
  436. *
  437. * 1. 如果设备从未上报过版本号, 在控制台网页将无法部署升级任务
  438. * 2. 如果设备升级完成后, 上报的不是新的版本号, 在控制台网页将会显示升级失败
  439. *
  440. */
  441. /* 演示MQTT连接建立起来之后, 就可以上报当前设备的版本号了 */
  442. res = aiot_ota_report_version(ota_handle, cur_version);
  443. if (res < STATE_SUCCESS) {
  444. uart_printf("report version failed, code is -0x%04X\r\n", -res);
  445. }
  446. while (1) {
  447. res = aiot_mqtt_process(mqtt_handle);
  448. if (res == STATE_USER_INPUT_EXEC_DISABLED)
  449. {
  450. uart_printf("download failed, error code is %d, exit!\r\n", res);
  451. break;
  452. }
  453. res = aiot_mqtt_recv(mqtt_handle);
  454. if (res == STATE_SYS_DEPEND_NWK_CLOSED) {
  455. ql_rtos_task_sleep_s(1);
  456. }
  457. if (NULL != g_dl_handle) {
  458. uart_printf("g_dl_handle is no NULL ,ready to download the firmware !!\n");
  459. /* 完成固件的接收前, 将mqtt的收包超时调整到100ms, 以减少两次固件下载动作之间的时间间隔 */
  460. int32_t ret = aiot_download_recv(g_dl_handle);
  461. timeout_ms = 100;
  462. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_TIMEOUT_MS, (void *)&timeout_ms);
  463. /* 本例子中, 将整个固件分为2个等份来下载, 每次下载一半, 第一半下载完成时会进入这个分支 */
  464. if (STATE_DOWNLOAD_RANGE_FINISHED == ret) {
  465. uart_printf("the first half download finished\n");
  466. /* 当第一次下载完成后, 要重新设置range的start/end值, 下载另外一半 */
  467. /*
  468. * 非常重要:
  469. *
  470. * 上一次下载的范围是[0, g_firmware_size/2],
  471. * 因此这一次下载需要从 [g_firmware_size/2 + 1, 固件结束地址],
  472. * 其中固件结束地址填0的话就表示直到下载结束
  473. *
  474. */
  475. uint32_t start = g_firmware_size / 2 + 1;
  476. uint32_t end = 0;
  477. aiot_download_setopt(g_dl_handle, AIOT_DLOPT_RANGE_START, (void *)&start);
  478. /* range_end如果指定为0, 服务器就理解为下载到文件末尾后结束 */
  479. aiot_download_setopt(g_dl_handle, AIOT_DLOPT_RANGE_END, (void *)&end);
  480. /* 向服务器发起下一次下载的请求 */
  481. aiot_download_send_request(g_dl_handle);
  482. continue;
  483. }
  484. /* 整个固件下载完成 */
  485. if (ret == STATE_DOWNLOAD_FINISHED) {
  486. uart_printf("down finished all\n");
  487. aiot_download_deinit(&g_dl_handle);
  488. /* 完成固件的接收后, 将mqtt的收包超时调整回到默认值5000ms */
  489. timeout_ms = 5000;
  490. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_TIMEOUT_MS, (void *)&timeout_ms);
  491. break;
  492. }
  493. /* 下载的内容超出了固件的总大小, 可能是用户把range划分错了, range之间有重叠 */
  494. if (ret == STATE_DOWNLOAD_FETCH_TOO_MANY) {
  495. uart_printf("downloaded more than expeced bytes, please check range start/end settings\n");
  496. aiot_download_deinit(&g_dl_handle);
  497. /* 完成固件的接收后, 将mqtt的收包超时调整回到默认值5000ms */
  498. timeout_ms = 5000;
  499. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_TIMEOUT_MS, (void *)&timeout_ms);
  500. continue;
  501. }
  502. if (STATE_DOWNLOAD_RENEWAL_REQUEST_SENT == ret) {
  503. uart_printf("download renewal request has been sent successfully\r\n");
  504. continue;
  505. }
  506. if (ret <= STATE_SUCCESS) {
  507. uart_printf("download failed, error code is %d, try to send renewal request\r\n", ret);
  508. continue;
  509. }
  510. }
  511. }
  512. /* 断开MQTT连接, 一般不会运行到这里 */
  513. res = aiot_mqtt_disconnect(mqtt_handle);
  514. if (res < STATE_SUCCESS) {
  515. uart_printf("aiot_mqtt_disconnect failed: -0x%04X\r\n", -res);
  516. goto exit;
  517. }
  518. exit:
  519. if (fotafile_handle > 0)
  520. {
  521. ql_fclose(fotafile_handle);
  522. fotafile_handle = -1;
  523. }
  524. while (1) {
  525. /* 销毁MQTT实例, 一般不会运行到这里 */
  526. res = aiot_mqtt_deinit(&mqtt_handle);
  527. if (res < STATE_SUCCESS) {
  528. uart_printf("aiot_mqtt_deinit failed: -0x%04X\r\n", -res);
  529. return ;
  530. } else {
  531. break;
  532. }
  533. }
  534. /* 销毁OTA实例, 一般不会运行到这里 */
  535. aiot_ota_deinit(&ota_handle);
  536. return ;
  537. }
  538. #define QL_ALI_TASK_STACK_SIZE 10240
  539. #define QL_ALI_TASK_PRIO APP_PRIORITY_NORMAL
  540. #define QL_ALI_TASK_EVENT_CNT 5
  541. int ql_ali_sdk_fota_test_init(void)
  542. {
  543. QlOSStatus status;
  544. int count = 0;
  545. /* 主循环进入休眠 */
  546. while (count < 10)
  547. {
  548. count++;
  549. ql_rtos_task_sleep_s(1);
  550. uart_printf("ql_ali_sdk_mqtt_client_test_init -0x%04X\n", count);
  551. }
  552. status =ql_rtos_task_create(&ql_alisdk_fota_task_ref, QL_ALI_TASK_STACK_SIZE, APP_PRIORITY_NORMAL, "fota_task", ql_alisdk_fota_task, NULL, QL_ALI_TASK_EVENT_CNT);
  553. if (status != QL_OSI_SUCCESS)
  554. {
  555. uart_printf("ql_ali_sdk_devinfo_test_init error");
  556. return -1;
  557. }
  558. return 0;
  559. }
  560. int fota_basic_image_verify(char *fotaFilePath)
  561. {
  562. ql_errcode_fota_e ret = ql_fota_image_verify(fotaFilePath);
  563. if ( ret != QL_FOTA_SUCCESS )
  564. {
  565. ql_remove(fotaFilePath);
  566. uart_printf("[%s]package is invalid",fotaFilePath);
  567. }
  568. else//校验成功
  569. {
  570. uart_printf("download is sucess ,system will reset power!");
  571. ql_rtos_task_sleep_s(5);
  572. ql_power_reset(RESET_NORMAL);
  573. }
  574. return ret;
  575. }