| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <template>
- <view class="mqttDemo">
- <view>{{mqttData}}</view>
- </view>
- </template>
- <script>
- import $mqtt from '@/utils/mqtt.min.js';
- export default {
- data() {
- return {
- client: {},
- //MQTT请求参数-传感器
- mtopic: "iot/device/sensor/sub/",
- //MQTT请求参数-智能控制
- mtopicOne: "iot/hardware/all/sub/",
- subId:'101093843117597548',
- mqttData:'',
- }
- },
- onLoad(option) {
- },
- onShow(){
- this.offMQTT('on');
- },
- mounted(){
- },
- methods: {
- //MQTT订阅
- sensorMQTT() {
- let self = this;
- this.client = $mqtt.connect(
- // #ifdef WEB
- 'wss://' + uni.getStorageSync('mqttUrl')
- // #endif
- // #ifdef MP-WEIXIN
- 'wxs://' + uni.getStorageSync('mqttUrl')
- // #endif
- , {
- username: uni.getStorageSync('mqttUser'),
- password: uni.getStorageSync('mqttPassword')
- });
- this.client.on("connect", e => {
- this.client.subscribe(this.mtopic + self.subId, (err) => {
- if (!err) {
- console.log("传感器订阅成功:" + this.mtopic + self.subId);
- } else {
- console.log("连接错误:" + err);
- }
- });
- this.client.subscribe(this.mtopicOne + self.subId, (err) => {
- if (!err) {
- console.log("智能控制订阅成功:" + this.mtopicOne + self.subId);
- } else {
- console.log("连接错误:" + err);
- }
- });
- });
- this.client.on("message", (topic, message) => {
- if (message) {
- let data = JSON.parse(message)
- console.log('data',data)
- this.$set(this,'mqttData',JSON.stringify(data));
- }
- });
- },
- //取消订阅关闭MQTT连接
- offMQTT(type) {
- let self = this;
- if (self.client.unsubscribe) {
- self.client.unsubscribe(self.mtopicOne + self.subId, error => {
- if (error) {
- // console.log('mqtt关闭连接错误:', error)
- }
- })
- self.client.end();
- self.$set(self, 'client', {});
- }
- //判断传入参数如果存在 发起一次新的连接
- if (type) {
- self.sensorMQTT();
- }
- },
- },
- onHide() {
- //清除MQTT
- let self = this;
- self.offMQTT();
- },
- beforeDestroy() {
- //清除MQTT
- let self = this;
- self.offMQTT();
- },
- }
- </script>
- <style lang="stylus" scoped>
- .mqttDemo{
- height:100%;
- width:100%;
- }
- </style>
|