千家信息网

MQTT如何连接阿里云订阅主题

发表于:2025-01-31 作者:千家信息网编辑
千家信息网最后更新 2025年01月31日,本篇内容主要讲解"MQTT如何连接阿里云订阅主题",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"MQTT如何连接阿里云订阅主题"吧!中移4G模块-ML302
千家信息网最后更新 2025年01月31日MQTT如何连接阿里云订阅主题

本篇内容主要讲解"MQTT如何连接阿里云订阅主题",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"MQTT如何连接阿里云订阅主题"吧!

中移4G模块-ML302-OpenCpu开发-(MQTT连接阿里云-订阅主题)

模块OpenCpu部分

cm_main.c文件里面的cm_main_task是主函数,在主函数里面调用cm_test_aliyun函数。

cm_test_aliyun函数:

void cm_test_aliyun(){    cm_printf("[ALIYUN]: aliyun demo start\n");    void                   *pclient = NULL;    int                     res = 0;    int                     rpc_res = 0;    int                     loop_cnt = 0;    iotx_mqtt_param_t       mqtt_params;    HAL_GetProductKey(DEMO_PRODUCT_KEY);    HAL_GetDeviceName(DEMO_DEVICE_NAME);    HAL_GetDeviceSecret(DEMO_DEVICE_SECRET);    memset(&mqtt_params, 0x0, sizeof(mqtt_params));    mqtt_params.handle_event.h_fp = example_event_handle;    pclient = IOT_MQTT_Construct(&mqtt_params);    if (NULL == pclient) {        cm_printf("[ALIYUN]: MQTT construct failed\n");        return -1;    }    res = example_subscribe(pclient);      //调用example_subscribe函数    if (res < 0) {        IOT_MQTT_Destroy(&pclient);        return -1;    }    while (1) {        if (0 == loop_cnt % 20) {            example_publish(pclient);        }        IOT_MQTT_Yield(pclient, 200);        loop_cnt += 1;        if(loop_cnt >= 100)  {            //break;        }    }        cm_printf("[ALIYUN]: aliyun demo end\n");}

example_subscribe函数:

example_subscribe一开始进行字符串连接,把${YourProductKey}/${YourDeviceName}/user/get拼接出来,然后调用IOT_MQTT_Subscribe函数订阅topic

int example_subscribe(void *handle){    int res = 0;    const char *fmt = "/%s/%s/user/get";    //订阅的MQTT路径    char *topic = NULL;    int topic_len = 0;    topic_len = strlen(fmt) + strlen(DEMO_PRODUCT_KEY) + strlen(DEMO_DEVICE_NAME) + 1;    topic = HAL_Malloc(topic_len);    if (topic == NULL) {        cm_printf("[ALIYUN]: memory not enough\n");        return -1;    }    memset(topic, 0, topic_len);    HAL_Snprintf(topic, topic_len, fmt, DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME);    //通过HAL_Snprintf函数的拼接得出最终的MQTT路径    //示例:${YourProductKey}/${YourDeviceName}/user/get    //其中的:example_message_arrive函数为接收的数据的回调函数        res = IOT_MQTT_Subscribe(handle, topic, IOTX_MQTT_QOS0, example_message_arrive, NULL);    if (res < 0) {        cm_printf("[ALIYUN]: subscribe failed\n");        HAL_Free(topic);        return -1;    }    HAL_Free(topic);    return 0;}

example_message_arrive函数

example_subscribe为topic接收回调函数,当接收到此topic的数据时会放到这里处理

void example_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg){    iotx_mqtt_topic_info_t     *topic_info = (iotx_mqtt_topic_info_pt) msg->msg;    cm_printf("example_message_arrive \n");    switch (msg->event_type) {        case IOTX_MQTT_EVENT_PUBLISH_RECEIVED:            /* print topic name and topic message */            cm_printf("[ALIYUN]: Message Arrived:");            cm_printf("Topic  : %.*s", topic_info->topic_len, topic_info->ptopic);            cm_printf("Payload: %.*s", topic_info->payload_len, topic_info->payload);            cm_printf("\n");            // topic_info->payload为接收到的数据            if(strcmp(topic_info->payload,"1") == 0){                cm_printf("开灯\n");                cm_gpio_write(21,CM_GPIO_LOW);            }else{                cm_printf("关灯\n");                cm_gpio_write(21,CM_GPIO_HIGH);            }            break;        default:            break;    }}

服务器部分

前端通过传入lightState来控制GPIO21是高电平还是低电平

@GetMapping(path="hello")    public WebResult setGPIOState(int lightState){        // XXXXXX:ProductKey        // YYYYYY: 设备名称        PubRequest request = new PubRequest();        request.setProductKey("XXXXXXXXXXXX");          request.setMessageContent(Base64.encodeBase64String((Integer.toString(lightState)).getBytes()));        request.setTopicFullName("/XXXXXXXXXX/YYYYYYYYYYY/user/get");        request.setQos(0); //目前支持QoS0和QoS1。        try {            PubResponse response = defaultAcsClient.getAcsResponse(request);            //System.out.println(response.getSuccess());            //System.out.println(response.getErrorMessage());        } catch (ServerException e) {            e.printStackTrace();        } catch (ClientException e) {            e.printStackTrace();        }        return WebResult.success(1,"hello");    }

前端网页部分

灯光开 灯光关
methods:{        setLightState(state){            console.log(state);            // 开关灯            axios({                method: 'get',                url: "/iot/hello",                params: {                    'lightState':state                }            }).then(res => {                console.log(res)            })        },    }

到此,相信大家对"MQTT如何连接阿里云订阅主题"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0