I want to use line bot and mqtt to control the light. I want to send a message to line bot, then line bot will determine whether it is on or off. After that, line bot will send a command to mqtt, then it can control the light. The problem is that I can't connect line bot and mqtt successfully.
What I have tried:
var CHANNEL_ACCESS_TOKEN = ' My LINE Channel Access Token ';
function doPost(e) {
var replyToken = JSON.parse(e.postData.contents).events[0].replyToken;
var userMessage = JSON.parse(e.postData.contents).events[0].message.text;
if (userMessage.includes('Turn on')) {
sendMqttCommandToBroker('My host', 'port', 'on');
pushLineBotMessage('Turned on the light', replyToken);
}
else if (userMessage.includes('Turn off') {
sendMqttCommandToBroker('My host', 'port', 'off');
pushLineBotMessage('Turned off the light', replyToken);
}
return ContentService.createTextOutput('Received').setMimeType(ContentService.MimeType.TEXT);
}
function pushLineBotMessage(sMsg, sReplyToken){
var linePayload = {
'replyToken': sReplyToken,
'messages': [
{
'type': 'text',
'text': sMsg
}
]
};
var lineOptions = {
'method': 'post',
'headers': {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN
},
'payload': JSON.stringify(linePayload)
};
UrlFetchApp.fetch('https://api.line.me/v2/bot/message/reply', lineOptions);
}
function sendMqttCommandToBroker(mqttBrokerHost, mqttBrokerPort, mqttCommand) {
var url = 'mqtt://' + mqttBrokerHost + ':' + mqttBrokerPort + '/TestMQTT_microbit';
var options = {
'method': 'post',
'payload': mqttCommand
};
try {
var response = UrlFetchApp.fetch(url, options);
console.log('MQTT Command sent:', response.getContentText());
} catch (error) {
console.error('Error sending MQTT command:', error);
}
}