Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

JavaScript
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'; // "TestMQTT_microbit" is my topic.
  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);
    }
  // UrlFetchApp.fetch(url, options);
}
Posted
Updated 29-Jan-24 5:38am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900