mqtt_broadcast_demo.c 14 KB

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