var mqtt = require('../../utils/mqtt.min.js') //根据自己存放的路径修改
Page({
data: {
actionIntervalIds: {},
actionStates: {
forward: false,
backward: false,
turnLeft: false,
turnRight: false,
},
client: null, // MQTT客户端实例
isConnected: false // 连接状态
},
onLoad: function() {
this.connectMQTT();
},
connectMQTT: function() {
if (this.data.isConnected) {
return; // 如果已经连接,则不重复连接
}
const options = {
keepalive: 60,
clean: true,
protocolVersion: 4,
clientId:`wx_client_${Math.random().toString(36).substr(2)}`,
url: 'wx://www.visionexpand.com.cn:8083/mqtt' // 替换为你的MQTT服务器WebSocket地址
};
this.data.client = mqtt.connect(options.url, options); // 注意:这行代码在真实环境中需要调整 this.data.client.on('connect', () => { console.log('连接 MQTT 服务器成功'); this.setData({
isConnected: true
});
});
this.data.client.on('error', (err) => { console.error('连接 MQTT 服务器失败:', err);
});
},
forward: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
return;
}
const message = JSON.stringify([0x20, 0x81, 0x81, 0xC1, 0x92, 0x80, 0x80, 0x80, 0x80, 0xF5]); this.data.client.publish('$thing/down/property/IQMPOB8BI9/temp/humi', message, { qos: 2 }, (err) => {
if (err) {
console.error('发送消息失败:', err);
} else {
console.log('消息已成功发送到:', message);
}
});
},
backward: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
return;
}
const message = JSON.stringify([0x20, 0x81, 0x81, 0xC5, 0x92, 0x80, 0x80, 0x80, 0x80, 0xF9]); this.data.client.publish('$thing/down/property/IQMPOB8BI9/temp/humi', message, { qos: 2 }, (err) => {
if (err) {
console.error('发送消息失败:', err);
} else {
console.log('消息已成功发送到:', message);
}
});
},
turnleft: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
return;
}
const message = JSON.stringify([0x20, 0x81, 0x81, 0xC7, 0x92, 0x80, 0x80, 0x80, 0x80, 0xFB]); this.data.client.publish('$thing/down/property/IQMPOB8BI9/temp/humi', message, { qos: 2 }, (err) => {
if (err) {
console.error('发送消息失败:', err);
} else {
console.log('消息已成功发送到:',message);
}
});
},
turnright: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
return;
}
const message = JSON.stringify([0x20, 0x81, 0x81, 0xC3, 0x92, 0x80, 0x80, 0x80, 0x80, 0xF7]);
this.data.client.publish('$thing/down/property/IQMPOB8BI9/temp/humi', message, { qos: 2 }, (err) => {
if (err) {
console.error('发送消息失败:', err);
} else {
console.log('消息已成功发送到:', message);
}
});
},
stop: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
return;
}
const message = JSON.stringify([0x20, 0x81, 0x81, 0xDA, 0x92, 0x80, 0x80, 0x80, 0x80, 0x8E]);
this.data.client.publish('$thing/down/property/IQMPOB8BI9/temp/humi', message, { qos: 2 }, (err) => {
if (err) {
console.error('发送消息失败:', err);
} else {
console.log('消息已成功发送到:', message);
}
});
}
})