das_basic_demo.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /*
  2. * 这个例程适用于`Linux`这类支持pthread的POSIX设备, 它演示了用SDK配置MQTT参数并建立连接, 之后创建2个线程
  3. *
  4. * + 一个线程用于保活长连接
  5. * + 一个线程用于接收消息, 并在有消息到达时进入默认的数据回调, 在连接状态变化时进入事件回调
  6. *
  7. * 接着在MQTT连接上发送NTP查询请求, 如果云平台的回应报文到达, 从接收线程会调用NTP消息处理的回调函数, 把对时后的本地时间打印出来
  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_das_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 das_mqtt_profile_idx 1
  34. /* 位于portfiles/aiot_port文件夹下的系统适配函数集合 */
  35. extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
  36. ql_task_t ql_alisdk_das_task_ref;
  37. static ql_task_t g_das_mqtt_process_task_ref;
  38. static ql_task_t g_das_mqtt_recv_task_ref;
  39. static uint8_t g_das_mqtt_process_task_ref_running = 0;
  40. static uint8_t g_das_mqtt_recv_task_ref_running = 0;
  41. static int datacall_satrt(void)
  42. {
  43. int ret = 0;
  44. int i = 0;
  45. ql_data_call_info_s info;
  46. char ip4_addr_str[16] = {0};
  47. uint8_t nSim = 0;
  48. ql_rtos_task_sleep_s(10);
  49. uart_printf("========== socket demo start ==========");
  50. uart_printf("wait for network register done");
  51. while ((ret = ql_network_register_wait(nSim, 120)) != 0 && i < 10)
  52. {
  53. i++;
  54. ql_rtos_task_sleep_s(1);
  55. }
  56. if (ret == 0)
  57. {
  58. i = 0;
  59. uart_printf("====network registered!!!!====");
  60. }
  61. else
  62. {
  63. uart_printf("====network register failure!!!!!====");
  64. goto exit;
  65. }
  66. ql_set_data_call_asyn_mode(nSim, das_mqtt_profile_idx, 0);
  67. uart_printf("===start data call====");
  68. ret = ql_start_data_call(nSim, das_mqtt_profile_idx, QL_PDP_TYPE_IP, "uninet", NULL, NULL, 0);
  69. uart_printf("===data call result:%d", ret);
  70. if (ret != 0)
  71. {
  72. uart_printf("====data call failure!!!!=====");
  73. }
  74. memset(&info, 0x00, sizeof(ql_data_call_info_s));
  75. ret = ql_get_data_call_info(nSim, das_mqtt_profile_idx, &info);
  76. if (ret != 0)
  77. {
  78. uart_printf("ql_get_data_call_info ret: %d", ret);
  79. ql_stop_data_call(nSim, das_mqtt_profile_idx);
  80. goto exit;
  81. }
  82. uart_printf("info->mqtt_profile_idx: %d", info.profile_idx);
  83. uart_printf("info->ip_version: %d", info.ip_version);
  84. uart_printf("info->v4.state: %d", info.v4.state);
  85. inet_ntop(AF_INET, &info.v4.addr.ip, ip4_addr_str, sizeof(ip4_addr_str));
  86. uart_printf("info.v4.addr.ip: %s\r\n", ip4_addr_str);
  87. inet_ntop(AF_INET, &info.v4.addr.pri_dns, ip4_addr_str, sizeof(ip4_addr_str));
  88. uart_printf("info.v4.addr.pri_dns: %s\r\n", ip4_addr_str);
  89. inet_ntop(AF_INET, &info.v4.addr.sec_dns, ip4_addr_str, sizeof(ip4_addr_str));
  90. uart_printf("info.v4.addr.sec_dns: %s\r\n", ip4_addr_str);
  91. return 0;
  92. exit:
  93. return -1;
  94. }
  95. /* TODO: 如果要关闭日志, 就把这个函数实现为空, 如果要减少日志, 可根据code选择不打印
  96. *
  97. * 例如: [1581501698.455][LK-0309] pub: /ext/ntp/a13FN5TplKq/ntp_basic_demo/request
  98. *
  99. * 上面这条日志的code就是0309(十六进制), code值的定义见core/aiot_state_api.h
  100. *
  101. */
  102. /* 日志回调函数, SDK的日志会从这里输出 */
  103. static int32_t demo_state_logcb(int32_t code, char *message)
  104. {
  105. uart_printf("%s", message);
  106. return 0;
  107. }
  108. /* MQTT事件回调函数, 当网络连接/重连/断开时被触发, 事件定义见core/aiot_mqtt_api.h */
  109. static void demo_mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event, void *userdata)
  110. {
  111. switch (event->type) {
  112. /* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功 */
  113. case AIOT_MQTTEVT_CONNECT: {
  114. uart_printf("AIOT_MQTTEVT_CONNECT\n");
  115. }
  116. break;
  117. /* SDK因为网络状况被动断连后, 自动发起重连已成功 */
  118. case AIOT_MQTTEVT_RECONNECT: {
  119. uart_printf("AIOT_MQTTEVT_RECONNECT\n");
  120. }
  121. break;
  122. /* SDK因为网络的状况而被动断开了连接, network是底层读写失败, heartbeat是没有按预期得到服务端心跳应答 */
  123. case AIOT_MQTTEVT_DISCONNECT: {
  124. char *cause = (event->data.disconnect == AIOT_MQTTDISCONNEVT_NETWORK_DISCONNECT) ? ("network disconnect") :
  125. ("heartbeat disconnect");
  126. uart_printf("AIOT_MQTTEVT_DISCONNECT: %s\n", cause);
  127. }
  128. break;
  129. default: {
  130. }
  131. }
  132. }
  133. /* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时, 且无对应用户回调处理时被调用 */
  134. static void demo_mqtt_default_recv_handler(void *handle, const aiot_mqtt_recv_t *packet, void *userdata)
  135. {
  136. switch (packet->type) {
  137. case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: {
  138. uart_printf("heartbeat response\n");
  139. }
  140. break;
  141. case AIOT_MQTTRECV_SUB_ACK: {
  142. uart_printf("suback, res: -0x%04X, packet id: %d, max qos: %d\n",
  143. -packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos);
  144. }
  145. break;
  146. case AIOT_MQTTRECV_PUB: {
  147. uart_printf("pub, qos: %d, topic: %d %s\n", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
  148. uart_printf("pub, payload: %d %s\n", packet->data.pub.payload_len, packet->data.pub.payload);
  149. }
  150. break;
  151. case AIOT_MQTTRECV_PUB_ACK: {
  152. uart_printf("puback, packet id: %d\n", packet->data.pub_ack.packet_id);
  153. }
  154. break;
  155. default: {
  156. }
  157. }
  158. }
  159. /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
  160. static void demo_mqtt_process_thread(void *args)
  161. {
  162. int32_t res = STATE_SUCCESS;
  163. while (g_das_mqtt_process_task_ref_running) {
  164. res = aiot_mqtt_process(args);
  165. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  166. break;
  167. }
  168. ql_rtos_task_sleep_s(1);
  169. }
  170. return;
  171. }
  172. /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
  173. static void demo_mqtt_recv_thread(void *args)
  174. {
  175. int32_t res = STATE_SUCCESS;
  176. while (g_das_mqtt_recv_task_ref_running) {
  177. res = aiot_mqtt_recv(args);
  178. if (res < STATE_SUCCESS) {
  179. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  180. break;
  181. }
  182. ql_rtos_task_sleep_s(1);
  183. }
  184. }
  185. return;
  186. }
  187. static int32_t demo_mqtt_start(void **handle)
  188. {
  189. int32_t res = STATE_SUCCESS;
  190. void *mqtt_handle = NULL;
  191. char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
  192. char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
  193. uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
  194. aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
  195. /* TODO: 替换为自己设备的三元组 */
  196. char *product_key = "a1TSu2F29co";
  197. char *device_name = "000001";
  198. char *device_secret = "bd220c3a9c6a5b3f5921485d091497e1";
  199. /*执行拨号操作,设备联网*/
  200. if(datacall_satrt()!=0)
  201. return -1;
  202. /* 配置SDK的底层依赖 */
  203. aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
  204. /* 配置SDK的日志输出 */
  205. aiot_state_set_logcb(demo_state_logcb);
  206. /* 创建SDK的安全凭据, 用于建立TLS连接 */
  207. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  208. cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE; /* 使用RSA证书校验MQTT服务端 */
  209. cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
  210. cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
  211. /* 创建1个MQTT客户端实例并内部初始化默认参数 */
  212. mqtt_handle = aiot_mqtt_init();
  213. if (mqtt_handle == NULL) {
  214. uart_printf("aiot_mqtt_init failed\n");
  215. return -1;
  216. }
  217. /* TODO: 如果以下代码不被注释, 则例程会用TCP而不是TLS连接云平台 */
  218. /*
  219. {
  220. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  221. cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE;
  222. }
  223. */
  224. snprintf(host, 100, "%s.%s", product_key, url);
  225. /* 配置MQTT服务器地址 */
  226. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
  227. /* 配置MQTT服务器端口 */
  228. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
  229. int pdp = das_mqtt_profile_idx;
  230. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PROFILE_IDX, (void *)&pdp);
  231. /* 配置设备productKey */
  232. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
  233. /* 配置设备deviceName */
  234. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
  235. /* 配置设备deviceSecret */
  236. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
  237. /* 配置网络连接的安全凭据, 上面已经创建好了 */
  238. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
  239. /* 配置MQTT默认消息接收回调函数 */
  240. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)demo_mqtt_default_recv_handler);
  241. /* 配置MQTT事件回调函数 */
  242. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
  243. /* 配置MQTT连接超时时间 */
  244. int time_delay_ms = 5000;
  245. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CONNECT_TIMEOUT_MS, (void *)&time_delay_ms);
  246. /* 与服务器建立MQTT连接 */
  247. res = aiot_mqtt_connect(mqtt_handle);
  248. if (res < STATE_SUCCESS) {
  249. /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
  250. aiot_mqtt_deinit(&mqtt_handle);
  251. uart_printf("aiot_mqtt_connect failed: -0x%04X\n", -res);
  252. return -1;
  253. }
  254. /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */
  255. g_das_mqtt_process_task_ref_running = 1;
  256. res = ql_rtos_task_create(&g_das_mqtt_process_task_ref, 24000, 24, "client_proc", demo_mqtt_process_thread, (void *)mqtt_handle, 5);
  257. if (res < 0) {
  258. uart_printf("pthread_create demo_mqtt_process_thread failed: %d\n", res);
  259. aiot_mqtt_deinit(&mqtt_handle);
  260. return -1;
  261. }
  262. /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
  263. g_das_mqtt_recv_task_ref_running = 1;
  264. res = ql_rtos_task_create(&g_das_mqtt_recv_task_ref, 24000, 25, "recv_test", demo_mqtt_recv_thread, (void*)mqtt_handle, 5);
  265. if (res < 0) {
  266. uart_printf("pthread_create demo_mqtt_recv_thread failed: %d\n", res);
  267. g_das_mqtt_process_task_ref_running = 0;
  268. aiot_mqtt_deinit(&mqtt_handle);
  269. return -1;
  270. }
  271. *handle = mqtt_handle;
  272. return 0;
  273. }
  274. int32_t demo_mqtt_stop(void **handle)
  275. {
  276. int32_t res = STATE_SUCCESS;
  277. void *mqtt_handle = NULL;
  278. mqtt_handle = *handle;
  279. g_das_mqtt_process_task_ref_running = 0;
  280. g_das_mqtt_recv_task_ref_running = 0;
  281. ql_rtos_task_delete(g_das_mqtt_process_task_ref);
  282. ql_rtos_task_delete(g_das_mqtt_recv_task_ref);
  283. /* 断开MQTT连接 */
  284. res = aiot_mqtt_disconnect(mqtt_handle);
  285. if (res < STATE_SUCCESS) {
  286. aiot_mqtt_deinit(&mqtt_handle);
  287. uart_printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res);
  288. return -1;
  289. }
  290. /* 销毁MQTT实例 */
  291. res = aiot_mqtt_deinit(&mqtt_handle);
  292. if (res < STATE_SUCCESS) {
  293. uart_printf("aiot_mqtt_deinit failed: -0x%04X\n", -res);
  294. return -1;
  295. }
  296. return 0;
  297. }
  298. static void ali_das_test(void *arg)
  299. {
  300. int32_t res = STATE_SUCCESS;
  301. void *mqtt_handle = NULL, *das_handle = NULL;
  302. uart_printf("==========%s entry !!==============\r\n",__func__);
  303. /* 建立MQTT连接, 并开启保活线程和接收线程 */
  304. res = demo_mqtt_start(&mqtt_handle);
  305. if (res < 0) {
  306. uart_printf("demo_mqtt_start failed\n");
  307. return;
  308. }
  309. /* 创建1个ntp客户端实例并内部初始化默认参数 */
  310. das_handle = aiot_das_init();
  311. if (das_handle == NULL) {
  312. demo_mqtt_stop(&mqtt_handle);
  313. uart_printf("aiot_das_init failed\n");
  314. return;
  315. }
  316. res = aiot_das_setopt(das_handle, AIOT_DASOPT_MQTT_HANDLE, mqtt_handle);
  317. if (res < STATE_SUCCESS) {
  318. uart_printf("aiot_das_setopt AIOT_DASOPT_MQTT_HANDLE failed, res: -0x%04X\n", -res);
  319. aiot_das_deinit(&das_handle);
  320. demo_mqtt_stop(&mqtt_handle);
  321. return;
  322. }
  323. res = aiot_das_setopt(das_handle, AIOT_DASOPT_SET_FIRMWARE_VERSION, (void *)"mzf_firmware_version");
  324. if (res < STATE_SUCCESS) {
  325. uart_printf("aiot_das_setopt AIOT_DASOPT_SET_FIRMWARE_VERSION failed, res: -0x%04X\n", -res);
  326. }
  327. while (1) {
  328. aiot_das_stepping(das_handle);
  329. ql_rtos_task_sleep_s(1);
  330. }
  331. /* 销毁NTP实例, 一般不会运行到这里 */
  332. res = aiot_das_deinit(&das_handle);
  333. if (res < STATE_SUCCESS) {
  334. demo_mqtt_stop(&mqtt_handle);
  335. uart_printf("aiot_das_deinit failed: -0x%04X\n", -res);
  336. return;
  337. }
  338. /* 销毁MQTT实例, 退出线程, 一般不会运行到这里 */
  339. res = demo_mqtt_stop(&mqtt_handle);
  340. if (res < 0) {
  341. uart_printf("demo_start_stop failed\n");
  342. return;
  343. }
  344. return;
  345. }
  346. #define QL_ALI_TASK_STACK_SIZE 10240
  347. #define QL_ALI_TASK_PRIO APP_PRIORITY_NORMAL
  348. #define QL_ALI_TASK_EVENT_CNT 5
  349. int ql_ali_sdk_das_test_init(void)
  350. {
  351. QlOSStatus status;
  352. int count = 0;
  353. /* 主体进入休眠 */
  354. while (count < 10)
  355. {
  356. count++;
  357. ql_rtos_task_sleep_s(1);
  358. uart_printf("ql_ali_sdk_mqtt_client_test_init -0x%04X\n", count);
  359. }
  360. status =ql_rtos_task_create(&ql_alisdk_das_task_ref, QL_ALI_TASK_STACK_SIZE, APP_PRIORITY_NORMAL, "das_test", ali_das_test, NULL, QL_ALI_TASK_EVENT_CNT);
  361. if (status != QL_OSI_SUCCESS)
  362. {
  363. uart_printf("ql_ali_sdk_das_test_init error");
  364. return -1;
  365. }
  366. return 0;
  367. }