//前进
handleForwardStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.startSending('forward'); // 启动定时器发送forward消息
if(this.data.currentGear==='空挡'){
this.handleStopSending();
wx.showToast({
title: '需要换挡',
})
return;
}else{
wx.showToast({
title: '前进',
});
}
},
//后退
handleBackwardStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.startSending('backward'); // 启动定时器发送backward消息
if(this.data.currentGear==='空挡'){
this.handleStopSending();
wx.showToast({
title: '需要换挡',
})
return;
}else{
wx.showToast({
title: '后退',
});
}
},
//左转
handleTurnLeftStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.startSending('turnLeft');
if(this.data.currentGear==='空挡'){
this.handleStopSending();
wx.showToast({
title: '需要换挡',
})
return;
}else{
wx.showToast({
title: '左转',
});
}
},
//右转
handleTurnRightStart: function() {
if (!this.data.isConnected) {
console.error('未连接到MQTT服务器,无法发送消息');
wx.showToast({
title: '未连接到MQTT服务器,无法发送消息',
})
return;
}
this.startSending('turnRight');
if(this.data.currentGear==='空挡'){
this.handleStopSending();
wx.showToast({
title: '需要换挡',
})
return;
}else{
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; // 记录当前正在执行的动作
this.data.intervalId = setInterval(() => {
let dataToSend;
switch(this.data.currentAction){
case 'forward':
if (this.data.currentGear === '2挡') {
dataToSend = '1';
} else if (this.data.currentGear === '1挡') {
dataToSend = 'c';
}
break;
case 'backward':
if (this.data.currentGear === '2挡') {
dataToSend = '4';
} else if (this.data.currentGear === '1挡') {
dataToSend = 'b';
}
break;
case 'turnLeft':
if (this.data.currentGear === '2挡') {
dataToSend = '2';
} else if (this.data.currentGear === '1挡') {
dataToSend = 'e';
}
break;
case 'turnRight':
if (this.data.currentGear === '2挡') {
dataToSend = '3';
} else if (this.data.currentGear === '1挡') {
dataToSend = 'd';
}
break;
}
if (dataToSend) {
if (Array.isArray(dataToSend)) {
dataToSend.forEach(data => this.sendData(data));
} else {
this.sendData(dataToSend);
}
}
}, 500);
},
stopSending: function() {
if (this.data.intervalId) {
clearInterval(this.data.intervalId);
this.data.intervalId = null;
this.data.currentAction = null; // 清除当前动作
this.sendData('0');
}
},