function SQLiteDBNodeIn(n) { RED.nodes.createNode(this,n); this.mydb = n.mydb; this.mydbConfig = RED.nodes.getNode(this.mydb); if (this.mydbConfig) { this.mydbConfig.connect(); this.dbname = n.db; var node = this; node.on("input", function(msg) { if (typeof msg.payload === 'string') { node.mydbConfig.connection.all(msg.payload, function(err, rows) { if (err) { node.warn(err); } else { msg.payload = rows; node.send(msg); } }); } else { if (typeof msg.topic !== 'string') node.error("msg.payload : the query is not defined as a string"); } }); } else { this.error("SQLite database not configured"); } }
function WebSocketOutNode(n) { RED.nodes.createNode(this,n); var node = this; this.server = n.server; this.serverConfig = RED.nodes.getNode(this.server); if (!this.serverConfig) { this.error("Missing server configuration"); } this.on("input", function(msg) { var payload; if (this.serverConfig.wholemsg) { delete msg._session; payload = JSON.stringify(msg); } else { payload = msg.payload; if (Buffer.isBuffer(payload)) { payload = payload.toString(); } else if (typeof payload === "object") { payload = JSON.stringify(payload); } else if (typeof payload !== "string") { payload = ""+payload; } } if (msg._session && msg._session.type == "websocket") { node.serverConfig.send(msg._session.id,payload); } else { node.serverConfig.broadcast(payload,function(error){ if(!!error){ node.warn("An error occurred while sending:" + inspect(error)); } }); } }); }
exec("gpio load spi",function(err,stdout,stderr) { if (err) { util.log('[37-rpi-piface.js] Error: "gpio load spi" command failed for some reason.'); } RED.nodes.registerType("rpi-piface in",PiFACEInNode); RED.nodes.registerType("rpi-piface out",PiFACEOutNode); });
function MysqlDBNodeIn(n) { RED.nodes.createNode(this,n); this.mydb = n.mydb; this.mydbConfig = RED.nodes.getNode(this.mydb); if (this.mydbConfig) { this.mydbConfig.connect(); var node = this; node.on("input", function(msg) { if (typeof msg.topic === 'string') { //console.log("query:",msg.topic); node.mydbConfig.connection.query(msg.topic, function(err, rows) { if (err) { node.warn(err); } else { msg.payload = rows; node.send(msg); } }); } else { if (typeof msg.topic !== 'string') node.error("msg.topic : the query is not defined as a string"); } }); } else { this.error("MySQL database not configured"); } }
function MongoOutNode(n) { RED.nodes.createNode(this,n); this.collection = n.collection; this.mongodb = n.mongodb; this.payonly = n.payonly || false; this.operation = n.operation; if (n.service == "_ext_") { var mongoConfig = RED.nodes.getNode(this.mongodb); if (mongoConfig) { this.url = mongoConfig.url; } } else if (n.service != "") { var mongoConfig = cfEnv.getService(n.service); if (mongoConfig) { this.url = mongoConfig.credentials.url||mongoConfig.credentials.uri||mongoConfig.credentials.json_url; } } if (this.url) { var node = this; ConnectionPool.get(this.url).then(function(db) { db.collection(node.collection, function(err,coll) { node.on("input",function(msg) { if (node.operation == "store") { delete msg._topic; if (node.payonly) { if (typeof msg.payload !== "object") { msg.payload = {"payload":msg.payload}; } coll.save(msg.payload,function(err,item){ if (err){node.error(err);} }); } else { coll.save(msg,function(err,item){if (err){node.error(err);}}); } } else if (node.operation == "insert") { delete msg._topic; if (node.payonly) { if (typeof msg.payload !== "object") { msg.payload = {"payload":msg.payload}; } coll.insert(msg.payload,function(err,item){ if (err){node.error(err);} }); } else { coll.insert(msg,function(err,item){if (err){node.error(err);}}); } } if (node.operation == "delete") { coll.remove(msg.payload, {w:1}, function(err, items){ if (err) node.error(err); }); } }); }); }).otherwise(function(err) { node.error(err); }); this.on("close", function() { if (this.url) { ConnectionPool.close(this.url); } }); } else { this.error("missing mongodb configuration"); } }
function SerialInNode(n) { RED.nodes.createNode(this,n); this.serial = n.serial; this.serialConfig = RED.nodes.getNode(this.serial); if (this.serialConfig) { var node = this; node.port = serialPool.get(this.serialConfig.serialport, this.serialConfig.serialbaud, this.serialConfig.databits, this.serialConfig.parity, this.serialConfig.stopbits, this.serialConfig.newline); this.port.on('data', function(msg) { node.send({ "payload": msg }); }); } else { this.error("missing serial config"); } this.on("close", function() { if (this.serialConfig) { try { serialPool.close(this.serialConfig.serialport); } catch(err) { } } }); }
function WebSocketInNode(n) { RED.nodes.createNode(this,n); this.server = n.server; var node = this; this.serverConfig = RED.nodes.getNode(this.server); if (this.serverConfig) { this.serverConfig.registerInputNode(this); } else { this.error("Missing server configuration"); } }
req.on('end', function(){ var newCreds = querystring.parse(body); var credentials = RED.nodes.getCredentials(req.params.id)||{}; if (newCreds.pushkey == "") { delete credentials.pushkey; } else { credentials.pushkey = newCreds.pushkey||credentials.pushkey; } RED.nodes.addCredentials(req.params.id,credentials); res.send(200); });
function HTTPRequest(n) { RED.nodes.createNode(this,n); var nodeUrl = n.url; var isTemplatedUrl = (nodeUrl||"").indexOf("{{") != -1; var nodeMethod = n.method || "GET"; var node = this; var credentials = RED.nodes.getCredentials(n.id); this.on("input",function(msg) { if (msg.url) { url = msg.url; } else if (isTemplatedUrl) { url = mustache.render(nodeUrl,msg); } else { url = nodeUrl; } var url = msg.url||nodeUrl; var method = (msg.method||nodeMethod).toUpperCase(); var opts = urllib.parse(url); opts.method = method; if (msg.headers) { opts.headers = msg.headers; } if (credentials) { opts.auth = credentials.user+":"+(credentials.password||""); } var req = ((/^https/.test(url))?https:http).request(opts,function(res) { res.setEncoding('utf8'); msg.statusCode = res.statusCode; msg.headers = res.headers; msg.payload = ""; res.on('data',function(chunk) { msg.payload += chunk; }); res.on('end',function() { node.send(msg); }); }); req.on('error',function(err) { msg.payload = err.toString(); msg.statusCode = err.code; node.send(msg); }); if (msg.payload && (method == "POST" || method == "PUT") ) { if (typeof msg.payload === "string" || Buffer.isBuffer(msg.payload)) { req.write(msg.payload); } else if (typeof msg.payload == "number") { req.write(msg.payload+""); } else { req.write(JSON.stringify(msg.payload)); } } req.end(); }); }
function MQTTBrokerNode(n) { RED.nodes.createNode(this,n); this.broker = n.broker; this.port = n.port; this.clientid = n.clientid; var credentials = RED.nodes.getCredentials(n.id); if (credentials) { this.username = credentials.user; this.password = credentials.password; } }
// The Input Node function IrcInNode(n) { RED.nodes.createNode(this,n); this.ircserver = n.ircserver; this.serverConfig = RED.nodes.getNode(this.ircserver); this.channel = n.channel || this.serverConfig.channel; if (this.serverConfig.ircclient == null) { this.serverConfig.ircclient = new irc.Client(this.serverConfig.server, this.serverConfig.nickname, { channels: [this.channel] }); this.serverConfig.ircclient.addListener('error', function(message) { util.log('[irc] '+ JSON.stringify(message)); }); } this.ircclient = this.serverConfig.ircclient; var node = this; this.ircclient.addListener('message', function (from, to, message) { //util.log(from + ' => ' + to + ': ' + message); var msg = { "topic":from, "from":from, "to":to, "payload":message }; node.send([msg,null]); }); this.ircclient.addListener('pm', function(from, message) { var msg = { "topic":from, "from":from, "to":"PRIV", "payload":message }; node.send([msg,null]); }); this.ircclient.addListener('join', function(channel, who) { var msg = { "payload": { "type":"join", "who":who, "channel":channel } }; node.send([null,msg]); node.log(who+' has joined '+channel); }); this.ircclient.addListener('invite', function(channel, from, message) { var msg = { "payload": { "type":"invite", "who":from, "channel":channel, "message":message } }; node.send([null,msg]); node.log(from+' sent invite to '+channel+': '+message); }); this.ircclient.addListener('part', function(channel, who, reason) { var msg = { "payload": { "type":"part", "who":who, "channel":channel, "reason":reason } }; node.send([null,msg]); node.log(who+'has left '+channel+': '+reason); }); this.ircclient.addListener('quit', function(nick, reason, channels, message) { var msg = { "payload": { "type":"quit", "who":nick, "channel":channels, "reason":reason } }; node.send([null,msg]); node.log(nick+'has quit '+channels+': '+reason); }); this.ircclient.addListener('kick', function(channel, who, by, reason) { var msg = { "payload": { "type":"kick", "who":who, "channel":channel, "by":by, "reason":reason } }; node.send([null,msg]); node.log(who+' was kicked from '+channel+' by '+by+': '+reason); }); }
function MongoOutNode(n) { RED.nodes.createNode(this,n); this.collection = n.collection; this.mongodb = n.mongodb; this.payonly = n.payonly || false; this.operation = n.operation; this.mongoConfig = RED.nodes.getNode(this.mongodb); if (this.mongoConfig) { var node = this; this.clientDb = new mongo.Db(node.mongoConfig.db, new mongo.Server(node.mongoConfig.hostname, node.mongoConfig.port, {}), {w: 1}); this.clientDb.open(function(err,cli) { if (err) { node.error(err); } else { node.clientDb.collection(node.collection,function(err,coll) { if (err) { node.error(err); } else { node.on("input",function(msg) { if (node.operation == "store") { delete msg._topic; if (node.payonly) { if (typeof msg.payload !== "object") { msg.payload = {"payload":msg.payload}; } coll.save(msg.payload,function(err,item){ if (err){node.error(err);} }); } else coll.save(msg,function(err,item){if (err){node.error(err);}}); } else if (node.operation == "insert") { delete msg._topic; if (node.payonly) { if (typeof msg.payload !== "object") { msg.payload = {"payload":msg.payload}; } coll.insert(msg.payload,function(err,item){ if (err){node.error(err);} }); } else coll.insert(msg,function(err,item){if (err){node.error(err);}}); } if (node.operation == "delete") { coll.remove(msg.payload, {w:1}, function(err, items){ if (err) node.error(err); }); } }); } }); } }); } else { this.error("missing mongodb configuration"); } this.on("close", function() { if (this.clientDb) { this.clientDb.close(); } }); }
function MongoInNode(n) { RED.nodes.createNode(this,n); this.collection = n.collection; this.mongodb = n.mongodb; if (n.service == "_ext_") { var mongoConfig = RED.nodes.getNode(this.mongodb); if (mongoConfig) { this.url = mongoConfig.url; } } else if (n.service != "") { var mongoConfig = cfEnv.getService(n.service); if (mongoConfig) { this.url = mongoConfig.credentials.url||mongoConfig.credentials.uri||mongoConfig.credentials.json_url; } } if (this.url) { var node = this; ConnectionPool.get(this.url).then(function(db) { db.collection(node.collection,function(err,coll) { node.on("input",function(msg) { msg.projection = msg.projection || {}; coll.find(msg.payload,msg.projection).sort(msg.sort).limit(msg.limit).toArray(function(err, items) { if (err) { node.error(err); } else { msg.payload = items; delete msg.projection; delete msg.sort; delete msg.limit; node.send(msg); } }); }); }); }).otherwise(function(err) { node.error(err); }); this.on("close", function() { if (this.url) { ConnectionPool.close(this.url); } }); } else { this.error("missing mongodb configuration"); } }
function PushbulletNode(n) { RED.nodes.createNode(this,n); this.title = n.title; var node = this; this.on("input",function(msg) { var titl = this.title||msg.topic||"Node-RED"; if (typeof(msg.payload) === 'object') { msg.payload = JSON.stringify(msg.payload); } else { msg.payload = msg.payload.toString(); } if (pushkey.pushbullet && pushkey.deviceid) { try { if (!isNaN(deviceId)) { deviceId = Number(deviceId); } pusher.note(deviceId, titl, msg.payload, function(err, response) { if (err) node.error("Pushbullet error: "+err); //console.log(response); }); } catch (err) { node.error(err); } } else { node.warn("Pushbullet credentials not set/found. See node info."); } }); }
function MPDOut(n) { RED.nodes.createNode(this,n); var node = this; node.mpc = mpc; if (mpc != null) { this.on("input", function(msg) { if (msg != null) { console.log(msg); try { //node.mpc.command(msg.payload); node.mpc.command(msg.payload, msg.param, function(err, results) { if (err) { console.log("MPD: Error:",err); } //else { console.log(results); } }); } catch (err) { console.log("MPD: Error:",err); } } }); node.mpc.on('error', function(err) { console.log("MPD: Error:",err); }); } else { node.warn("MPD not running"); } }
function FolderNode(n) { RED.nodes.createNode(this,n); this.folderpath = n.folderpath; this.filepath = n.filepath; this.fileparametername = n.fileparametername; this.listfiles = n.listfiles; this.defaultfile = n.defaultfile; var node = this; this.on("input",function(msg) { var file = (n.filepath=="URL")? ((msg.req.url==="/")?msg.req.url+node.defaultfile:msg.req.url) :msg.payload[node.fileparametername]; var filePath = "."+decodeURIComponent((node.folderpath+"/"+file).replace(/[\/\/\\\\]{2,}/g,"/").split("?")[0]); if(fs.existsSync(filePath)&&fs.lstatSync(filePath).isFile()){ msg.res.sendfile(filePath); }else{ if(node.listfiles){ var listPath = filePath.split("/"); listPath = listPath.splice(0,listPath.length-1).join("/"); console.log(listPath); msg.res.send(JSON.stringify(fs.readdirSync(listPath))); }else{ msg.res.statusCode = "404"; msg.res.send("<h1>File Not Found: "+filePath+"</h1>"); } } }); }
function PiFACEInNode(n) { RED.nodes.createNode(this,n); this.buttonState = -1; this.pin = pintable[n.pin]; this.intype = n.intype; var node = this; if (node.pin) { exec("gpio -p mode "+node.pin+" "+node.intype, function(err,stdout,stderr) { if (err) node.error(err); else { node._interval = setInterval( function() { exec("gpio -p read "+node.pin, function(err,stdout,stderr) { if (err) node.error(err); else { if (node.buttonState !== Number(stdout)) { var previousState = node.buttonState; node.buttonState = Number(stdout); if (previousState !== -1) { var msg = {topic:"piface/"+tablepin[node.pin], payload:node.buttonState}; node.send(msg); } } } }); }, 200); } }); } else { node.error("Invalid PiFACE pin: "+node.pin); } node.on("close", function() { clearInterval(node._interval); }); }
function RangeNode(n) { RED.nodes.createNode(this, n); this.action = n.action; this.round = n.round || false; this.minin = Number(n.minin); this.maxin = Number(n.maxin); this.minout = Number(n.minout); this.maxout = Number(n.maxout); var node = this; this.on('input', function (msg) { var n = Number(msg.payload); if (!isNaN(n)) { if (node.action == "clamp") { if (n < node.minin) { n = node.minin; } if (n > node.maxin) { n = node.maxin; } } if (node.action == "roll") { if (n >= node.maxin) { n = (n - node.minin) % (node.maxin - node.minin) + node.minin; } if (n < node.minin) { n = (n - node.minin) % (node.maxin - node.minin) + node.maxin; } } msg.payload = ((n - node.minin) / (node.maxin - node.minin) * (node.maxout - node.minout)) + node.minout; if (node.round) { msg.payload = Math.round(msg.payload); } node.send(msg); } else { node.log("Not a number: "+msg.payload); } }); }
function EmailNode(n) { RED.nodes.createNode(this,n); this.topic = n.topic; this.name = n.name; var node = this; this.on("input", function(msg) { //node.log("email :",this.id,this.topic," received",msg.payload); if (msg != null) { smtpTransport.sendMail({ from: emailkey.user, // sender address to: node.name, // comma separated list of receivers subject: msg.topic, // Subject line text: msg.payload // plaintext body }, function(error, response) { if (error) { node.error(error); } else { node.log("Message sent: " + response.message); } }); } }); }
function SwitchNode(n) { RED.nodes.createNode(this,n); this.rules = n.rules; this.property = n.property; var propertyParts = n.property.split("."); var node = this; this.on('input',function(msg) { var onward = []; var prop = propertyParts.reduce(function(obj,i) { return obj[i] },msg); for (var i=0;i<node.rules.length;i+=1) { var rule = node.rules[i]; if (operators[rule.t](prop,rule.v,rule.v2)) { onward.push(msg); } else { onward.push(null); } } this.send(onward); }); }
function BlinkStick(n) { RED.nodes.createNode(this,n); var p1 = /^\#[A-Fa-f0-9]{6}$/ var p2 = /[0-9]+,[0-9]+,[0-9]+/ this.led = blinkstick.findFirst(); // maybe try findAll() (one day) var node = this; this.on("input", function(msg) { if (msg != null) { if (Object.size(node.led) !== 0) { try { if (p2.test(msg.payload)) { var rgb = msg.payload.split(","); node.led.setColor(parseInt(rgb[0])&255, parseInt(rgb[1])&255, parseInt(rgb[2])&255); } else { node.led.setColor(msg.payload.toLowerCase().replace(/\s+/g,'')); } } catch (err) { node.warn("BlinkStick missing ?"); node.led = blinkstick.findFirst(); } } else { //node.warn("No BlinkStick found"); node.led = blinkstick.findFirst(); } } }); if (Object.size(node.led) === 0) { node.error("No BlinkStick found"); } }
function ProwlNode(n) { RED.nodes.createNode(this,n); this.title = n.title; this.priority = parseInt(n.priority); if (this.priority > 2) this.priority = 2; if (this.priority < -2) this.priority = -2; var node = this; this.on("input",function(msg) { var titl = this.title||msg.topic||"Node-RED"; var pri = msg.priority||this.priority; if (typeof(msg.payload) == 'object') { msg.payload = JSON.stringify(msg.payload); } else { msg.payload = msg.payload.toString(); } if (pushkey) { try { prowl.push(msg.payload, titl, { priority: pri }, function(err, remaining) { if (err) node.error(err); node.log( remaining + ' calls to Prowl api during current hour.' ); }); } catch (err) { node.error(err); } } else { node.warn("Prowl credentials not set/found. See node info."); } }); }
req.on('end', function(){ var newCreds = querystring.parse(body); var credentials = RED.nodes.getCredentials(req.params.id)||{}; if (newCreds.user == null || newCreds.user == "") { delete credentials.user; } else { credentials.user = newCreds.user; } if (newCreds.password == "") { delete credentials.password; } else { credentials.password = newCreds.password||credentials.password; } RED.nodes.addCredentials(req.params.id,credentials); res.send(200); });
function SwitchNode(n) { RED.nodes.createNode(this, n); this.rules = n.rules; this.property = n.property; this.checkall = n.checkall || "true"; var propertyParts = n.property.split("."), node = this; this.on('input', function (msg) { var onward = []; var prop = propertyParts.reduce(function (obj, i) { return obj[i] }, msg); var elseflag = true; for (var i=0; i<node.rules.length; i+=1) { var rule = node.rules[i]; var test = prop; if (rule.t == "else") { test = elseflag; elseflag = true; } if (operators[rule.t](test,rule.v, rule.v2)) { onward.push(msg); elseflag = false; if (node.checkall == "false") { break; } } else { onward.push(null); } } this.send(onward); }); }
RED.httpAdmin.post('/http-request/:id',function(req,res) { var newCreds = body.req; var credentials = RED.nodes.getCredentials(req.params.id)||{}; if (newCreds.user == null || newCreds.user == "") { delete credentials.user; } else { credentials.user = newCreds.user; } if (newCreds.password == "") { delete credentials.password; } else { credentials.password = newCreds.password||credentials.password; } RED.nodes.addCredentials(req.params.id,credentials); res.send(200); });
function MongoNode(n) { RED.nodes.createNode(this,n); this.hostname = n.hostname; this.port = n.port; this.db = n.db; this.name = n.name; }
function RedisOutNode(n) { RED.nodes.createNode(this,n); this.port = n.port||"6379"; this.hostname = n.hostname||"127.0.0.1"; this.key = n.key; this.structtype = n.structtype; this.client = redisConnectionPool.get(this.hostname,this.port); this.on("input", function(msg) { if (msg != null) { var k = this.key || msg.topic; if (k) { if (this.structtype == "string") { this.client.set(k,msg.payload); } else if (this.structtype == "hash") { var r = hashFieldRE.exec(msg.payload); if (r) { this.client.hset(k,r[1],r[2]); } else { this.warn("Invalid payload for redis hash"); } } else if (this.structtype == "set") { this.client.sadd(k,msg.payload); } else if (this.structtype == "list") { this.client.rpush(k,msg.payload); } } else { this.warn("No key or topic set"); } } }); }
function DebugNode(n) { RED.nodes.createNode(this,n); this.name = n.name; this.complete = n.complete; this.console = n.console; this.active = (n.active == null)||n.active; var node = this; this.on("input",function(msg) { if (this.complete == "true") { // debug complete msg object if (this.console == "true") { node.log("\n"+util.inspect(msg, {colors:useColors, depth:10})); } if (msg.payload instanceof Buffer) { msg.payload = "(Buffer) "+msg.payload.toString('hex'); } if (this.active) { DebugNode.send({id:this.id,name:this.name,topic:msg.topic,msg:msg,_path:msg._path}); } } else { // debug just the msg.payload if (this.console == "true") { if (typeof msg.payload === "string") { if (msg.payload.indexOf("\n") != -1) { msg.payload = "\n"+msg.payload; } node.log(msg.payload); } else if (typeof msg.payload === "object") { node.log("\n"+util.inspect(msg.payload, {colors:useColors, depth:10})); } else { node.log(util.inspect(msg.payload, {colors:useColors})); } } if (typeof msg.payload == "undefined") { msg.payload = "(undefined)"; } if (msg.payload instanceof Buffer) { msg.payload = "(Buffer) "+msg.payload.toString('hex'); } if (this.active) { DebugNode.send({id:this.id,name:this.name,topic:msg.topic,msg:msg.payload,_path:msg._path}); } } }); }
function HttpGet(n) { RED.nodes.createNode(this,n); this.baseurl = n.baseurl || ""; this.append = n.append || ""; var node = this; if (this.baseurl.substring(0,5) === "https") { var http = require("https"); } else { var http = require("http"); } this.on("input", function(msg) { msg._payload = msg.payload; //util.log("[httpget] "+this.baseurl+msg.payload+this.append); http.get(this.baseurl+msg.payload+this.append, function(res) { node.log("Http response: " + res.statusCode); msg.rc = res.statusCode; msg.payload = ""; if ((msg.rc != 200) && (msg.rc != 404)) { node.send(msg); } res.setEncoding('utf8'); res.on('data', function(chunk) { msg.payload += chunk; }); res.on('end', function() { node.send(msg); }); }).on('error', function(e) { //node.error(e); msg.rc = 503; msg.payload = e; node.send(msg); }); }); }
function SerialPortNode(n) { RED.nodes.createNode(this,n); this.serialport = n.serialport; this.serialbaud = n.serialbaud * 1; this.newline = n.newline; this.addchar = n.addchar || "false"; }