handleForwardStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.sendData('1'); // 发送forward消息
this.startSending('forward'); // 启动定时器发送forward消息
wx.showToast({
title: '前进',
})
},
handleBackwardStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.sendData('4'); // 发送backward消息
this.startSending('backward'); // 启动定时器发送backward消息
wx.showToast({
title: '后退',
})
},
handleTurnLeftStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.sendData('2'); // 发送forward消息
this.startSending('turnLeft'); // 启动定时器发送forward消息
wx.showToast({
title: '左转',
})
},
handleTurnRightStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.sendData('3'); // 发送forward消息
this.startSending('turnRight'); // 启动定时器发送forward消息
wx.showToast({
title: '右转',
})
},
handleStopSending: function() {
this.stopSending(); // 停止发送消息并清除定时器
},
sendData: function(message) {
const topic = '$thing/down/property/IQMPOB8BI9/temp/humi';
this.data.client.publish(topic, message, { qos: 2 }, (err) => {
if (err) {
console.error('发送消息失败:', err);
} else {
console.log('消息已成功发送到:', message);
}
});
},
startSending: function(action) {
if (this.data.intervalId) {
clearInterval(this.data.intervalId); // 如果有之前的定时器在运行,先清除它
}
this.data.currentAction = action; // 记录当前正在执行的动作
// 设置定时器,每5秒调用一次sendData函数,但这里我们不直接在定时器中调用sendData
// 而是使用另一个函数来根据当前动作发送数据
this.data.intervalId = setInterval(() => {
switch(this.data.currentAction){
case 'forward':
this.sendData('1');
break;
case 'backward':
this.sendData('4');
break;
case 'turnLeft':
this.sendData('2');
break;
case 'turnRight':
this.sendData('3');
break;
}
}, 1000);
},
stopSending: function() {
if (this.data.intervalId) {
clearInterval(this.data.intervalId);
this.data.intervalId = null;
this.data.currentAction = null; // 清除当前动作
// 发送停止消息(如果需要)
this.sendData('0');
}
},
3337

被折叠的 条评论
为什么被折叠?



