uniapp vue3 连接树莓派物联网服务器的方法

一、树莓派物联网服务器配置配置

 参考博客:树莓派系列(十四) 树莓派4B安装 docker并配置为 MQTT服务器_docker pull emqx/emqx:4.3-rc.5-CSDN博客

二、uniapp的main.js全局配置:

import { createApp } from 'vue';
import App from './App.vue';
import MQTT from 'mqtt/dist/mqtt.js';

let mqttClient = null; // 全局 MQTT 客户端实例

let options = {
  username: 'lxt',
  clientId: '6666',
  connectTimeout: 600000,
  keepalive: 5,
  clean: true,
};

let subscribe = "mqtt11";

// mqttClient = MQTT.connect('ws://192.168.1.105:8083/mqtt', options);
mqttClient = MQTT.connect('ws://106.54.235.58:18083/mqtt', options);
mqttClient.on('connect', () => {  
  console.log('Connected to MQTT broker');
  console.log("连接成功");
  mqttClient.subscribe(subscribe, (err) => {  
    console.log(err);
    if (!err) {  
      console.log("订阅成功");
	        // 连接成功后发送数据
	        sendDataToServer('lightoff'); // 这里假设初始状态为关闭灯
    }  
  });
});

function sendDataToServer(command) {
  // 在这里编写发送数据的逻辑
  // let command = command;
  let topic = 'mqtt11';
  mqttClient.publish(topic, command, (err) => {
    if (!err) {
      console.log('Message sent successfully');
    } else {
      console.error('Failed to send message:', err);
    }
  });
mqttClient.on('message', (topic, message) => {  
  console.log(`Received message on topic ${topic}: ${message.toString()}`);
  // 在这里处理接收到的消息
});
}
const app = createApp(App);
app.config.globalProperties.$mqttClient = mqttClient; // 将 mqttClient 挂载到全局属性中
app.mount('#app');

三、页面调用

<template>
  <div>
    <p>{{ receivedMessage }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      receivedMessage: ''
    }
  }
  ,
  mounted() {
    this.$mqttClient.on('message', (topic, message) => {  
      console.log(`Received message on topic ${topic}: ${message.toString()}`);
      this.receivedMessage = message.toString(); // 更新接收到的消息
    });
  }
}
</script>

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值