cota_basic_demo.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /*
  2. * 这个例子主要用于演示如何从设备端获取存储在云端的关于这个设备的远程配置
  3. *
  4. * 需要用户关注或修改的部分, 已用 `TODO` 在注释中标明
  5. *
  6. */
  7. /* TODO: 本例子用到了sleep函数, 所以包含了unistd.h. 如果用户自己的库中有可以替代的函数, 则可以将unistd.h替换掉
  8. *
  9. */
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include "aiot_state_api.h"
  13. #include "aiot_sysdep_api.h"
  14. #include "aiot_mqtt_api.h"
  15. #include "aiot_ota_api.h"
  16. #include "ali_demo.h"
  17. #include "ql_api_osi.h"
  18. #include "ql_api_nw.h"
  19. #include "ali_demo.h"
  20. #include "ql_log.h"
  21. #include "ql_api_datacall.h"
  22. #include "sockets.h"
  23. #include "lwip/ip_addr.h"
  24. #include "lwip/ip6_addr.h"
  25. #include "lwip/netdb.h"
  26. #include "lwip/netif.h"
  27. #include "lwip/inet.h"
  28. #include "lwip/tcp.h"
  29. #define QL_SOCKET_LOG_LEVEL QL_LOG_LEVEL_INFO
  30. #define uart_printf(msg, ...) QL_LOG(QL_SOCKET_LOG_LEVEL, "linkSDK ", msg, ##__VA_ARGS__)
  31. #define cota_model_profile_idx 1
  32. /* TODO: 替换为自己设备的三元组 */
  33. static char *product_key = "a1TSu2F29co";
  34. static char *device_name = "000001";
  35. static char *device_secret = "bd220c3a9c6a5b3f5921485d091497e1";
  36. /* 位于external/ali_ca_cert.c中的服务器证书 */
  37. extern const char *ali_ca_cert;
  38. static void *g_dl_handle = NULL;
  39. ql_task_t ql_alisdk_cota_task_ref;
  40. /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
  41. extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
  42. static int datacall_satrt(void)
  43. {
  44. int ret = 0;
  45. int i = 0;
  46. ql_data_call_info_s info;
  47. char ip4_addr_str[16] = {0};
  48. uint8_t nSim = 0;
  49. ql_rtos_task_sleep_s(10);
  50. uart_printf("========== socket demo start ==========");
  51. uart_printf("wait for network register done");
  52. while ((ret = ql_network_register_wait(nSim, 120)) != 0 && i < 10)
  53. {
  54. i++;
  55. ql_rtos_task_sleep_s(1);
  56. }
  57. if (ret == 0)
  58. {
  59. i = 0;
  60. uart_printf("====network registered!!!!====");
  61. }
  62. else
  63. {
  64. uart_printf("====network register failure!!!!!====");
  65. goto exit;
  66. }
  67. ql_set_data_call_asyn_mode(nSim, cota_model_profile_idx, 0);
  68. uart_printf("===start data call====");
  69. ret = ql_start_data_call(nSim, cota_model_profile_idx, QL_PDP_TYPE_IP, "uninet", NULL, NULL, 0);
  70. uart_printf("===data call result:%d", ret);
  71. if (ret != 0)
  72. {
  73. uart_printf("====data call failure!!!!=====");
  74. }
  75. memset(&info, 0x00, sizeof(ql_data_call_info_s));
  76. ret = ql_get_data_call_info(nSim, cota_model_profile_idx, &info);
  77. if (ret != 0)
  78. {
  79. uart_printf("ql_get_data_call_info ret: %d", ret);
  80. ql_stop_data_call(nSim, cota_model_profile_idx);
  81. goto exit;
  82. }
  83. uart_printf("info->mqtt_profile_idx: %d", info.profile_idx);
  84. uart_printf("info->ip_version: %d", info.ip_version);
  85. uart_printf("info->v4.state: %d", info.v4.state);
  86. inet_ntop(AF_INET, &info.v4.addr.ip, ip4_addr_str, sizeof(ip4_addr_str));
  87. uart_printf("info.v4.addr.ip: %s\r\n", ip4_addr_str);
  88. inet_ntop(AF_INET, &info.v4.addr.pri_dns, ip4_addr_str, sizeof(ip4_addr_str));
  89. uart_printf("info.v4.addr.pri_dns: %s\r\n", ip4_addr_str);
  90. inet_ntop(AF_INET, &info.v4.addr.sec_dns, ip4_addr_str, sizeof(ip4_addr_str));
  91. uart_printf("info.v4.addr.sec_dns: %s\r\n", ip4_addr_str);
  92. return 0;
  93. exit:
  94. return -1;
  95. }
  96. /* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印
  97. *
  98. * 例如: [1578463098.611][LK-0309] pub: /ota/device/upgrade/a13FN5TplKq/ota_demo
  99. *
  100. * 上面这条日志的code就是0309(十六进制), code值的定义见core/aiot_state_api.h
  101. *
  102. */
  103. /* 日志回调函数, SDK的日志会从这里输出 */
  104. static int32_t demo_state_logcb(int32_t code, char *message)
  105. {
  106. /* 下载远程配置的时候会有大量的HTTP收包日志, 通过code筛选出来关闭 */
  107. if (STATE_HTTP_LOG_RECV_CONTENT != code) {
  108. uart_printf("%s", message);
  109. }
  110. return 0;
  111. }
  112. /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */
  113. static void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *const event, void *userdata)
  114. {
  115. switch (event->type) {
  116. /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */
  117. case AIOT_MQTTEVT_CONNECT: {
  118. uart_printf("AIOT_MQTTEVT_CONNECT\r\n");
  119. /* TODO: 处理SDK建连成功, 不可以在这里调用耗时较长的阻塞函数 */
  120. }
  121. break;
  122. /* SDK因为网络状况被动断连后, 自动发起重连已成功 */
  123. case AIOT_MQTTEVT_RECONNECT: {
  124. uart_printf("AIOT_MQTTEVT_RECONNECT\r\n");
  125. /* TODO: 处理SDK重连成功, 不可以在这里调用耗时较长的阻塞函数 */
  126. }
  127. break;
  128. /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */
  129. case AIOT_MQTTEVT_DISCONNECT: {
  130. char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") :
  131. ("heartbeat disconnect");
  132. uart_printf("AIOT_MQTTEVT_DISCONNECT: %s\r\n", cause);
  133. /* TODO: 处理SDK被动断连, 不可以在这里调用耗时较长的阻塞函数 */
  134. }
  135. break;
  136. default: {
  137. }
  138. }
  139. }
  140. /* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时, 且无对应用户回调处理时被调用 */
  141. static void demo_mqtt_default_recv_handler(void *handle, const aiot_mqtt_recv_t *const packet, void *userdata)
  142. {
  143. switch (packet->type) {
  144. case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: {
  145. uart_printf("heartbeat response\r\n");
  146. /* TODO: 处理服务器对心跳的回应, 一般不处理 */
  147. }
  148. break;
  149. case AIOT_MQTTRECV_SUB_ACK: {
  150. uart_printf("suback, res: -0x%04X, packet id: %d, max qos: %d\r\n",
  151. -packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos);
  152. /* TODO: 处理服务器对订阅请求的回应, 一般不处理 */
  153. }
  154. break;
  155. case AIOT_MQTTRECV_PUB: {
  156. uart_printf("pub, qos: %d, topic: %d %s\r\n", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
  157. uart_printf("pub, payload: %d %s\r\n", packet->data.pub.payload_len, packet->data.pub.payload);
  158. /* TODO: 处理服务器下发的业务报文 */
  159. }
  160. break;
  161. case AIOT_MQTTRECV_PUB_ACK: {
  162. uart_printf("puback, packet id: %d\r\n", packet->data.pub_ack.packet_id);
  163. /* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */
  164. }
  165. break;
  166. default: {
  167. }
  168. }
  169. }
  170. /* 下载收包回调, 用户调用 aiot_download_recv() 后, SDK收到数据会进入这个函数, 把下载到的数据交给用户 */
  171. /* TODO: 在用户收到远程配置的数据后, 需要自己决定如何处理 */
  172. static void demo_download_recv_handler(void *handle, const aiot_download_recv_t *packet, void *userdata)
  173. {
  174. /* 目前只支持 packet->type 为 AIOT_DLRECV_HTTPBODY 的情况 */
  175. if (!packet || AIOT_DLRECV_HTTPBODY != packet->type) {
  176. return;
  177. }
  178. int32_t percent = packet->data.percent;
  179. uint8_t *src_buffer = packet->data.buffer;
  180. uint32_t src_buffer_len = packet->data.len;
  181. /* 如果 percent 为负数, 说明发生了收包异常或者digest校验错误 */
  182. if (percent < 0) {
  183. /* 收包异常或者digest校验错误 */
  184. uart_printf("exception happend, percent is %d\r\n", percent);
  185. return;
  186. }
  187. aiot_download_report_progress(handle, percent);
  188. uart_printf("config len is %d, config content is %.*s\r\n", src_buffer_len, src_buffer_len, (char *)src_buffer);
  189. }
  190. /* 用户通过 aiot_ota_setopt() 注册的OTA消息处理回调, 如果SDK收到了OTA相关的MQTT消息, 会自动识别, 调用这个回调函数 */
  191. static void demo_ota_recv_handler(void *ota_handle, aiot_ota_recv_t *ota_msg, void *userdata)
  192. {
  193. switch (ota_msg->type) {
  194. case AIOT_OTARECV_COTA: {
  195. uint16_t port = 443;
  196. uint32_t max_buffer_len = 2048;
  197. aiot_sysdep_network_cred_t cred;
  198. void *dl_handle = aiot_download_init();
  199. if (NULL == dl_handle || NULL == ota_msg->task_desc) {
  200. return;
  201. }
  202. uart_printf("configId: %s, configSize: %u Bytes\r\n", ota_msg->task_desc->version,
  203. ota_msg->task_desc->size_total);
  204. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  205. cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA;
  206. cred.max_tls_fragment = 16384;
  207. cred.x509_server_cert = ali_ca_cert;
  208. cred.x509_server_cert_len = strlen(ali_ca_cert);
  209. /* 设置下载时为TLS下载 */
  210. if ((STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_NETWORK_CRED, (void *)(&cred))) ||
  211. /* 设置下载时访问的服务器端口号 */
  212. (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_NETWORK_PORT, (void *)(&port))) ||
  213. /* 设置下载的任务信息, 通过输入参数 ota_msg 中的 task_desc 成员得到, 内含下载地址, 远程配置的大小和版本号*/
  214. (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_TASK_DESC, (void *)(ota_msg->task_desc))) ||
  215. /* 设置下载内容到达时, SDK将调用的回调函数 */
  216. (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_RECV_HANDLER, (void *)(demo_download_recv_handler))) ||
  217. /* 设置单次下载最大的buffer长度, 每当这个长度的内存读满了后会通知用户 */
  218. (STATE_SUCCESS != aiot_download_setopt(dl_handle, AIOT_DLOPT_BODY_BUFFER_MAX_LEN, (void *)(&max_buffer_len))) ||
  219. /* 发送http的GET请求给http服务器 */
  220. (STATE_SUCCESS != aiot_download_send_request(dl_handle))) {
  221. aiot_download_deinit(&dl_handle);
  222. break;
  223. }
  224. g_dl_handle = dl_handle;
  225. break;
  226. }
  227. default:
  228. break;
  229. }
  230. }
  231. static void ql_alisdk_cota_task(void *arg)
  232. {
  233. int32_t res = STATE_SUCCESS;
  234. void *mqtt_handle = NULL;
  235. char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
  236. char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
  237. uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
  238. aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
  239. void *ota_handle = NULL;
  240. uint32_t timeout_ms = 0;
  241. int time_delay_ms = 5000;
  242. int pdp = cota_model_profile_idx;
  243. /*执行拨号操作,设备联网*/
  244. if(datacall_satrt() != 0)
  245. goto exit;
  246. /* 配置SDK的底层依赖 */
  247. aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
  248. /* 配置SDK的日志输出 */
  249. aiot_state_set_logcb(demo_state_logcb);
  250. /* 创建SDK的安全凭据, 用于建立TLS连接 */
  251. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  252. cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
  253. cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
  254. cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
  255. cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
  256. cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
  257. /* 创建1个MQTT客户端实例并内部初始化默认参数 */
  258. mqtt_handle = aiot_mqtt_init();
  259. if (mqtt_handle == NULL) {
  260. return;
  261. }
  262. snprintf(host, 100, "%s.%s", product_key, url);
  263. /* 配置MQTT服务器地址 */
  264. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
  265. /* 配置MQTT服务器端口 */
  266. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
  267. /* 配置设备productKey */
  268. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
  269. /* 配置设备deviceName */
  270. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
  271. /* 配置设备deviceSecret */
  272. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
  273. /* 配置网络连接的安全凭据, 上面已经创建好了 */
  274. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
  275. /* 配置MQTT默认消息接收回调函数 */
  276. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)demo_mqtt_default_recv_handler);
  277. /* 配置MQTT事件回调函数 */
  278. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
  279. /* 配置MQTT连接超时时间 */
  280. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CONNECT_TIMEOUT_MS, (void *)&time_delay_ms);
  281. /* 配置拨号profile_idx信息(quectel平台必须执行此操作)*/
  282. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PROFILE_IDX, (void *)&pdp);
  283. /* 与MQTT例程不同的是, 这里需要增加创建OTA会话实例的语句 */
  284. ota_handle = aiot_ota_init();
  285. if (NULL == ota_handle) {
  286. goto exit;
  287. }
  288. /* 用以下语句, 把OTA会话和MQTT会话关联起来 */
  289. aiot_ota_setopt(ota_handle, AIOT_OTAOPT_MQTT_HANDLE, mqtt_handle);
  290. /* 用以下语句, 设置OTA会话的数据接收回调, SDK收到OTA相关推送时, 会进入这个回调函数 */
  291. aiot_ota_setopt(ota_handle, AIOT_OTAOPT_RECV_HANDLER, demo_ota_recv_handler);
  292. /* 与服务器建立MQTT连接 */
  293. res = aiot_mqtt_connect(mqtt_handle);
  294. if (res < STATE_SUCCESS) {
  295. uart_printf("aiot_mqtt_connect failed: -0x%04X\r\n", -res);
  296. /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
  297. goto exit;
  298. }
  299. /* 发送请求, 获取云端的远程配置 */
  300. {
  301. char *topic_string = "/sys/a1dhWKuKqX5/cota_basic_demo/thing/config/get";
  302. char *payload_string = "{\"id\":\"123\",\"params\":{\"configScope\":\"product\",\"getType\":\"file\"}}";
  303. res = aiot_mqtt_pub(mqtt_handle, topic_string, (uint8_t *)payload_string, strlen(payload_string), 0);
  304. if (res < STATE_SUCCESS) {
  305. uart_printf("aiot_mqtt_pub failed: -0x%04X\r\n", -res);
  306. /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
  307. goto exit;
  308. }
  309. }
  310. while (1) {
  311. aiot_mqtt_process(mqtt_handle);
  312. res = aiot_mqtt_recv(mqtt_handle);
  313. if (res == STATE_SYS_DEPEND_NWK_CLOSED) {
  314. ql_rtos_task_sleep_s(1);
  315. }
  316. if (NULL != g_dl_handle) {
  317. /* 完成远程配置的接收前, 将mqtt的收包超时调整到100ms, 以减少两次远程配置的下载间隔*/
  318. int32_t ret = aiot_download_recv(g_dl_handle);
  319. timeout_ms = 100;
  320. if (STATE_DOWNLOAD_FINISHED == ret) {
  321. aiot_download_deinit(&g_dl_handle);
  322. /* 完成远程配置的接收后, 将mqtt的收包超时调整回到默认值5000ms */
  323. timeout_ms = 5000;
  324. }
  325. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_TIMEOUT_MS, (void *)&timeout_ms);
  326. }
  327. }
  328. /* 断开MQTT连接, 一般不会运行到这里 */
  329. res = aiot_mqtt_disconnect(mqtt_handle);
  330. if (res < STATE_SUCCESS) {
  331. uart_printf("aiot_mqtt_disconnect failed: -0x%04X\r\n", -res);
  332. goto exit;
  333. }
  334. exit:
  335. while (1) {
  336. /* 销毁MQTT实例, 一般不会运行到这里 */
  337. res = aiot_mqtt_deinit(&mqtt_handle);
  338. if (res < STATE_SUCCESS) {
  339. uart_printf("aiot_mqtt_deinit failed: -0x%04X\r\n", -res);
  340. return;
  341. } else {
  342. break;
  343. }
  344. }
  345. /* 销毁OTA实例, 一般不会运行到这里 */
  346. aiot_ota_deinit(&ota_handle);
  347. return ;
  348. }
  349. #define QL_ALI_TASK_STACK_SIZE 10240
  350. #define QL_ALI_TASK_PRIO APP_PRIORITY_NORMAL
  351. #define QL_ALI_TASK_EVENT_CNT 5
  352. int ql_ali_sdk_cota_test_init(void)
  353. {
  354. QlOSStatus status;
  355. int count = 0;
  356. /* 主循环进入休眠 */
  357. while (count < 10)
  358. {
  359. count++;
  360. ql_rtos_task_sleep_s(1);
  361. uart_printf("ql_ali_sdk_mqtt_client_test_init -0x%04X\n", count);
  362. }
  363. status =ql_rtos_task_create(&ql_alisdk_cota_task_ref, QL_ALI_TASK_STACK_SIZE, APP_PRIORITY_NORMAL, "ali_cota_task", ql_alisdk_cota_task, NULL, QL_ALI_TASK_EVENT_CNT);
  364. if (status != QL_OSI_SUCCESS)
  365. {
  366. uart_printf("ql_ali_sdk_cota_test_init error");
  367. return -1;
  368. }
  369. return 0;
  370. }