logpost_basic_demo.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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_logpost_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 logpost_model_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_logpost_task_ref;
  39. static ql_task_t ql_alisdk_logpost_process_task_ref;
  40. static ql_task_t ql_alisdk_logpost_recv_task_ref;
  41. static uint8_t g_logpost_process_task_running = 0;
  42. static uint8_t g_logpost_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, logpost_model_profile_idx, 0);
  69. uart_printf("===start data call====");
  70. ret = ql_start_data_call(nSim, logpost_model_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, logpost_model_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, logpost_model_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. * 例如: [1581501698.455][LK-0309] pub: /sys/a13FN5TplKq/logpost_basic_demo/thing/deviceinfo/update
  100. *
  101. * 上面这条日志的code就是0309(十六进制), code值的定义见core/aiot_state_api.h
  102. *
  103. */
  104. /* 日志回调函数, SDK的日志会从这里输出, 禁止在此函数中调用SDK API */
  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\r\n");
  117. }
  118. break;
  119. /* SDK因为网络状况被动断连后, 自动发起重连已成功 */
  120. case AIOT_MQTTEVT_RECONNECT: {
  121. uart_printf("AIOT_MQTTEVT_RECONNECT\r\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\r\n", cause);
  129. }
  130. break;
  131. default: {
  132. }
  133. }
  134. }
  135. /* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时, 且无对应用户回调处理时被调用 */
  136. static void demo_mqtt_default_recv_handler(void *handle, const aiot_mqtt_recv_t *packet, void *userdata)
  137. {
  138. switch (packet->type) {
  139. case AIOT_MQTTRECV_HEARTBEAT_RESPONSE: {
  140. uart_printf("heartbeat response\r\n");
  141. }
  142. break;
  143. case AIOT_MQTTRECV_SUB_ACK: {
  144. uart_printf("suback, res: -0x%04X, packet id: %d, max qos: %d\r\n",
  145. -packet->data.sub_ack.res, packet->data.sub_ack.packet_id, packet->data.sub_ack.max_qos);
  146. }
  147. break;
  148. case AIOT_MQTTRECV_PUB: {
  149. uart_printf("pub, qos: %d, topic: %d %s\r\n", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
  150. uart_printf("pub, payload: %d %s\r\n", packet->data.pub.payload_len, packet->data.pub.payload);
  151. }
  152. break;
  153. case AIOT_MQTTRECV_PUB_ACK: {
  154. uart_printf("puback, packet id: %d\r\n", packet->data.pub_ack.packet_id);
  155. }
  156. break;
  157. default: {
  158. }
  159. }
  160. }
  161. /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
  162. static void demo_mqtt_process_thread(void *args)
  163. {
  164. int32_t res = STATE_SUCCESS;
  165. while (g_logpost_process_task_running) {
  166. res = aiot_mqtt_process(args);
  167. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  168. break;
  169. }
  170. ql_rtos_task_sleep_s(1);
  171. }
  172. return;
  173. }
  174. /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
  175. static void demo_mqtt_recv_thread(void *args)
  176. {
  177. int32_t res = STATE_SUCCESS;
  178. while (g_logpost_recv_task_running) {
  179. res = aiot_mqtt_recv(args);
  180. if (res < STATE_SUCCESS) {
  181. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  182. break;
  183. }
  184. ql_rtos_task_sleep_s(1);
  185. }
  186. }
  187. return;
  188. }
  189. static int32_t demo_mqtt_start(void **handle, char *product_key, char *device_name, char *device_secret)
  190. {
  191. int32_t res = STATE_SUCCESS;
  192. void *mqtt_handle = NULL;
  193. char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
  194. char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
  195. uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
  196. aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
  197. /*执行拨号操作,设备联网*/
  198. if(datacall_satrt() != 0)
  199. return -1;
  200. /* 配置SDK的底层依赖 */
  201. aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
  202. /* 配置SDK的日志输出 */
  203. aiot_state_set_logcb(demo_state_logcb);
  204. /* 创建SDK的安全凭据, 用于建立TLS连接 */
  205. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  206. cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
  207. cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
  208. cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
  209. cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
  210. cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
  211. /* 创建1个MQTT客户端实例并内部初始化默认参数 */
  212. mqtt_handle = aiot_mqtt_init();
  213. if (mqtt_handle == NULL) {
  214. uart_printf("aiot_mqtt_init failed\r\n");
  215. return -1;
  216. }
  217. /* 如果以下代码不被注释, 则例程会用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. /* 配置设备productKey */
  230. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
  231. /* 配置设备deviceName */
  232. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
  233. /* 配置设备deviceSecret */
  234. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
  235. /* 配置网络连接的安全凭据, 上面已经创建好了 */
  236. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
  237. /* 配置MQTT默认消息接收回调函数 */
  238. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)demo_mqtt_default_recv_handler);
  239. /* 配置MQTT事件回调函数 */
  240. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
  241. /* 配置MQTT连接超时时间 */
  242. int time_delay_ms = 5000;
  243. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CONNECT_TIMEOUT_MS, (void *)&time_delay_ms);
  244. /* 配置拨号profile_idx信息(quectel平台必须执行此操作)*/
  245. int pdp = logpost_model_profile_idx;
  246. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PROFILE_IDX, (void *)&pdp);
  247. /* 与服务器建立MQTT连接 */
  248. res = aiot_mqtt_connect(mqtt_handle);
  249. if (res < STATE_SUCCESS) {
  250. /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
  251. aiot_mqtt_deinit(&mqtt_handle);
  252. uart_printf("aiot_mqtt_connect failed: -0x%04X\r\n", -res);
  253. return -1;
  254. }
  255. /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */
  256. g_logpost_process_task_running = 1;
  257. res = ql_rtos_task_create(&ql_alisdk_logpost_process_task_ref, 24576, 24, "client_task", demo_mqtt_process_thread, (void *)mqtt_handle, 5);
  258. if (res < 0) {
  259. uart_printf("pthread_create demo_mqtt_process_thread failed: %d\r\n", res);
  260. aiot_mqtt_deinit(&mqtt_handle);
  261. return -1;
  262. }
  263. /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
  264. g_logpost_recv_task_running = 1;
  265. res = ql_rtos_task_create(&ql_alisdk_logpost_recv_task_ref, 24576, 25, "recv_task", demo_mqtt_recv_thread, (void *)mqtt_handle, 5);
  266. if (res < 0) {
  267. uart_printf("pthread_create demo_mqtt_recv_thread failed: %d\r\n", res);
  268. g_logpost_process_task_running = 0;
  269. ql_rtos_task_delete(ql_alisdk_logpost_process_task_ref);
  270. aiot_mqtt_deinit(&mqtt_handle);
  271. return -1;
  272. }
  273. *handle = mqtt_handle;
  274. return 0;
  275. }
  276. static int32_t demo_mqtt_stop(void **handle)
  277. {
  278. int32_t res = STATE_SUCCESS;
  279. void *mqtt_handle = NULL;
  280. mqtt_handle = *handle;
  281. g_logpost_process_task_running = 0;
  282. g_logpost_recv_task_running = 0;
  283. ql_rtos_task_delete(ql_alisdk_logpost_process_task_ref);
  284. ql_rtos_task_delete(ql_alisdk_logpost_recv_task_ref);
  285. /* 断开MQTT连接 */
  286. res = aiot_mqtt_disconnect(mqtt_handle);
  287. if (res < STATE_SUCCESS) {
  288. aiot_mqtt_deinit(&mqtt_handle);
  289. uart_printf("aiot_mqtt_disconnect failed: -0x%04X\r\n", -res);
  290. return -1;
  291. }
  292. /* 销毁MQTT实例 */
  293. res = aiot_mqtt_deinit(&mqtt_handle);
  294. if (res < STATE_SUCCESS) {
  295. uart_printf("aiot_mqtt_deinit failed: -0x%04X\r\n", -res);
  296. return -1;
  297. }
  298. return 0;
  299. }
  300. /* 事件处理回调, 用户可通过此回调获取日志上报通道的开关状态 */
  301. static void demo_logpost_event_handler(void *handle, const aiot_logpost_event_t *event, void *userdata)
  302. {
  303. switch (event->type) {
  304. /* 日志配置事件, 当设备连云成功或者用户在控制台页面控制日志开关时会收到此事件 */
  305. case AIOT_LOGPOSTEVT_CONFIG_DATA: {
  306. uart_printf("log switch state is: %d\r\n", event->data.config_data.on_off);
  307. }
  308. default:
  309. break;
  310. }
  311. }
  312. /* 上报日志到云端 */
  313. static void demo_send_log(void *handle, char *log)
  314. {
  315. int32_t res = 0;
  316. aiot_logpost_msg_t msg;
  317. memset(&msg, 0, sizeof(aiot_logpost_msg_t));
  318. msg.timestamp = 0; /* 单位为ms的时间戳, 填写0则SDK将使用当前的时间戳 */
  319. msg.loglevel = AIOT_LOGPOST_LEVEL_DEBUG; /* 日志级别 */
  320. msg.module_name = "APP"; /* 日志对应的模块 */
  321. msg.code = 200; /* 状态码 */
  322. msg.msg_id = 0; /* 云端下行报文的消息标示符, 若无对应消息可直接填0 */
  323. msg.content = log; /* 日志内容 */
  324. res = aiot_logpost_send(handle, &msg);
  325. if (res < 0) {
  326. uart_printf("aiot_logpost_send failed: -0x%04X\r\n", -res);
  327. }
  328. }
  329. static void ql_alisdk_logpost_task(void *arg)
  330. {
  331. int32_t res = STATE_SUCCESS;
  332. /* TODO: 替换为自己设备的三元组 */
  333. char *product_key = "a1TSu2F29co";
  334. char *device_name = "000001";
  335. char *device_secret = "bd220c3a9c6a5b3f5921485d091497e1";
  336. void *mqtt_handle = NULL, *logpost_handle = NULL;
  337. /* 建立MQTT连接, 并开启保活线程和接收线程 */
  338. res = demo_mqtt_start(&mqtt_handle, product_key, device_name, device_secret);
  339. if (res < 0) {
  340. uart_printf("demo_mqtt_start failed\r\n");
  341. goto exit;
  342. }
  343. /* 创建1个logpost客户端实例并内部初始化默认参数 */
  344. logpost_handle = aiot_logpost_init();
  345. if (logpost_handle == NULL) {
  346. demo_mqtt_stop(&mqtt_handle);
  347. uart_printf("aiot_logpost_init failed\r\n");
  348. goto exit;
  349. }
  350. /* 配置logpost会话, 把它和MQTT会话的句柄关联起来 */
  351. res = aiot_logpost_setopt(logpost_handle, AIOT_LOGPOSTOPT_MQTT_HANDLE, mqtt_handle);
  352. if (res < STATE_SUCCESS) {
  353. uart_printf("aiot_logpost_setopt AIOT_LOGPOSTOPT_MQTT_HANDLE failed, res: -0x%04X\r\n", -res);
  354. aiot_logpost_deinit(&logpost_handle);
  355. demo_mqtt_stop(&mqtt_handle);
  356. goto exit;
  357. }
  358. res = aiot_logpost_setopt(logpost_handle, AIOT_LOGPOSTOPT_EVENT_HANDLER, (void *)demo_logpost_event_handler);
  359. if (res < STATE_SUCCESS) {
  360. uart_printf("aiot_logpost_setopt AIOT_LOGPOSTOPT_EVENT_HANDLER failed, res: -0x%04X\r\n", -res);
  361. aiot_logpost_deinit(&logpost_handle);
  362. demo_mqtt_stop(&mqtt_handle);
  363. goto exit;
  364. }
  365. /* 主线程进入休眠, 等云平台的logpost回应到达时, 接收线程会调用 demo_logpost_recv_handler() */
  366. while (1) {
  367. ql_rtos_task_sleep_s(10);
  368. /* TODO: 用户可取消注释上报日志到云端, 注意: 日志模块完成初始化后上报通道默认为关闭状态, 日志模块会在收到设备建连内部事件后立即同步云端控制台的开关状态。*/
  369. demo_send_log(logpost_handle, "log in while(1)");
  370. }
  371. /* 销毁logpost实例, 一般不会运行到这里 */
  372. res = aiot_logpost_deinit(&logpost_handle);
  373. if (res < STATE_SUCCESS) {
  374. demo_mqtt_stop(&mqtt_handle);
  375. uart_printf("aiot_logpost_deinit failed: -0x%04X\r\n", -res);
  376. goto exit;
  377. }
  378. /* 销毁MQTT实例, 退出线程, 一般不会运行到这里 */
  379. res = demo_mqtt_stop(&mqtt_handle);
  380. if (res < 0) {
  381. uart_printf("demo_start_stop failed\r\n");
  382. goto exit;
  383. }
  384. return ;
  385. exit:
  386. ql_rtos_task_delete(NULL);
  387. }
  388. #define QL_ALI_TASK_STACK_SIZE 10240
  389. #define QL_ALI_TASK_PRIO APP_PRIORITY_NORMAL
  390. #define QL_ALI_TASK_EVENT_CNT 5
  391. int ql_ali_sdk_logpost_test_init(void)
  392. {
  393. QlOSStatus status;
  394. int count = 0;
  395. /* 主循环进入休眠 */
  396. while (count < 10)
  397. {
  398. count++;
  399. ql_rtos_task_sleep_s(1);
  400. uart_printf("ql_ali_sdk_mqtt_client_test_init -0x%04X\n", count);
  401. }
  402. status =ql_rtos_task_create(&ql_alisdk_logpost_task_ref, QL_ALI_TASK_STACK_SIZE, APP_PRIORITY_NORMAL, "log_task", ql_alisdk_logpost_task, NULL, QL_ALI_TASK_EVENT_CNT);
  403. if (status != QL_OSI_SUCCESS)
  404. {
  405. uart_printf("ql_ali_sdk_devinfo_test_init error");
  406. return -1;
  407. }
  408. return 0;
  409. }