(三)基于vue3的网页设备连接阿里云生活物联网平台/物联网平台(附代码)

概述

        本章首先通过vue3架构和vscode编辑器实现网页设备与阿里云生活物联网平台/物联网平台相连,实现网页设备-物联网平台这二者之间的信息交互。

        单片机如何与阿里云生活物联网平台/物联网平台实现通信已经在上一章讲解,链接为:(二)stm32单片机连接阿里云生活物联网平台/物联网平台-CSDN博客

三、网页设备与生活物联网平台/物联网平台实现通信

1.vue3下载与安装

安装教程可以参考Vue3安装配置、开发环境搭建(组件安装卸载)(图文详细)-CSDN博客Vue3 安装与配置 详细教程_安装vue3-CSDN博客

2.创建网页设备

按照第一章的步骤创建网页设备

可以设置多个不同类型的功能以测试不同的信息

然后点击发布,加上之前的单片机设备一共有两个设备

 3.通过MQTT连接物联网平台

首先附上成功链接上的代码:

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import mqtt from 'mqtt';

export default {
    setup() {
        const client = ref(null);
        const recvData = ref('');
        const paramsData = ref('');
        const publishpowerstate = ref(null); // 初始化为 null
        const publishMessage = ref('');
        const publishdoorswitch = ref(null); // 初始化为 null
        const publishtemp = ref(null); // 初始化为 null
        let reconnectCount = 0;
        const publishFlag = ref(false);
        const isConnected = ref(false);

        const options = {
            connectTimeout: 10000,
            clientId: 'yourclientid,
            username: 'yourusername',
            password: 'yourpassword',
            cleanSession: false,
            keepAlive: 400,
        };

        const subscription = {
            topic: '/sys/a1VxoApLdIE/client/thing/service/property/set',
            qos: 0,
        };

        const publication = {
            topic: '/sys/a1VxoApLdIE/client/thing/event/property/post',
            qos: 0,
        };

        const doConnected = () => {
            console.log('正在连接...');
            try {
                client.value = mqtt.connect('wss://a1VxoApLdIE.iot-as-mqtt.cn-shanghai.aliyuncs.com:443', options);
            } catch (error) {
                console.log('mqtt连接失败: ', error);
            }
            client.value.on('connect', () => {
                console.log('连接成功');
                if (!isConnected.value) {
                    doSubscribe();
                    isConnected.value = true;
                }
            });

            client.value.on('message', (topic, message) => {
                console.log('收到来自', topic, '的消息', message.toString());
                const messageobject = JSON.parse(message.toString());
                paramsData.value = messageobject.params;
                recvData.value = message.toString();
                console.log('提取到的params数据', paramsData);
                if (paramsData.value.powerstate === 1) {
                    setTimeout(() => {
                        doPublish("true", 1, 22.5);
                    }, 100);
                } else if (paramsData.value.powerstate === 0) {
                    setTimeout(() => {
                        doPublish("false", 0, 23);
                    }, 100);
                }
            });

            client.value.on('error', (error) => {
                console.log('连接出错: ', error);
            });

            client.value.on('reconnect', (error) => {
                console.log(`重新连接... (第 ${++reconnectCount} 次)`, error);
                console.log('当前连接状态:', client.value.connected);
            });
        };

        const doDisconnected = () => {
            try {
                doUnSubscribe();
                client.value.end();
                console.log('断开连接');
            } catch (error) {
                console.log('断开连接失败: ', error.toString());
            }
        };

        const doSubscribe = () => {
            const { topic, qos } = subscription;
            client.value.subscribe(topic, qos, (error) => {
                if (!error) {
                    console.log('订阅成功');
                } else {
                    console.log('订阅失败');
                }
            });
        };

        const doUnSubscribe = () => {
            const { topic } = subscription;
            client.value.unsubscribe(topic, (error) => {
                if (error) {
                    console.log('取消订阅失败', error);
                }
            });
        };

        const payloadJson = {
            method: "thing.service.property.post",
            id: Date.now().toString(),
            params: {
                DoorSwitch: 0,
                mess: "",
                temp: 0,
            },
            version: "1.0.0",
        };

        const doPublish = () => {
            const { topic, qos } = publication;
            payloadJson.params.mess = publishMessage.value;
            payloadJson.params.DoorSwitch = publishdoorswitch.value;
            payloadJson.params.temp = publishtemp.value;
            const payload = JSON.stringify(payloadJson);
            client.value.publish(topic, payload, qos, (error) => {
                if (error) {
                    console.log('发布失败', error);
                } else {
                    console.log('发布成功', payload);
                }
            });
        };

        onMounted(() => {
            console.log('组件挂载后执行的代码块');
        });

        onBeforeUnmount(() => {
            console.log('组件销毁前执行的代码块');
            doDisconnected(); // 组件销毁前断开连接
        });

        return {
            doConnected,
            doDisconnected,
            doSubscribe,
            doUnSubscribe,
            doPublish,
            recvData,
            paramsData,
            publishMessage,
            publishpowerstate,
            publishtemp,
            publishFlag,
            publishdoorswitch,
        };
    },
};
</script>


