diff --git a/mqtt-exec.js b/mqtt-exec.js index 0b636e3..703e12b 100755 --- a/mqtt-exec.js +++ b/mqtt-exec.js @@ -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') @@ -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"); }