温湿度数据(temp004)需要包含LED状态例如#80#10#off,并使硬件设备LED反应,同时以上已经实现的功能代码得存在;// 获取应用实例
const app = getApp()
import mqtt from '../../utils/js/mqtt.min.js';
Page({
data: {
uid: "1eacbabea77cd2fce337e15e9028d301",
ledtopic: "swi006",
dhttopic: "temp004",
device_status: "离线",
ledOnOff: "关闭",
checked: false,
wendu: "",
shidu: "",
ledicon: "/utils/img/lightoff.png",
client: null,
// 新增状态标记防止循环更新
isUpdatingFromDevice: false
},
mqttConnect() {
var that = this
var options = {
keepalive: 60,
clean: true,
protocolVersion: 4,
clientId: this.data.uid
}
this.data.client = mqtt.connect('wxs://bemfa.com:9504/wss', options)
// 连接成功回调
this.data.client.on('connect', function () {
console.log('MQTT连接成功')
that.setData({ device_status: "在线" })
// 订阅LED状态主题和温湿度主题
that.data.client.subscribe([that.data.ledtopic, that.data.dhttopic], function (err) {
if (err) console.log("订阅失败:", err)
else console.log("成功订阅主题")
})
})
// 消息处理
that.data.client.on('message', function (topic, message) {
const msg = message.toString()
console.log(`收到主题[${topic}]消息: ${msg}`)
// 处理LED状态更新
if (topic === that.data.ledtopic) {
that.handleLedState(msg)
}
// 处理温湿度数据
if (topic === that.data.dhttopic) {
that.handleSensorData(msg)
}
})
// 断线重连
this.data.client.on("reconnect", function () {
console.log("MQTT重新连接中...")
that.setData({ device_status: "重连中" })
})
// 错误处理
this.data.client.on('error', (err) => {
console.error('MQTT错误:', err)
that.setData({ device_status: "连接错误" })
})
},
// 处理LED状态更新
handleLedState(msg) {
if (this.data.isUpdatingFromDevice) return
this.setData({
isUpdatingFromDevice: true,
checked: msg === "on",
ledOnOff: msg === "on" ? "打开" : "关闭",
ledicon: msg === "on" ? "/utils/img/lighton.png" : "/utils/img/lightoff.png"
}, () => {
setTimeout(() => this.setData({ isUpdatingFromDevice: false }), 500)
})
},
// 处理传感器数据
handleSensorData(msg) {
if (msg.indexOf("#") === -1) return
const parts = msg.split("#").filter(Boolean)
if (parts.length < 2) return
this.setData({
wendu: parts[0],
shidu: parts[1]
})
},
onLoad() {
this.mqttConnect()
this.getDeviceStatus()
console.log("小程序启动完成")
},
onUnload() {
if (this.data.client) {
this.data.client.end()
console.log("MQTT连接已关闭")
}
},
// LED控制切换
onChange({ detail }) {
this.toggleLedState(detail)
},
// LED图标点击
onChange2() {
this.toggleLedState(!this.data.checked)
},
// LED状态切换核心方法
toggleLedState(newState) {
if (!this.data.client || this.data.device_status !== "在线") {
wx.showToast({ title: '设备离线', icon: 'error' })
return
}
const command = newState ? "on" : "off"
this.data.client.publish(this.data.ledtopic, command)
this.setData({
checked: newState,
ledOnOff: newState ? "打开" : "关闭",
ledicon: newState ? "/utils/img/lighton.png" : "/utils/img/lightoff.png"
})
console.log(`发送LED控制命令: ${command}`)
},
// 获取设备状态
getDeviceStatus() {
wx.request({
url: 'https://api.bemfa.com/mqtt/status/',
data: { uid: this.data.uid, topic: this.data.ledtopic },
header: { 'content-type': "application/x-www-form-urlencoded" },
success: (res) => {
this.setData({
device_status: res.data.status === "online" ? "在线" : "离线"
})
},
fail: (err) => {
console.error("状态获取失败:", err)
}
})
}
})给出完整代码,不要把不用修改的代码省略