shadow_basic_demo.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. * 这个例程适用于`Linux`这类支持pthread的POSIX设备, 它演示了用SDK配置MQTT参数并建立连接, 之后创建2个线程
  3. *
  4. * + 一个线程用于保活长连接
  5. * + 一个线程用于接收消息, 并在有消息到达时进入默认的数据回调, 在连接状态变化时进入事件回调
  6. *
  7. * 接着演示了在MQTT连接上进行设备影子更新, 删除, 拉取等操作, 取消这些代码段落的注释即可观察运行效果
  8. *
  9. * 需要用户关注或修改的部分, 已经用 TODO 在注释中标明
  10. *
  11. */
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include "aiot_state_api.h"
  15. #include "aiot_sysdep_api.h"
  16. #include "aiot_mqtt_api.h"
  17. #include "aiot_shadow_api.h"
  18. #include "ali_demo.h"
  19. #include "ql_api_osi.h"
  20. #include "ql_api_nw.h"
  21. #include "ali_demo.h"
  22. #include "ql_log.h"
  23. #include "ql_api_datacall.h"
  24. #include "sockets.h"
  25. #include "lwip/ip_addr.h"
  26. #include "lwip/ip6_addr.h"
  27. #include "lwip/netdb.h"
  28. #include "lwip/netif.h"
  29. #include "lwip/inet.h"
  30. #include "lwip/tcp.h"
  31. #define QL_SOCKET_LOG_LEVEL QL_LOG_LEVEL_INFO
  32. #define uart_printf(msg, ...) QL_LOG(QL_SOCKET_LOG_LEVEL, "linkSDK ", msg, ##__VA_ARGS__)
  33. #define shadow_profile_idx 1
  34. /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
  35. extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
  36. /* 位于external/ali_ca_cert.c中的服务器证书 */
  37. extern const char *ali_ca_cert;
  38. ql_task_t ql_alisdk_shadow_task_ref;
  39. static ql_task_t ql_alisdk_shadow_process_task_ref;
  40. static ql_task_t ql_alisdk_shadow_recv_task_ref;
  41. static uint8_t g_shadow_process_task_running = 0;
  42. static uint8_t g_shadow_recv_task_running = 0;
  43. static int datacall_satrt(void)
  44. {
  45. int ret = 0;
  46. int i = 0;
  47. ql_data_call_info_s info;
  48. char ip4_addr_str[16] = {0};
  49. uint8_t nSim = 0;
  50. ql_rtos_task_sleep_s(10);
  51. uart_printf("========== socket demo start ==========");
  52. uart_printf("wait for network register done");
  53. while ((ret = ql_network_register_wait(nSim, 120)) != 0 && i < 10)
  54. {
  55. i++;
  56. ql_rtos_task_sleep_s(1);
  57. }
  58. if (ret == 0)
  59. {
  60. i = 0;
  61. uart_printf("====network registered!!!!====");
  62. }
  63. else
  64. {
  65. uart_printf("====network register failure!!!!!====");
  66. goto exit;
  67. }
  68. ql_set_data_call_asyn_mode(nSim, shadow_profile_idx, 0);
  69. uart_printf("===start data call====");
  70. ret = ql_start_data_call(nSim, shadow_profile_idx, QL_PDP_TYPE_IP, "uninet", NULL, NULL, 0);
  71. uart_printf("===data call result:%d", ret);
  72. if (ret != 0)
  73. {
  74. uart_printf("====data call failure!!!!=====");
  75. }
  76. memset(&info, 0x00, sizeof(ql_data_call_info_s));
  77. ret = ql_get_data_call_info(nSim, shadow_profile_idx, &info);
  78. if (ret != 0)
  79. {
  80. uart_printf("ql_get_data_call_info ret: %d", ret);
  81. ql_stop_data_call(nSim, shadow_profile_idx);
  82. goto exit;
  83. }
  84. uart_printf("info->mqtt_profile_idx: %d", info.profile_idx);
  85. uart_printf("info->ip_version: %d", info.ip_version);
  86. uart_printf("info->v4.state: %d", info.v4.state);
  87. inet_ntop(AF_INET, &info.v4.addr.ip, ip4_addr_str, sizeof(ip4_addr_str));
  88. uart_printf("info.v4.addr.ip: %s\r\n", ip4_addr_str);
  89. inet_ntop(AF_INET, &info.v4.addr.pri_dns, ip4_addr_str, sizeof(ip4_addr_str));
  90. uart_printf("info.v4.addr.pri_dns: %s\r\n", ip4_addr_str);
  91. inet_ntop(AF_INET, &info.v4.addr.sec_dns, ip4_addr_str, sizeof(ip4_addr_str));
  92. uart_printf("info.v4.addr.sec_dns: %s\r\n", ip4_addr_str);
  93. return 0;
  94. exit:
  95. return -1;
  96. }
  97. /* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印
  98. *
  99. * 例如: [1577589489.033][LK-0317] shadow_basic_demo&a13FN5TplKq
  100. *
  101. * 上面这条日志的code就是0317(十六进制), code值的定义见core/aiot_state_api.h
  102. *
  103. */
  104. /* 日志回调函数, SDK的日志会从这里输出 */
  105. static int32_t demo_state_logcb(int32_t code, char *message)
  106. {
  107. uart_printf("%s", message);
  108. return 0;
  109. }
  110. /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */
  111. static void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata)
  112. {
  113. switch (event->type) {
  114. /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */
  115. case AIOT_MQTTEVT_CONNECT: {
  116. uart_printf("AIOT_MQTTEVT_CONNECT\n");
  117. }
  118. break;
  119. /* SDK因为网络状况被动断连后, 自动发起重连已成功 */
  120. case AIOT_MQTTEVT_RECONNECT: {
  121. uart_printf("AIOT_MQTTEVT_RECONNECT\n");
  122. }
  123. break;
  124. /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */
  125. case AIOT_MQTTEVT_DISCONNECT: {
  126. char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") :
  127. ("heartbeat disconnect");
  128. uart_printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause);
  129. }
  130. break;
  131. default: {
  132. }
  133. }
  134. }
  135. /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
  136. static void demo_mqtt_process_thread(void *args)
  137. {
  138. int32_t res = STATE_SUCCESS;
  139. while (g_shadow_process_task_running) {
  140. res = aiot_mqtt_process(args);
  141. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  142. break;
  143. }
  144. ql_rtos_task_sleep_s(1);
  145. }
  146. return;
  147. }
  148. /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
  149. static void demo_mqtt_recv_thread(void *args)
  150. {
  151. int32_t res = STATE_SUCCESS;
  152. while (g_shadow_recv_task_running) {
  153. res = aiot_mqtt_recv(args);
  154. if (res < STATE_SUCCESS) {
  155. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  156. break;
  157. }
  158. ql_rtos_task_sleep_s(1);
  159. }
  160. }
  161. return;
  162. }
  163. /* 数据处理回调, 当SDK从网络上收到shadow消息时被调用 */
  164. static void demo_shadow_recv_handler(void *handle, const aiot_shadow_recv_t *recv, void *userdata)
  165. {
  166. uart_printf("demo_shadow_recv_handler, type = %d, productKey = %s, deviceName = %s\r\n",
  167. recv->type, recv->product_key, recv->device_name);
  168. switch (recv->type) {
  169. /* 当设备发送AIOT_SHADOWMSG_UPDATE, AIOT_SHADOWMSG_CLEAN_DESIRED或者AIOT_SHADOWMSG_DELETE_REPORTED消息后, 会收到此应答消息 */
  170. case AIOT_SHADOWRECV_GENERIC_REPLY: {
  171. const aiot_shadow_recv_generic_reply_t *generic_reply = &recv->data.generic_reply;
  172. uart_printf("payload = \"%.*s\", status = %s, timestamp = %ld\r\n",
  173. generic_reply->payload_len,
  174. generic_reply->payload,
  175. generic_reply->status,
  176. (unsigned long)generic_reply->timestamp);
  177. }
  178. break;
  179. /* 当设备在线时, 若用户应用程序调用云端API主动更新设备影子, 设备便会收到此消息 */
  180. case AIOT_SHADOWRECV_CONTROL: {
  181. const aiot_shadow_recv_control_t *control = &recv->data.control;
  182. uart_printf("payload = \"%.*s\", version = %ld\r\n",
  183. control->payload_len,
  184. control->payload,
  185. (unsigned long)control->version);
  186. }
  187. break;
  188. /* 当设备发送AIOT_SHADOWMSG_GET消息主动获取设备影子时, 会收到此消息 */
  189. case AIOT_SHADOWRECV_GET_REPLY: {
  190. const aiot_shadow_recv_get_reply_t *get_reply = &recv->data.get_reply;
  191. uart_printf("payload = \"%.*s\", version = %ld\r\n",
  192. get_reply->payload_len,
  193. get_reply->payload,
  194. (unsigned long)get_reply->version);
  195. }
  196. default:
  197. break;
  198. }
  199. }
  200. /* 发送更新设备影子reported值的请求 */
  201. static int32_t demo_update_shadow(void *shadow_handle, char *reported_data, int64_t version)
  202. {
  203. aiot_shadow_msg_t message;
  204. memset(&message, 0, sizeof(aiot_shadow_msg_t));
  205. message.type = AIOT_SHADOWMSG_UPDATE;
  206. message.data.update.reported = reported_data;
  207. message.data.update.version = version;
  208. return aiot_shadow_send(shadow_handle, &message);
  209. }
  210. /* 发送删除设备影子中特定reported值的请求 */
  211. static int32_t demo_delete_shadow_report(void *shadow_handle, char *reported, int64_t version)
  212. {
  213. aiot_shadow_msg_t message;
  214. memset(&message, 0, sizeof(aiot_shadow_msg_t));
  215. message.type = AIOT_SHADOWMSG_DELETE_REPORTED;
  216. message.data.delete_reporte.reported = reported;
  217. message.data.delete_reporte.version = version;
  218. return aiot_shadow_send(shadow_handle, &message);
  219. }
  220. /* 发送清除设备影子中所有desired值的请求 */
  221. static int32_t demo_clean_shadow_desired(void *shadow_handle, int64_t version)
  222. {
  223. aiot_shadow_msg_t message;
  224. memset(&message, 0, sizeof(aiot_shadow_msg_t));
  225. message.type = AIOT_SHADOWMSG_CLEAN_DESIRED;
  226. message.data.clean_desired.version = version;
  227. return aiot_shadow_send(shadow_handle, &message);
  228. }
  229. /* 发送获取设备影子的请求 */
  230. static int32_t demo_get_shadow(void *shadow_handle)
  231. {
  232. aiot_shadow_msg_t message;
  233. memset(&message, 0, sizeof(aiot_shadow_msg_t));
  234. message.type = AIOT_SHADOWMSG_GET;
  235. return aiot_shadow_send(shadow_handle, &message);
  236. }
  237. static void ql_alisdk_shadow_task(void *arg)
  238. {
  239. int32_t res = STATE_SUCCESS;
  240. void *mqtt_handle = NULL;
  241. void *shadow_handle = NULL;
  242. char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
  243. char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
  244. uint16_t port = 1883; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
  245. aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
  246. /* TODO: 替换为自己设备的三元组 */
  247. char *product_key = "a1TSu2F29co";
  248. char *device_name = "000001";
  249. char *device_secret = "bd220c3a9c6a5b3f5921485d091497e1";
  250. /*执行拨号操作,设备联网*/
  251. if(datacall_satrt() != 0)
  252. goto exit;
  253. /* 配置SDK的底层依赖 */
  254. aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
  255. /* 配置SDK的日志输出 */
  256. aiot_state_set_logcb(demo_state_logcb);
  257. /* 创建SDK的安全凭据, 用于建立TLS连接 */
  258. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  259. cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
  260. cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
  261. cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
  262. cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
  263. cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
  264. /* 创建1个MQTT客户端实例并内部初始化默认参数 */
  265. mqtt_handle = aiot_mqtt_init();
  266. if (mqtt_handle == NULL) {
  267. uart_printf("aiot_mqtt_init failed\n");
  268. goto exit;
  269. }
  270. snprintf(host, 100, "%s.%s", product_key, url);
  271. /* 配置MQTT服务器地址 */
  272. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
  273. /* 配置MQTT服务器端口 */
  274. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
  275. /* 配置设备productKey */
  276. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
  277. /* 配置设备deviceName */
  278. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
  279. /* 配置设备deviceSecret */
  280. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
  281. /* 配置网络连接的安全凭据, 上面已经创建好了 */
  282. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
  283. /* 配置MQTT事件回调函数 */
  284. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
  285. /* 配置MQTT连接超时时间 */
  286. int time_delay_ms = 5000;
  287. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CONNECT_TIMEOUT_MS, (void *)&time_delay_ms);
  288. /* 配置拨号profile_idx信息(quectel平台必须执行此操作)*/
  289. uint16_t pdp = shadow_profile_idx;
  290. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PROFILE_IDX, (void *)&pdp);
  291. /* 创建1个shadow客户端实例并内部初始化默认参数 */
  292. shadow_handle = aiot_shadow_init();
  293. if (shadow_handle == NULL) {
  294. uart_printf("aiot_shadow_init failed\n");
  295. goto exit;
  296. }
  297. /* 配置MQTT实例句柄 */
  298. aiot_shadow_setopt(shadow_handle, AIOT_SHADOWOPT_MQTT_HANDLE, mqtt_handle);
  299. /* 配置SHADOW默认消息接收回调函数 */
  300. aiot_shadow_setopt(shadow_handle, AIOT_SHADOWOPT_RECV_HANDLER, (void *)demo_shadow_recv_handler);
  301. /* 与服务器建立MQTT连接 */
  302. res = aiot_mqtt_connect(mqtt_handle);
  303. if (res < STATE_SUCCESS) {
  304. /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
  305. aiot_mqtt_deinit(&mqtt_handle);
  306. uart_printf("aiot_mqtt_connect failed: -0x%04X\n", -res);
  307. goto exit;
  308. }
  309. /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */
  310. g_shadow_process_task_running = 1;
  311. res = ql_rtos_task_create(&ql_alisdk_shadow_process_task_ref, 24576, 24, "client_proc", demo_mqtt_process_thread, (void *)mqtt_handle, 5);
  312. if (res < 0) {
  313. uart_printf("pthread_create demo_mqtt_process_thread failed: %d\n", res);
  314. goto exit;
  315. }
  316. /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
  317. g_shadow_recv_task_running = 1;
  318. res = ql_rtos_task_create(&ql_alisdk_shadow_recv_task_ref, 24576, 25, "recv_test", demo_mqtt_recv_thread, (void *)mqtt_handle, 5);
  319. if (res < 0) {
  320. uart_printf("pthread_create demo_mqtt_recv_thread failed: %d\n", res);
  321. goto exit;
  322. }
  323. /* 主循环进入休眠 */
  324. while (1) {
  325. /* TODO: 以下代码演示了发送请求拉取设备影子, 设备影子将在demo_shadow_recv_handler回调函数中返回, 用户可取消注释观察演示效果 */
  326. res = demo_get_shadow(shadow_handle);
  327. if (res < 0) {
  328. uart_printf("demo_get_shadow failed, res = -0x%04x\r\n", -res);
  329. }
  330. ql_rtos_task_sleep_s(2);
  331. /* TODO: 以下代码演示了如何清除设备影子中的desired值, 同时将version设置为1, 用户可取消注释观察演示效果 */
  332. res = demo_clean_shadow_desired(shadow_handle, 1);
  333. if (res < 0) {
  334. uart_printf("demo_clean_shadow_desired failed, res = -0x%04x\r\n", -res);
  335. }
  336. ql_rtos_task_sleep_s(2);
  337. /* TODO: 以下代码演示了如何删除设备影子中特定的reported值, 同时将version设置为2, 用户可取消注释观察演示效果 */
  338. res = demo_delete_shadow_report(shadow_handle, "{\"LightSwitch\":\"null\"}", 2);
  339. if (res < 0) {
  340. uart_printf("demo_delete_shadow_report failed, res = -0x%04x\r\n", -res);
  341. }
  342. ql_rtos_task_sleep_s(2);
  343. /* TODO: 以下代码演示了如何更新设备影子中的reported值, 同时将version重置为0, 用户可取消注释观察演示效果 */
  344. res = demo_update_shadow(shadow_handle, "{\"LightSwitch\":1}", 0);
  345. if (res < 0) {
  346. uart_printf("demo_delete_shadow_report failed, res = -0x%04x\r\n", -res);
  347. }
  348. ql_rtos_task_sleep_s(10);
  349. }
  350. /* 断开MQTT连接, 一般不会运行到这里 */
  351. res = aiot_mqtt_disconnect(mqtt_handle);
  352. if (res < STATE_SUCCESS) {
  353. aiot_mqtt_deinit(&mqtt_handle);
  354. uart_printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res);
  355. goto exit;
  356. }
  357. /* 销毁SHADOW实例, 一般不会运行到这里 */
  358. res = aiot_shadow_deinit(&shadow_handle);
  359. if (res < STATE_SUCCESS) {
  360. uart_printf("aiot_shadow_deinit failed: -0x%04X\n", -res);
  361. goto exit;
  362. }
  363. /* 销毁MQTT实例, 一般不会运行到这里 */
  364. res = aiot_mqtt_deinit(&mqtt_handle);
  365. if (res < STATE_SUCCESS) {
  366. uart_printf("aiot_mqtt_deinit failed: -0x%04X\n", -res);
  367. goto exit;
  368. }
  369. g_shadow_process_task_running = 0;
  370. g_shadow_recv_task_running = 0;
  371. ql_rtos_task_delete(ql_alisdk_shadow_process_task_ref);
  372. ql_rtos_task_delete(ql_alisdk_shadow_recv_task_ref);
  373. return ;
  374. exit:
  375. ql_rtos_task_delete(NULL);
  376. }
  377. #define QL_ALI_TASK_STACK_SIZE 10240
  378. #define QL_ALI_TASK_PRIO APP_PRIORITY_NORMAL
  379. #define QL_ALI_TASK_EVENT_CNT 5
  380. int ql_ali_sdk_shadow_test_init(void)
  381. {
  382. QlOSStatus status;
  383. int count = 0;
  384. /* 主循环进入休眠 */
  385. while (count < 10)
  386. {
  387. count++;
  388. ql_rtos_task_sleep_s(1);
  389. uart_printf("ql_ali_sdk_mqtt_client_test_init -0x%04X\n", count);
  390. }
  391. status =ql_rtos_task_create(&ql_alisdk_shadow_task_ref, QL_ALI_TASK_STACK_SIZE, APP_PRIORITY_NORMAL, "shadow_task", ql_alisdk_shadow_task, NULL, QL_ALI_TASK_EVENT_CNT);
  392. if (status != QL_OSI_SUCCESS)
  393. {
  394. uart_printf("ql_ali_sdk_devinfo_test_init error");
  395. return -1;
  396. }
  397. return 0;
  398. }