<template>
    <div class="set">
        <div class="test">测试</div>
        <br>
        <div>
            <button @click="doConnected" class="connect">连接</button>
            <button @click="doDisconnected" class="disconnect">断开连接</button>
        </div>
        <br>
        <div>
            <tr>
                <td>状态:</td>
                <td><input type="number" v-model="publishpowerstate"></td>
            </tr>
            <tr>
                <td>门:</td>
                <td><input type="number" v-model="publishdoorswitch"></td>
            </tr>
            <tr>
                <td>温度:</td>
                <td><input type="number" v-model="publishtemp"></td>
            </tr>
            <tr>
                <td>消息:</td>
                <td><input type="text" v-model="publishMessage"></td>
            </tr>
        </div>
        <br>
        <div>
            <button @click="doPublish">发布</button>
        </div>
        <br>
        <div>
            <p>收到的消息: {{ recvData }}</p>
            <p>收到的params:{{ paramsData }}</p>
        </div>
    </div>
</template>

其中连接MQTT连接参数可在物联网平台中查阅

订阅与发布 的topic可以在生活物联网上,如果使用的是物联网平台的话,topic就在物联网平台上查询。

注意 使用WebSocket方式进行连接时,注意MQTT连接URL的协议和端口号和securemode参数

具体说明在:如何使用MQTT-WebSocket连接通信_物联网平台(IoT)-阿里云帮助中心

4.网页设备与生活物联网平台连接

在vscode中打开终端

Ctrl+'~'

接着进入到相对应的文件的路径运行文件并打开对应的网页

npm run dev

 

打开之后的网页如图,因为没有仔细设计所以页面显得比较丑0.0,主要是为了实现连接设备的功能 ,点击连接之后便能看到连接成功并且在生活物联网平台上可以看到设备已经处于连接状态。

 5.测试网页设备与物联网平台之间的通讯

在物联网平台上点击调试功能

可以看到平台发送信息时,网页设备后台会收到相对应的信息

 

同样的,网页设备也可以给物联网平台发送信息。

 6.gitee代码链接

https://gitee.com/jianghaoliang/vue3-mqtt.git

四、单片机与网页设备实现云产品流转功能

下一章计划讲讲单片机和网页设备通过物联网平台的云产品流转功能,并导入blender模型,实现可视化交互。

补充:(四) 单片机与网页设备实现云产品流转(设备与设备之间通信)功能(附代码)-CSDN博客

  • 15
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的VUE mqtt连接阿里云物联网平台的程序: 1. 首先,在你的VUE项目中安装mqtt依赖: ``` npm install mqtt --save ``` 2. 在你的组件中引入mqtt: ```javascript import mqtt from 'mqtt' ``` 3. 在你的组件中定义mqtt连接的参数: ```javascript const options = { clientId: 'your_client_id', username: 'your_username', password: 'your_password', clean: true } const mqttUrl = 'mqtt://your_mqtt_url:1883' ``` 4. 在你的组件中创建mqtt连接: ```javascript let client = mqtt.connect(mqttUrl, options) ``` 5. 在你的组件中定义mqtt连接的事件处理函数: ```javascript client.on('connect', function () { console.log('connected') }) client.on('message', function (topic, message) { console.log(topic, message.toString()) }) client.on('error', function (error) { console.log(error) }) ``` 6. 在你的组件中订阅mqtt主题: ```javascript client.subscribe('your_topic') ``` 7. 在你的组件中发布mqtt消息: ```javascript client.publish('your_topic', 'your_message') ``` 完整代码示例: ```javascript <template> <div> <p>MQTT</p> </div> </template> <script> import mqtt from 'mqtt' export default { name: 'mqtt', data() { return { client: null } }, created() { const options = { clientId: 'your_client_id', username: 'your_username', password: 'your_password', clean: true } const mqttUrl = 'mqtt://your_mqtt_url:1883' let client = mqtt.connect(mqttUrl, options) client.on('connect', function () { console.log('connected') }) client.on('message', function (topic, message) { console.log(topic, message.toString()) }) client.on('error', function (error) { console.log(error) }) client.subscribe('your_topic') client.publish('your_topic', 'your_message') this.client = client }, beforeDestroy() { this.client.end() } } </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值