mqtt_basic_demo.c 14 KB

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