forked from maxwellhadley/node-red-contrib-ipc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipc.js
95 lines (84 loc) · 3.13 KB
/
ipc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Copyright 2016 Maxwell Hadley
*
* Licensed under the BSD 2-clause license - see accompanying LICENSE file
**/
module.exports = function(RED) {
"use strict";
var debugOption = false,
lineEnd = "\n",
net = require("net"),
fs = require("fs");
// Set the ipc debug option from the environment variable
if (process.env.hasOwnProperty("RED_DEBUG") && process.env.RED_DEBUG.toLowerCase().indexOf("ipc") >= 0) {
debugOption = true;
}
// Detect platform type and adjust defaults accordingly
if (require("os").platform() === "win32") {
lineEnd = "\r\n";
}
function ipcInNode(config) {
RED.nodes.createNode(this, config);
// node configuration
this.path = config.path;
this.topic = config.topic;
this.name = config.name;
var node = this;
node.status({fill:"yellow", shape:"ring", text:"disconnected"});
// Process the input buffers assuming they are utf-8 strings. Generate
// a new message for each line. Handles lines split across multiple data events
node.stringBuffer = "";
node.parser = function (data) {
if (debugOption) {
node.log("IPC on " + node.path + " - received data");
}
var parts, i, msg;
node.stringBuffer = node.stringBuffer + data.toString('utf8');
parts = node.stringBuffer.split(lineEnd);
for (i = 0; i < parts.length - 1; i += 1) {
msg = {topic:node.topic, payload:parts[i]};
node.send(msg);
}
node.stringBuffer = parts[parts.length-1];
};
node.server = net.createServer(function (connection) {
if (debugOption) {
node.log("IPC on " + node.path + " - client connected");
}
connection.on("data", node.parser);
if (debugOption) {
connection.on("end", function () {
if (debugOption) {
node.log("IPC on " + node.path + " - client disconnected");
}
});
}
});
node.server.on('error', function (e) {
// If the path exists, set status and retry at intervals
if (e.code == 'EADDRINUSE') {
if (debugOption) {
node.log("IPC: path " + node.path + " in use, retrying...");
}
node.status({fill:"red", shape:"ring", text:"Path in use"});
setTimeout(function () {
node.server.close();
node.server.listen(node.path);
}, 2000);
}
});
node.server.listen(node.path, function () {
if (debugOption){
node.log("IPC listening on " + node.path);
}
node.status({fill:"green", shape:"dot", text:"listening"})
});
node.on("close", function () {
node.server.close();
// Boot off anyone connected to the socket
node.server.unref();
});
}
// Register the node by name.
RED.nodes.registerType("IPC-in", ipcInNode);
};