Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 41 additions & 23 deletions mqtt-exec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ var mqtt = require('mqtt')
, optimist = require('optimist')
, util = require('util')
, exec = require('child_process').exec
, sleep = require('sleep')
, url = require('url')
, fs = require('fs')
, log4js = require('log4js')
Expand Down Expand Up @@ -46,39 +45,58 @@ for(var key in configuration){

//Creating the MQTT Client
logger.info("Creating client for: " + mqtt_url.hostname);
var options = {
port: mqtt_url.port,
host: mqtt_url.hostname,
var c = mqtt.connect(mqtt_url.href, {
username: auth[0],
password: auth[1]
}
var c = mqtt.connect(options);

});

c.on('connect', function() {
logger.info("Subscribe to topics...: " + topics);
logger.info("Subscribe to topics: " + topics);
c.subscribe(topics);
c.on('message', function(topic, message) {
topic = topic.toString().replace(/"/g, "\\\"");
var message = message.toString().replace(/"/g, "\\\"");
console.log(topic);
console.log(message);
executeShellCommand(topic,message);
var topic_outgoing = topic.replace(/\/set/g,'/get');
console.log("Reportig value back to topic: " + topic_outgoing);
c.publish(topic_outgoing,message,{retain: true});
});
});

function executeShellCommand(topic,payload){
c.on('message', function(topic, message) {
// Fix: message is a Buffer, convert to string first
var messageStr = message.toString().replace(/"/g, "\\\"");
var topicStr = topic.replace(/"/g, "\\\"");
executeShellCommand(topicStr, messageStr);

var topic_outgoing = topic.replace(/\/set/g, '');
console.log("Reporting value back to topic: " + topic_outgoing);
c.publish(topic_outgoing, message, {retain: true});
});

c.on('error', function(err) {
logger.error("MQTT connection error: " + err.message);
});

function executeShellCommand(topic, payload) {
// Fix: add null check
var commands = configuration[topic];
if (!commands) {
logger.warn("No configuration found for topic: " + topic);
return;
}
var command = commands[payload];
if (!command) {
logger.warn("No command found for payload: " + payload + " on topic: " + topic);
return;
}
logger.info("Executing command: " + command + " for topic: " + topic + " and payload: " + payload);
exec(command, puts);
sleep.sleep(1);//sleep for 1 seconds
}

function puts(error, stdout, stderr) {
util.puts(stdout);
logger.info("Executing Done");
function puts(error, stdout, stderr) {
// Fix: util.puts is deprecated, use console.log
if (error) {
logger.error("Exec error: " + error.message);
return;
}
if (stdout) {
console.log(stdout);
}
if (stderr) {
logger.error("stderr: " + stderr);
}
logger.info("Executing done");
}