[技术干货] 使用LiteOS MQTT_AL组件自己搭建的EMQ-X服务器(MQTT服务器)的测试代码分享

本代码基于MQTT_AL开启成功的前提,使用MQTT_AL提供的API进行连接测试: 测试代码: ```c #include <osal.h> #include <mqtt_al.h> #include <string.h> #define DEFAULT_LIFETIME 60 #define DEFAULT_SERVER_IPV4 "122.51.89.94" #define DEFAULT_SERVER_PORT 1883 #define CN_MQTT_EP_CLIENTID "emqx-test-001" #define CN_MQTT_EP_USERNAME "mculover666" #define CN_MQTT_EP_PASSWD "123456789" static int task_report_msg_entry(void *args) { int ret = -1; void *handle = NULL; mqtt_al_conpara_t config; mqtt_al_string_t str_temp; /* 配置结构体 */ str_temp.data = DEFAULT_SERVER_IPV4; str_temp.len = sizeof(DEFAULT_SERVER_IPV4); config.serveraddr = str_temp; config.serverport = DEFAULT_SERVER_PORT; config.security = en_mqtt_al_security_none; config.version = en_mqtt_al_version_3_1_0; str_temp.data = CN_MQTT_EP_CLIENTID; str_temp.len = sizeof(CN_MQTT_EP_CLIENTID); config.clientid = str_temp; str_temp.data = CN_MQTT_EP_USERNAME; str_temp.len = sizeof(CN_MQTT_EP_USERNAME); config.user = str_temp; str_temp.data = CN_MQTT_EP_PASSWD; str_temp.len = sizeof(CN_MQTT_EP_PASSWD); config.passwd = str_temp; config.cleansession = 1; config.willmsg = NULL; config.keepalivetime = DEFAULT_LIFETIME; config.timeout = 30; /* 配置并连接服务器 */ handle = mqtt_al_connect(&config); if(handle == NULL) { /* 连接出错 */ printf("config error.\r\n"); return -1; } else { /* 进一步检查服务器返回值 */ if(config.conret != cn_mqtt_al_con_code_ok) { /* 服务器返回值出错 */ printf("server return error, conret = %d.\r\n", config.conret); return -1; } else { printf("connect to server success.\r\n"); } } while(1) { printf("config ok.\r\n"); osal_task_sleep(5*1000); } } int standard_app_demo_main() { /* 创建任务 */ osal_task_create("task_reportmsg",task_report_msg_entry,NULL,0x800,NULL,8); return 0; } ``` # 结果 ![image.png](https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/attachment/forum/202001/10/105653ygqu2ejbcvdq7022.png) ![image.png](https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/attachment/forum/202001/10/105859ufywymrrpoa9ppyf.png)