mqtt_rrpc_demo.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * 这个例程适用于`Linux`这类支持pthread的POSIX设备, 它演示了用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 rrpc_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. ql_task_t ql_alisdk_rrpc_task_ref;
  36. ql_task_t ql_alisdk_rrpc_mqtt_process_task_ref;
  37. ql_task_t ql_alisdk_rrpc_mqtt_recv_task_ref;
  38. static uint8_t g_rrpc_mqtt_process_task_running = 0;
  39. static uint8_t g_rrpc_mqtt_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, rrpc_profile_idx, 0);
  66. uart_printf("===start data call====");
  67. ret = ql_start_data_call(nSim, rrpc_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, rrpc_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, rrpc_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: %.*s\n", packet->data.pub.qos, packet->data.pub.topic_len, packet->data.pub.topic);
  152. uart_printf("pub, payload: %.*s\n", packet->data.pub.payload_len, packet->data.pub.payload);
  153. /* TODO: 处理服务器下发的业务报文, 此处如果收到rrpc的报文, 那么应答时使用相同的topic即可 */
  154. /* 更多信息请参考 https://help.aliyun.com/document_detail/90570.html */
  155. /* 下面是一个rrpc的应答示例 */
  156. {
  157. char *payload = "pong";
  158. char resp_topic[256];
  159. memset(resp_topic, 0, sizeof(resp_topic));
  160. memcpy(resp_topic, packet->data.pub.topic, packet->data.pub.topic_len);
  161. aiot_mqtt_pub(handle, resp_topic, (uint8_t *)payload, (uint32_t)strlen(payload), 0);
  162. }
  163. }
  164. break;
  165. case AIOT_MQTTRECV_PUB_ACK: {
  166. uart_printf("puback, packet id: %d\n", packet->data.pub_ack.packet_id);
  167. /* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */
  168. }
  169. break;
  170. default: {
  171. }
  172. }
  173. }
  174. /* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
  175. static void demo_mqtt_process_thread(void *args)
  176. {
  177. int32_t res = STATE_SUCCESS;
  178. while (g_rrpc_mqtt_process_task_running) {
  179. res = aiot_mqtt_process(args);
  180. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  181. break;
  182. }
  183. ql_rtos_task_sleep_s(1);
  184. }
  185. ql_alisdk_rrpc_mqtt_process_task_ref = NULL;
  186. ql_rtos_task_delete(NULL);
  187. return;
  188. }
  189. /* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
  190. static void demo_mqtt_recv_thread(void *args)
  191. {
  192. int32_t res = STATE_SUCCESS;
  193. while (g_rrpc_mqtt_recv_task_running) {
  194. res = aiot_mqtt_recv(args);
  195. if (res < STATE_SUCCESS) {
  196. if (res == STATE_USER_INPUT_EXEC_DISABLED) {
  197. break;
  198. }
  199. ql_rtos_task_sleep_s(1);
  200. }
  201. }
  202. ql_alisdk_rrpc_mqtt_recv_task_ref = NULL;
  203. ql_rtos_task_delete(NULL);
  204. return;
  205. }
  206. static void ql_alisdk_rrpc_task(void *arg)
  207. {
  208. int32_t res = STATE_SUCCESS;
  209. void *mqtt_handle = NULL;
  210. char *url = "iot-as-mqtt.cn-shanghai.aliyuncs.com"; /* 阿里云平台上海站点的域名后缀 */
  211. char host[100] = {0}; /* 用这个数组拼接设备连接的云平台站点全地址, 规则是 ${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com */
  212. uint16_t port = 443; /* 无论设备是否使用TLS连接阿里云平台, 目的端口都是443 */
  213. aiot_sysdep_network_cred_t cred; /* 安全凭据结构体, 如果要用TLS, 这个结构体中配置CA证书等参数 */
  214. /* TODO: 替换为自己设备的三元组 */
  215. char *product_key = "a1TSu2F29co";
  216. char *device_name = "000001";
  217. char *device_secret = "bd220c3a9c6a5b3f5921485d091497e1";
  218. int time_delay_ms = 5000;
  219. int pdp = rrpc_profile_idx;
  220. /*执行拨号操作,设备联网*/
  221. if(datacall_satrt() != 0)
  222. goto exit;
  223. /* 配置SDK的底层依赖 */
  224. aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
  225. /* 配置SDK的日志输出 */
  226. aiot_state_set_logcb(demo_state_logcb);
  227. /* 创建SDK的安全凭据, 用于建立TLS连接 */
  228. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  229. cred.option = AIOT_SYSDEP_NETWORK_CRED_SVRCERT_CA; /* 使用RSA证书校验MQTT服务端 */
  230. cred.max_tls_fragment = 16384; /* 最大的分片长度为16K, 其它可选值还有4K, 2K, 1K, 0.5K */
  231. cred.sni_enabled = 1; /* TLS建连时, 支持Server Name Indicator */
  232. cred.x509_server_cert = ali_ca_cert; /* 用来验证MQTT服务端的RSA根证书 */
  233. cred.x509_server_cert_len = strlen(ali_ca_cert); /* 用来验证MQTT服务端的RSA根证书长度 */
  234. /* 创建1个MQTT客户端实例并内部初始化默认参数 */
  235. mqtt_handle = aiot_mqtt_init();
  236. if (mqtt_handle == NULL) {
  237. uart_printf("aiot_mqtt_init failed\n");
  238. goto exit;
  239. }
  240. /* TODO: 如果以下代码不被注释, 则例程会用TCP而不是TLS连接云平台 */
  241. /*
  242. {
  243. memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
  244. cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE;
  245. }
  246. */
  247. snprintf(host, 100, "%s.%s", product_key, url);
  248. /* 配置MQTT服务器地址 */
  249. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_HOST, (void *)host);
  250. /* 配置MQTT服务器端口 */
  251. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PORT, (void *)&port);
  252. /* 配置设备productKey */
  253. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PRODUCT_KEY, (void *)product_key);
  254. /* 配置设备deviceName */
  255. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_NAME, (void *)device_name);
  256. /* 配置设备deviceSecret */
  257. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_DEVICE_SECRET, (void *)device_secret);
  258. /* 配置网络连接的安全凭据, 上面已经创建好了 */
  259. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_NETWORK_CRED, (void *)&cred);
  260. /* 配置MQTT默认消息接收回调函数 */
  261. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER, (void *)demo_mqtt_default_recv_handler);
  262. /* 配置MQTT事件回调函数 */
  263. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER, (void *)demo_mqtt_event_handler);
  264. /* 配置MQTT连接超时时间 */
  265. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_CONNECT_TIMEOUT_MS, (void *)&time_delay_ms);
  266. /* 配置拨号profile_idx信息(quectel平台必须执行此操作)*/
  267. aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PROFILE_IDX, (void *)&pdp);
  268. /* 与服务器建立MQTT连接 */
  269. res = aiot_mqtt_connect(mqtt_handle);
  270. if (res < STATE_SUCCESS) {
  271. /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
  272. aiot_mqtt_deinit(&mqtt_handle);
  273. uart_printf("aiot_mqtt_connect failed: -0x%04X\n", -res);
  274. goto exit;
  275. }
  276. /* MQTT 订阅topic功能示例, 请根据自己的业务需求进行使用 */
  277. {
  278. char *sub_topic = "/a13FN5TplKq/mqtt_rrpc_demo/user/get";
  279. res = aiot_mqtt_sub(mqtt_handle, sub_topic, NULL, 1, NULL);
  280. if (res < 0) {
  281. uart_printf("aiot_mqtt_sub failed, res: -0x%04X\n", -res);
  282. goto exit;
  283. }
  284. }
  285. /* MQTT 发布消息功能示例, 请根据自己的业务需求进行使用 */
  286. /* {
  287. char *pub_topic = "/sys/a13FN5TplKq/mqtt_basic_demo/thing/event/property/post";
  288. char *pub_payload = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}";
  289. res = aiot_mqtt_pub(mqtt_handle, pub_topic, (uint8_t *)pub_payload, (uint32_t)strlen(pub_payload), 0);
  290. if (res < 0) {
  291. uart_printf("aiot_mqtt_pub failed, res: -0x%04X\n", -res);
  292. goto exit;
  293. }
  294. } */
  295. /* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活, 以及重发QoS1的未应答报文 */
  296. g_rrpc_mqtt_process_task_running = 1;
  297. res = ql_rtos_task_create(&ql_alisdk_rrpc_mqtt_process_task_ref, 24576, 24, "client_test", demo_mqtt_process_thread, (void *)mqtt_handle, 5);
  298. if (res < 0) {
  299. uart_printf("pthread_create demo_mqtt_process_thread failed: %d\n", res);
  300. goto exit;
  301. }
  302. /* 创建一个单独的线程用于执行aiot_mqtt_recv, 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
  303. g_rrpc_mqtt_recv_task_running = 1;
  304. res = ql_rtos_task_create(&ql_alisdk_rrpc_mqtt_recv_task_ref, 24576, 25, "recv_test", demo_mqtt_recv_thread, (void *)mqtt_handle, 5);
  305. if (res < 0) {
  306. uart_printf("pthread_create demo_mqtt_recv_thread failed: %d\n", res);
  307. goto exit;
  308. }
  309. /* 主循环进入休眠 */
  310. while (1) {
  311. ql_rtos_task_sleep_s(1);
  312. }
  313. exit:
  314. g_rrpc_mqtt_process_task_running = 0;
  315. g_rrpc_mqtt_recv_task_running = 0;
  316. while(NULL != ql_alisdk_rrpc_mqtt_process_task_ref || NULL != ql_alisdk_rrpc_mqtt_recv_task_ref)
  317. {
  318. ql_rtos_task_sleep_s(1);
  319. }
  320. if(NULL != mqtt_handle)
  321. {
  322. /* 断开MQTT连接, 一般不会运行到这里 */
  323. res = aiot_mqtt_disconnect(mqtt_handle);
  324. if (res < STATE_SUCCESS) {
  325. aiot_mqtt_deinit(&mqtt_handle);
  326. uart_printf("aiot_mqtt_disconnect failed: -0x%04X\n", -res);
  327. }
  328. /* 销毁MQTT实例, 一般不会运行到这里 */
  329. res = aiot_mqtt_deinit(&mqtt_handle);
  330. if (res < STATE_SUCCESS) {
  331. uart_printf("aiot_mqtt_deinit failed: -0x%04X\n", -res);
  332. }
  333. }
  334. ql_alisdk_rrpc_task_ref = NULL;
  335. ql_rtos_task_delete(NULL);
  336. }
  337. #define QL_ALI_TASK_STACK_SIZE 10240
  338. #define QL_ALI_TASK_PRIO APP_PRIORITY_NORMAL
  339. #define QL_ALI_TASK_EVENT_CNT 5
  340. int ql_ali_sdk_rrpc_test_init(void)
  341. {
  342. QlOSStatus status;
  343. int count = 0;
  344. /* 主循环进入休眠 */
  345. while (count < 10)
  346. {
  347. count++;
  348. ql_rtos_task_sleep_s(1);
  349. uart_printf("ql_ali_sdk_mqtt_client_test_init -0x%04X\n", count);
  350. }
  351. status =ql_rtos_task_create(&ql_alisdk_rrpc_task_ref, QL_ALI_TASK_STACK_SIZE, APP_PRIORITY_NORMAL, "rrpc_task", ql_alisdk_rrpc_task, NULL, QL_ALI_TASK_EVENT_CNT);
  352. if (status != QL_OSI_SUCCESS)
  353. {
  354. uart_printf("ql_ali_sdk_devinfo_test_init error");
  355. return -1;
  356. }
  357. return 0;
  358. }