Riorganizzato in cartelle e aggiunto tcp

This commit is contained in:
2020-04-16 18:41:44 +02:00
parent d97866933e
commit 2ea5fe3063
11 changed files with 1584 additions and 14 deletions
+332
View File
@@ -0,0 +1,332 @@
<script type="text/html" data-template-name="parser-consume">
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
<div class="form-row">
<label for="node-input-property"><i class="fa fa-ellipsis-h"></i> <span data-i18n="switch.label.property"></span></label>
<input type="text" id="node-input-property" style="width: 70%"/>
<input type="hidden" id="node-input-outputs"/>
</div>
<div class="form-row node-input-rule-container-row">
<ol id="node-input-rule-container"></ol>
</div>
<!--<div class="form-row">
<label>&nbsp;</label>
<input type="checkbox" id="node-input-elsenode" placeholder="" style="display:inline-block; width:auto; vertical-align:top;">
<label for="node-input-elsenode" style="width:70%;">Add <code>else</code> output</label>
</div>-->
<div class="form-row">
<select id="node-input-checkall" style="width:100%; margin-right:5px;">
<option value="true" data-i18n="switch.checkall">All matches</option>
<option value="false" data-i18n="switch.stopfirst">First match</option>
</select>
</div>
</script>
<script type="text/javascript">
(function () {
var operators = [
{ v: "eq", t: "==", kind: 'V' },
{ v: "regex", t: "/regex/", kind: 'V' }
];
function clipValueLength(v) {
if (v.length > 15) {
return v.substring(0, 15) + "...";
}
return v;
}
function prop2name(key) {
var result = RED.utils.parseContextKey(key);
return result.key;
}
function getValueLabel(t, v) {
if (t === 'str') {
return '"' + clipValueLength(v) + '"';
} else if (t === 'msg') {
return t + "." + clipValueLength(v);
} else if (t === 'flow' || t === 'global') {
return t + "." + clipValueLength(prop2name(v));
}
return clipValueLength(v);
}
RED.nodes.registerType('parser-consume', {
color: "#77aadd",
category: 'function',
defaults: {
name: { value: "" },
property: { value: "payload", required: true, validate: RED.validators.typedInput("propertyType") },
propertyType: { value: "msg" },
rules: { value: [{ t: "eq", v: "", vt: "str" }] },
checkall: { value: "true", required: true },
outputs: { value: 1 },
elsenode: { value: false }
},
inputs: 1,
outputs: 1,
outputLabels: function (index) {
var rule = this.rules[index];
var label = "";
if (rule) {
label = rule.v;
if (label == "") {
return "(empty)";
}
return label;
}
},
icon: "switch.svg",
label: function () {
return this.name || "Consume token";
},
labelStyle: function () {
return this.name ? "node_label_italic" : "";
},
oneditprepare: function () {
var node = this;
var previousValueType = { value: "prev", label: this._("switch.previous"), hasValue: false };
$("#node-input-property").typedInput({ default: this.propertyType || 'msg', types: ['msg', 'flow', 'global', 'jsonata', 'env'] });
var outputCount = $("#node-input-outputs").val("{}");
var andLabel = this._("switch.and");
var caseLabel = this._("switch.ignorecase");
function resizeRule(rule) {
var newWidth = rule.width();
var selectField = rule.find("select");
var type = selectField.val() || "";
var valueField = rule.find(".node-input-rule-value");
var typeField = rule.find(".node-input-rule-type-value");
var numField = rule.find(".node-input-rule-num-value");
var expField = rule.find(".node-input-rule-exp-value");
var keyField = rule.find(".node-input-rule-key-value");
var btwnField1 = rule.find(".node-input-rule-btwn-value");
var btwnField2 = rule.find(".node-input-rule-btwn-value2");
var selectWidth;
if (type.length < 4) {
selectWidth = 60;
} else if (type === "regex") {
selectWidth = 147;
} else {
selectWidth = 120;
}
selectField.width(selectWidth);
valueField.typedInput("width", (newWidth - selectWidth - 70));
}
$("#node-input-rule-container").css('min-height', '150px').css('min-width', '450px').editableList({
addItem: function (container, i, opt) {
if (!opt.hasOwnProperty('r')) {
opt.r = {};
}
var rule = opt.r;
if (!rule.hasOwnProperty('t')) {
rule.t = 'eq';
}
if (!opt.hasOwnProperty('i')) {
opt._i = Math.floor((0x99999 - 0x10000) * Math.random()).toString();
}
container.css({
overflow: 'hidden',
whiteSpace: 'nowrap'
});
var row = $('<div/>').appendTo(container);
var row2 = $('<div/>').appendTo(container);
var row3 = $('<div/>').appendTo(container);
var selectField = $('<select/>', { style: "width:120px; margin-left: 5px; text-align: center;" }).appendTo(row);
var group0 = $('<optgroup/>', { label: "value rules" }).appendTo(selectField);
for (var d in operators) {
if (operators[d].kind === 'V') {
group0.append($("<option></option>").val(operators[d].v).text(/^switch/.test(operators[d].t) ? node._(operators[d].t) : operators[d].t));
}
}
function createValueField() {
return $('<input/>', { class: "node-input-rule-value", type: "text", style: "margin-left: 5px;" }).appendTo(row).typedInput({ default: 'str', types: ['str'] });
}
function createTypeValueField() {
return $('<input/>', { class: "node-input-rule-type-value", type: "text", style: "margin-left: 5px;" }).appendTo(row).typedInput({
default: 'string', types: [
{ value: "string", label: RED._("common.type.string"), hasValue: false, icon: "red/images/typedInput/az.png" },
]
});
}
var valueField = null;
var numValueField = null;
var expValueField = null;
var btwnAndLabel = null;
var btwnValueField = null;
var btwnValue2Field = null;
var typeValueField = null;
var finalspan = $('<span/>', { style: "float: right;margin-top: 6px;" }).appendTo(row);
var desc_label = $('<span/>', {style:"width:100px;display:inline-block;"}).text("Help:").appendTo(row2);
var desc = $('<input/>', { class: "node-input-rule-help", type: "text", style: "margin-left: 5px; width:250px", placeholder:"Help description" }).appendTo(row2);
desc.val(rule.help || "");
var desc_label = $('<span/>', {style:"width:100px;display:inline-block;"}).text("Variable:").appendTo(row3);
var match_name = $('<input/>', { class: "node-input-rule-match_name", type: "text", style: "margin-left: 5px; width: 250px;", placeholder:"Matched variable name" }).appendTo(row3);
match_name.val(rule.match_name || "");
if (rule.type !== "regex") {
row3.hide();
}
finalspan.append(' &#8594; <span class="node-input-rule-index">' + (i + 1) + '</span> ');
selectField.on("change", function () {
var type = selectField.val();
if (type == "regex") {
row3.show();
} else {
row3.hide();
}
valueField.typedInput('hide');
if (!valueField) {
valueField = createValueField();
}
valueField.typedInput('show');
resizeRule(container);
});
selectField.val(rule.t);
if (!valueField) {
valueField = createValueField();
}
valueField.typedInput('value', rule.v);
valueField.typedInput('type', 'str');
selectField.change();
var currentOutputs = JSON.parse(outputCount.val() || "{}");
currentOutputs[opt.hasOwnProperty('i') ? opt.i : opt._i] = i;
outputCount.val(JSON.stringify(currentOutputs));
},
removeItem: function (opt) {
var currentOutputs = JSON.parse(outputCount.val() || "{}");
if (opt.hasOwnProperty('i')) {
currentOutputs[opt.i] = -1;
} else {
delete currentOutputs[opt._i];
}
var rules = $("#node-input-rule-container").editableList('items');
rules.each(function (i) {
$(this).find(".node-input-rule-index").html(i + 1);
var data = $(this).data('data');
currentOutputs[data.hasOwnProperty('i') ? data.i : data._i] = i;
});
outputCount.val(JSON.stringify(currentOutputs));
},
resizeItem: resizeRule,
sortItems: function (rules) {
var currentOutputs = JSON.parse(outputCount.val() || "{}");
var rules = $("#node-input-rule-container").editableList('items');
rules.each(function (i) {
$(this).find(".node-input-rule-index").html(i + 1);
var data = $(this).data('data');
currentOutputs[data.hasOwnProperty('i') ? data.i : data._i] = i;
});
outputCount.val(JSON.stringify(currentOutputs));
},
sortable: true,
removable: true
});
for (var i = 0; i < this.rules.length; i++) {
var rule = this.rules[i];
$("#node-input-rule-container").editableList('addItem', { r: rule, i: i });
}
},
oneditsave: function () {
var rules = $("#node-input-rule-container").editableList('items');
var node = this;
node.rules = [];
rules.each(function (i) {
var ruleData = $(this).data('data');
var rule = $(this);
var type = rule.find("select").val();
var r = { t: type };
r.v = rule.find(".node-input-rule-value").typedInput('value');
r.vt = rule.find(".node-input-rule-value").typedInput('type');
r.help = rule.find(".node-input-rule-help").val();
if(r.t == 'regex') {
r.match_name = rule.find(".node-input-rule-match_name").val();
}
node.rules.push(r);
});
this.propertyType = $("#node-input-property").typedInput('type');
},
oneditresize: function (size) {
var rows = $("#dialog-form>div:not(.node-input-rule-container-row)");
var height = size.height;
for (var i = 0; i < rows.length; i++) {
height -= $(rows[i]).outerHeight(true);
}
var editorRow = $("#dialog-form>div.node-input-rule-container-row");
height -= (parseInt(editorRow.css("marginTop")) + parseInt(editorRow.css("marginBottom")));
height += 16;
$("#node-input-rule-container").editableList('height', height);
}
});
})();
</script>
<script type="text/html" data-template-name="parser-entry-point">
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
<div class="form-row">
<label for="node-input-property"><i class="fa fa-ellipsis-h"></i> Property:</label>
<input type="text" id="node-input-property" style="width: 70%"/>
</div>
<div class="form-row">
<label for="node-input-help_keyword"><i class="fa fa-ellipsis-h"></i> Help keyword:</label>
<input type="text" id="node-input-help_keyword" style="width: 70%"/>
</div>
<div class="form-row node-text-editor-row">
<input type="hidden" id="node-input-help_text" autofocus="autofocus">
<div style="height: 250px; min-height:150px;" class="node-text-editor" id="node-input-help_text-editor"></div>
</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('parser-entry-point',{
category: 'function',
color: "#77aadd",
defaults: {
property: { value: "payload", required: true, validate: RED.validators.typedInput("propertyType") },
name: { value: "" },
help_text: {value: ""},
help_keyword: {value: "help"},
},
inputs: 1,
outputs: 2,
label: function() {
return this.name || "parser entry point";
},
oneditprepare: function() {
var that = this;
this.editor = RED.editor.createEditor({
id: 'node-input-help_text-editor',
value: $("#node-input-help_text").val()
});
this.editor.focus();
},
oneditsave: function() {
$("#node-input-help_text").val(this.editor.getValue());
this.editor.destroy();
delete this.editor;
},
oneditcancel: function() {
this.editor.destroy();
delete this.editor;
},
});
</script>
+170
View File
@@ -0,0 +1,170 @@
module.exports = function (RED) {
"use strict";
function format_usage(usage, prefix) {
if (!prefix) {
prefix = [];
}
let out = "";
for (let k in usage) {
if (!usage.hasOwnProperty(k))
continue;
if(typeof usage[k] == "object"){
out += format_usage(usage[k], prefix.concat([k]));
} else {
let ext = k != "" ? [k] : [];
out += prefix.concat(ext).join(" ") + ": " + usage[k] + "\n";
}
}
return out;
}
function depth_first(n, path) {
if (!path) {
path = [n.id];
}
if (!n) {
return null;
}
let usage = {};
if (n.type == 'parser-consume') {
for (let r_idx in n.rules) {
let r = n.rules[r_idx];
let key;
if (r.t == "regex") {
if (r.match_name){
key = `[${r.match_name}]`;
} else {
key = `[espressione]`;
}
} else {
key = r.v;
}
if (r.help) {
usage[key] = r.help;
} else {
let sub_usage = {};
for (let wire of n.wires[r_idx]) {
if (path.indexOf(wire) === -1) {
let sub_n = RED.nodes.getNode(wire);
let tmp_sub_usage = depth_first(sub_n, path + [wire]);
if (tmp_sub_usage !== null) {
Object.assign(sub_usage, tmp_sub_usage);
}
}
}
usage[key] = sub_usage;
}
}
}
return usage;
}
function ParserEntryPoint(n) {
RED.nodes.createNode(this, n);
this.property = n.property;
this.help_text = n.help_text;
this.help_keyword = n.help_keyword;
this.genera_errore = function(msg) {
let out = "";
if (msg && msg.token_parser && msg.token_parser.consumed_tokens.length > 0) {
let offending_token = msg.token_parser.consumed_tokens[msg.token_parser.consumed_tokens.length - 1];
if (offending_token == "") {
offending_token = "(vuoto)";
}
out += msg.token_parser.consumed_tokens.slice(0, -1).join(" ") +`: comando non riconosciuto: ${offending_token}.\n`;
if (this.help_keyword) {
let help_command = msg.token_parser.consumed_tokens.slice(0, -1).concat([this.help_keyword]).join(" ");
out += `Usa '${help_command}' per la guida.\n`;
}
}
return out;
}
this.genera_help = function (root, msg) {
let usages = {};
if (!root) {
for (let wire of root.wires[0]) {
Object.assign(usages, depth_first(RED.nodes.getNode(wire)));
}
} else {
usages = depth_first(root);
}
return format_usage(usages, msg.token_parser.consumed_tokens.slice(0,-1));
};
this.on("input", msg => {
RED.util.evaluateNodeProperty(this.property, "msg", this, msg,
(err, value) => {
if (err) {
this.error(`Can't evaluate msg.${this.property}`);
} else {
let tokens = value.trim().toLowerCase().split(" ");
msg.regex_matches = {};
msg.token_parser = {
new_tokens: tokens,
consumed_tokens: [],
help_keyword: this.help_keyword,
on_error: (msg, maybe_error) => {
let err = maybe_error ? maybe_error : this.genera_errore(msg);
this.send([undefined, err]);
},
on_help: (help_node, msg) => {
let err = this.genera_help(help_node, msg);
this.send([undefined, err]);
}
};
this.send([msg, undefined]);
};
});
});
}
RED.nodes.registerType("parser-entry-point", ParserEntryPoint);
function ConsumaToken(n) {
RED.nodes.createNode(this, n);
this.rules = n.rules;
this.behavior = n.behavior;
this.checkall = n.checkall;
function check_rule(r, token) {
switch (r.t) {
case "eq":
return token == r.v.toLowerCase();
case "regex":
let reg = new RegExp(r.v);
return token.match(reg);
}
}
this.on("input", msg => {
let token = msg.token_parser.new_tokens.shift() || "";
msg.token_parser.consumed_tokens.push(token);
if(token == msg.token_parser.help_keyword) {
msg.token_parser.on_help(this, msg);
return;
}
let out = [];
let n_matches = 0;
for (let r of this.rules) {
let matches = check_rule(r, token);
if (matches === true || (matches != null && matches.length && matches.length > 0)) {
if (matches.length > 0) {
msg.regex_matches[r.match_name] = matches;
}
out.push(msg);
n_matches += 1;
if (!this.checkall) {
break;
}
} else {
out.push(undefined);
}
}
if (n_matches == 0) {
msg.token_parser.on_error(msg);
return;
}
this.send(out);
});
}
RED.nodes.registerType("parser-consume", ConsumaToken);
}
+33
View File
@@ -0,0 +1,33 @@
<script type="text/html" data-template-name="my-debounce">
<div class="form-row">
<label for="node-input-delay"><i class="fa fa-wrench"></i> Delay</label>
<input type="text" id="node-input-delay">
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="node-red:common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]node-red:common.label.name">
</div>
</script>
<script type="text/html" data-help-name="my-debounce">
<p>Deduplica messaggi per valore del payload entro <code>delay</code>.</p>
</script>
<script type="text/javascript">
RED.nodes.registerType('my-debounce',{
category: 'function',
color: "#E6E0F8",
defaults: {
delay: { value: 1000, required: true, validate: RED.validators.number() },
name: { value: "" }
},
inputs: 1,
outputs: 1,
icon: "timer.png",
label: function() {
return this.name || "my-debounce";
}
});
</script>
+27
View File
@@ -0,0 +1,27 @@
module.exports = function (RED) {
"use strict";
function XMPPServerNode(n) {
RED.nodes.createNode(this, n);
this.delay_msec = n.delay;
//this.by_value = n.by_value;
this.recv = new Map();
this.on("input", msg => {
let msg_json = JSON.stringify(msg.payload);
let now = new Date();
for (let [key, val] of this.recv) {
if ((now.getTime() - val.getTime()) > this.delay_msec) {
this.recv.delete(key);
}
}
if (!this.recv.has(msg_json)) {
this.send(msg);
this.recv.set(msg_json, now);
}
});
}
RED.nodes.registerType("my-debounce", XMPPServerNode);
}
+57
View File
@@ -0,0 +1,57 @@
{
"tcpin": {
"label": {
"type": "Type",
"output": "Output",
"port": "port",
"host": "at host",
"payload": "payload(s)",
"delimited": "delimited by",
"close-connection": "Close connection after each message is sent?",
"decode-base64": "Decode Base64 message?",
"server": "Server",
"return": "Return",
"ms": "ms",
"chars": "chars"
},
"type": {
"listen": "Listen on",
"connect": "Connect to",
"reply": "Reply to TCP"
},
"output": {
"stream": "stream of",
"single": "single",
"buffer": "Buffer",
"string": "String",
"base64": "Base64 String"
},
"return": {
"timeout": "after a fixed timeout of",
"character": "when character received is",
"number": "a fixed number of chars",
"never": "never - keep connection open",
"immed": "immediately - don't wait for reply"
},
"status": {
"connecting": "connecting to __host__:__port__",
"connected": "connected to __host__:__port__",
"listening-port": "listening on port __port__",
"stopped-listening": "stopped listening on port",
"connection-from": "connection from __host__:__port__",
"connection-closed": "connection closed from __host__:__port__",
"connections": "__count__ connection",
"connections_plural": "__count__ connections"
},
"errors": {
"connection-lost": "connection lost to __host__:__port__",
"timeout": "timeout closed socket port __port__",
"cannot-listen": "unable to listen on port __port__, error: __error__",
"error": "error: __error__",
"socket-error": "socket error from __host__:__port__",
"no-host": "Host and/or port not set",
"connect-timeout": "connect timeout",
"connect-fail": "connect failed"
}
}
}
+286
View File
@@ -0,0 +1,286 @@
<!--
Copyright JS Foundation and other contributors, http://js.foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<script type="text/x-red" data-template-name="briq tcp in">
<div class="form-row">
<label for="node-input-server"><i class="fa fa-dot-circle-o"></i> <span data-i18n="tcpin.label.type"></span></label>
<select id="node-input-server" style="width:120px; margin-right:5px;">
<option value="server" data-i18n="tcpin.type.listen"></option>
<option value="client" data-i18n="tcpin.type.connect"></option>
</select>
<span data-i18n="tcpin.label.port"></span> <input type="text" id="node-input-port" style="width:65px">
</div>
<div class="form-row hidden" id="node-input-host-row" style="padding-left: 110px;">
<span data-i18n="tcpin.label.host"></span> <input type="text" id="node-input-host" placeholder="localhost" style="width: 60%;">
</div>
<div class="form-row">
<label><i class="fa fa-sign-out"></i> <span data-i18n="tcpin.label.output"></span></label>
<select id="node-input-datamode" style="width:110px;">
<option value="stream" data-i18n="tcpin.output.stream"></option>
<option value="single" data-i18n="tcpin.output.single"></option>
</select>
<select id="node-input-datatype" style="width:140px;">
<option value="buffer" data-i18n="tcpin.output.buffer"></option>
<option value="utf8" data-i18n="tcpin.output.string"></option>
<option value="base64" data-i18n="tcpin.output.base64"></option>
</select>
<span data-i18n="tcpin.label.payload"></span>
</div>
<div id="node-row-newline" class="form-row hidden" style="padding-left:110px;">
<span data-i18n="tcpin.label.delimited"></span> <input type="text" id="node-input-newline" style="width:110px;">
</div>
<div class="form-row">
<label for="node-input-topic"><i class="fa fa-tasks"></i> <span data-i18n="common.label.topic"></span></label>
<input type="text" id="node-input-topic" data-i18n="[placeholder]common.label.topic">
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('briq tcp in', {
category: 'network',
color: "Silver",
defaults: {
name: { value: "" },
server: { value: "server", required: true },
host: { value: "", validate: function (v) { return (this.server == "server") || v.length > 0; } },
port: { value: "", required: true, validate: RED.validators.number() },
datamode: { value: "stream" },
datatype: { value: "buffer" },
newline: { value: "" },
topic: { value: "" },
base64: {/*deprecated*/ value: false, required: true }
},
inputs: 0,
outputs: 1,
icon: "bridge-dash.svg",
label: function () {
return this.name || "tcp:" + (this.host ? this.host + ":" : "") + this.port;
},
labelStyle: function () {
return this.name ? "node_label_italic" : "";
},
oneditprepare: function () {
var updateOptions = function () {
var sockettype = $("#node-input-server").val();
if (sockettype == "client") {
$("#node-input-host-row").show();
} else {
$("#node-input-host-row").hide();
}
var datamode = $("#node-input-datamode").val();
var datatype = $("#node-input-datatype").val();
if (datamode == "stream") {
if (datatype == "utf8") {
$("#node-row-newline").show();
} else {
$("#node-row-newline").hide();
}
} else {
$("#node-row-newline").hide();
}
};
updateOptions();
$("#node-input-server").change(updateOptions);
$("#node-input-datatype").change(updateOptions);
$("#node-input-datamode").change(updateOptions);
}
});
</script>
<script type="text/x-red" data-template-name="briq tcp out">
<div class="form-row">
<label for="node-input-beserver"><i class="fa fa-dot-circle-o"></i> <span data-i18n="tcpin.label.type"></span></label>
<select id="node-input-beserver" style="width:150px; margin-right:5px;">
<option value="server" data-i18n="tcpin.type.listen"></option>
<option value="client" data-i18n="tcpin.type.connect"></option>
<option value="reply" data-i18n="tcpin.type.reply"></option>
</select>
<span id="node-input-port-row"><span data-i18n="tcpin.label.port"></span> <input type="text" id="node-input-port" style="width: 65px"></span>
</div>
<div class="form-row hidden" id="node-input-host-row" style="padding-left: 110px;">
<span data-i18n="tcpin.label.host"></span> <input type="text" id="node-input-host" style="width: 60%;">
</div>
<div class="form-row hidden" id="node-input-end-row">
<label>&nbsp;</label>
<input type="checkbox" id="node-input-end" style="display: inline-block; width: auto; vertical-align: top;">
<label for="node-input-end" style="width: 70%;"><span data-i18n="tcpin.label.close-connection"></span></label>
</div>
<div class="form-row">
<label>&nbsp;</label>
<input type="checkbox" id="node-input-base64" placeholder="base64" style="display: inline-block; width: auto; vertical-align: top;">
<label for="node-input-base64" style="width: 70%;"><span data-i18n="tcpin.label.decode-base64"></span></label>
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('briq tcp out', {
category: 'network',
color: "Silver",
defaults: {
host: { value: "", validate: function (v) { return (this.beserver != "client") || v.length > 0; } },
port: { value: "", validate: function (v) { return (this.beserver == "reply") || RED.validators.number()(v); } },
beserver: { value: "client", required: true },
base64: { value: false, required: true },
end: { value: false, required: true },
name: { value: "" }
},
inputs: 1,
outputs: 0,
icon: "bridge-dash.svg",
align: "right",
label: function () {
return this.name || "tcp:" + (this.host ? this.host + ":" : "") + this.port;
},
labelStyle: function () {
return (this.name) ? "node_label_italic" : "";
},
oneditprepare: function () {
var updateOptions = function () {
var sockettype = $("#node-input-beserver").val();
if (sockettype == "reply") {
$("#node-input-port-row").hide();
$("#node-input-host-row").hide();
$("#node-input-end-row").hide();
} else if (sockettype == "client") {
$("#node-input-port-row").show();
$("#node-input-host-row").show();
$("#node-input-end-row").show();
} else {
$("#node-input-port-row").show();
$("#node-input-host-row").hide();
$("#node-input-end-row").show();
}
};
updateOptions();
$("#node-input-beserver").change(updateOptions);
}
});
</script>
<script type="text/x-red" data-template-name="briq tcp request">
<div class="form-row">
<label for="node-input-server"><i class="fa fa-globe"></i> <span data-i18n="tcpin.label.server"></span></label>
<input type="text" id="node-input-server" placeholder="ip.address" style="width:45%">
<span data-i18n="tcpin.label.port"></span>
<input type="text" id="node-input-port" style="width:60px">
</div>
<div class="form-row">
<label for="node-input-out"><i class="fa fa-sign-out"></i> <span data-i18n="tcpin.label.return"></span></label>
<select type="text" id="node-input-out" style="width:54%;">
<option value="time" data-i18n="tcpin.return.timeout"></option>
<option value="char" data-i18n="tcpin.return.character"></option>
<option value="count" data-i18n="tcpin.return.number"></option>
<option value="sit" data-i18n="tcpin.return.never"></option>
<option value="immed" data-i18n="tcpin.return.immed"></option>
</select>
<input type="text" id="node-input-splitc" style="width:50px;">
<span id="node-units"></span>
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('briq tcp request', {
category: 'network',
color: "Silver",
defaults: {
server: { value: "" },
port: { value: "", validate: RED.validators.regex(/^(\d*|)$/) },
out: { value: "time", required: true },
splitc: { value: "0", required: true },
name: { value: "" }
},
inputs: 1,
outputs: 1,
icon: "bridge-dash.svg",
label: function () {
return this.name || "tcp:" + (this.server ? this.server + ":" : "") + this.port;
},
labelStyle: function () {
return this.name ? "node_label_italic" : "";
},
oneditprepare: function () {
var previous = null;
$("#node-input-out").on('focus', function () { previous = this.value; }).on("change", function () {
if (previous === null) { previous = $("#node-input-out").val(); }
if ($("#node-input-out").val() == "char") {
if (previous != "char") { $("#node-input-splitc").val("\\n"); }
$("#node-units").text("");
}
else if ($("#node-input-out").val() == "time") {
if (previous != "time") { $("#node-input-splitc").val("0"); }
$("#node-units").text(RED._("node-red:tcpin.label.ms"));
}
else if ($("#node-input-out").val() == "immed") {
if (previous != "immed") { $("#node-input-splitc").val(" "); }
$("#node-units").text("");
}
else if ($("#node-input-out").val() == "count") {
if (previous != "count") { $("#node-input-splitc").val("12"); }
$("#node-units").text(RED._("node-red:tcpin.label.chars"));
}
else {
if (previous != "sit") { $("#node-input-splitc").val(" "); }
$("#node-units").text("");
}
});
}
});
</script>
<script type="text/x-red" data-template-name="briq tcp close">
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
<input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('briq tcp close', {
category: 'network',
color: "Silver",
defaults: {
name: { value: "" },
},
inputs: 1,
outputs: 0,
icon: "bridge-dash.svg",
label: function () {
return this.name || "tcp: close";
},
labelStyle: function () {
return this.name ? "node_label_italic" : "";
},
});
</script>
+715
View File
@@ -0,0 +1,715 @@
/**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
module.exports = function(RED) {
"use strict";
var reconnectTime = RED.settings.socketReconnectTime||10000;
var socketTimeout = RED.settings.socketTimeout||null;
const msgQueueSize = RED.settings.tcpMsgQueueSize || 1000;
const Denque = require('denque');
var net = require('net');
var connectionPool = {};
/**
* Enqueue `item` in `queue`
* @param {Denque} queue - Queue
* @param {*} item - Item to enqueue
* @private
* @returns {Denque} `queue`
*/
const enqueue = (queue, item) => {
// drop msgs from front of queue if size is going to be exceeded
if (queue.length === msgQueueSize) { queue.shift(); }
queue.push(item);
return queue;
};
/**
* Shifts item off front of queue
* @param {Deque} queue - Queue
* @private
* @returns {*} Item previously at front of queue
*/
const dequeue = queue => queue.shift();
function TcpIn(n) {
RED.nodes.createNode(this,n);
this.host = n.host;
this.port = n.port * 1;
this.topic = n.topic;
this.stream = (!n.datamode||n.datamode=='stream'); /* stream,single*/
this.datatype = n.datatype||'buffer'; /* buffer,utf8,base64 */
this.newline = (n.newline||"").replace("\\n","\n").replace("\\r","\r");
this.base64 = n.base64;
this.server = (typeof n.server == 'boolean')?n.server:(n.server == "server");
this.closing = false;
this.connected = false;
var node = this;
var count = 0;
if (!node.server) {
var buffer = null;
var client;
var reconnectTimeout;
var end = false;
var setupTcpClient = function() {
node.log(RED._("tcpin.status.connecting",{host:node.host,port:node.port}));
node.status({fill:"grey",shape:"dot",text:"common.status.connecting"});
var id = (1+Math.random()*4294967295).toString(16);
client = net.connect(node.port, node.host, function() {
buffer = (node.datatype == 'buffer') ? Buffer.alloc(0) : "";
node.connected = true;
node.log(RED._("tcpin.status.connected",{host:node.host,port:node.port}));
node.status({fill:"green",shape:"dot",text:"common.status.connected"});
});
client.setKeepAlive(true,120000);
connectionPool[id] = client;
client.on('data', function (data) {
if (node.datatype != 'buffer') {
data = data.toString(node.datatype);
}
if (node.stream) {
var msg;
if ((node.datatype) === "utf8" && node.newline !== "") {
buffer = buffer+data;
var parts = buffer.split(node.newline);
for (var i = 0; i<parts.length-1; i+=1) {
msg = {topic:node.topic, payload:parts[i]};
msg._session = {type:"tcp",id:id};
node.send(msg);
}
buffer = parts[parts.length-1];
} else {
msg = {topic:node.topic, payload:data};
msg._session = {type:"tcp",id:id};
node.send(msg);
}
} else {
if ((typeof data) === "string") {
buffer = buffer+data;
} else {
buffer = Buffer.concat([buffer,data],buffer.length+data.length);
}
}
});
client.on('end', function() {
if (!node.stream || (node.datatype == "utf8" && node.newline !== "" && buffer.length > 0)) {
var msg = {topic:node.topic, payload:buffer};
msg._session = {type:"tcp",id:id};
if (buffer.length !== 0) {
end = true; // only ask for fast re-connect if we actually got something
node.send(msg);
}
buffer = null;
}
});
client.on('close', function() {
delete connectionPool[id];
node.connected = false;
node.status({fill:"red",shape:"ring",text:"common.status.disconnected"});
if (!node.closing) {
if (end) { // if we were asked to close then try to reconnect once very quick.
end = false;
reconnectTimeout = setTimeout(setupTcpClient, 20);
}
else {
node.log(RED._("tcpin.errors.connection-lost",{host:node.host,port:node.port}));
reconnectTimeout = setTimeout(setupTcpClient, reconnectTime);
}
} else {
if (node.doneClose) { node.doneClose(); }
}
});
client.on('error', function(err) {
node.log(err);
});
}
setupTcpClient();
this.on('close', function(done) {
node.doneClose = done;
this.closing = true;
if (client) { client.destroy(); }
clearTimeout(reconnectTimeout);
if (!node.connected) { done(); }
});
}
else {
var server = net.createServer(function (socket) {
socket.setKeepAlive(true,120000);
if (socketTimeout !== null) { socket.setTimeout(socketTimeout); }
var id = (1+Math.random()*4294967295).toString(16);
var fromi;
var fromp;
connectionPool[id] = socket;
count++;
node.status({
text:RED._("tcpin.status.connections",{count:count}),
event:"connect",
ip:socket.remoteAddress,
port:socket.remotePort,
_session: {type:"tcp",id:id}
});
var buffer = (node.datatype == 'buffer') ? Buffer.alloc(0) : "";
socket.on('data', function (data) {
if (node.datatype != 'buffer') {
data = data.toString(node.datatype);
}
if (node.stream) {
var msg;
if ((typeof data) === "string" && node.newline !== "") {
buffer = buffer+data;
var parts = buffer.split(node.newline);
for (var i = 0; i<parts.length-1; i+=1) {
msg = {topic:node.topic, payload:parts[i], ip:socket.remoteAddress, port:socket.remotePort};
msg._session = {type:"tcp",id:id};
node.send(msg);
}
buffer = parts[parts.length-1];
} else {
msg = {topic:node.topic, payload:data, ip:socket.remoteAddress, port:socket.remotePort};
msg._session = {type:"tcp",id:id};
node.send(msg);
}
}
else {
if ((typeof data) === "string") {
buffer = buffer+data;
} else {
buffer = Buffer.concat([buffer,data],buffer.length+data.length);
}
fromi = socket.remoteAddress;
fromp = socket.remotePort;
}
});
socket.on('end', function() {
if (!node.stream || (node.datatype === "utf8" && node.newline !== "")) {
if (buffer.length > 0) {
var msg = {topic:node.topic, payload:buffer, ip:fromi, port:fromp};
msg._session = {type:"tcp",id:id};
node.send(msg);
}
buffer = null;
}
});
socket.on('timeout', function() {
node.log(RED._("tcpin.errors.timeout",{port:node.port}));
socket.end();
});
socket.on('close', function() {
delete connectionPool[id];
count--;
node.status({
text:RED._("tcpin.status.connections",{count:count}),
event:"disconnect",
ip:socket.remoteAddress,
port:socket.remotePort,
_session: {type:"tcp",id:id}
});
});
socket.on('error',function(err) {
node.log(err);
});
});
server.on('error', function(err) {
if (err) {
node.error(RED._("tcpin.errors.cannot-listen",{port:node.port,error:err.toString()}));
}
});
server.listen(node.port, function(err) {
if (err) {
node.error(RED._("tcpin.errors.cannot-listen",{port:node.port,error:err.toString()}));
} else {
node.log(RED._("tcpin.status.listening-port",{port:node.port}));
node.on('close', function() {
for (var c in connectionPool) {
if (connectionPool.hasOwnProperty(c)) {
connectionPool[c].end();
connectionPool[c].unref();
}
}
node.closing = true;
server.close();
node.log(RED._("tcpin.status.stopped-listening",{port:node.port}));
});
}
});
}
}
RED.nodes.registerType("briq tcp in",TcpIn);
function TcpOut(n) {
RED.nodes.createNode(this,n);
this.host = n.host;
this.port = n.port * 1;
this.base64 = n.base64;
this.doend = n.end || false;
this.beserver = n.beserver;
this.name = n.name;
this.closing = false;
this.connected = false;
var node = this;
if (!node.beserver||node.beserver=="client") {
var reconnectTimeout;
var client = null;
var end = false;
var setupTcpClient = function() {
node.log(RED._("tcpin.status.connecting",{host:node.host,port:node.port}));
node.status({fill:"grey",shape:"dot",text:"common.status.connecting"});
client = net.connect(node.port, node.host, function() {
node.connected = true;
node.log(RED._("tcpin.status.connected",{host:node.host,port:node.port}));
node.status({fill:"green",shape:"dot",text:"common.status.connected"});
});
client.setKeepAlive(true,120000);
client.on('error', function (err) {
node.log(RED._("tcpin.errors.error",{error:err.toString()}));
});
client.on('end', function (err) {
node.status({});
node.connected = false;
});
client.on('close', function() {
node.status({fill:"red",shape:"ring",text:"common.status.disconnected"});
node.connected = false;
client.destroy();
if (!node.closing) {
if (end) {
end = false;
reconnectTimeout = setTimeout(setupTcpClient,20);
}
else {
node.log(RED._("tcpin.errors.connection-lost",{host:node.host,port:node.port}));
reconnectTimeout = setTimeout(setupTcpClient,reconnectTime);
}
} else {
if (node.doneClose) { node.doneClose(); }
}
});
}
setupTcpClient();
node.on("input", function(msg,nodeSend,nodeDone) {
if (node.connected && msg.payload != null) {
if (Buffer.isBuffer(msg.payload)) {
client.write(msg.payload);
} else if (typeof msg.payload === "string" && node.base64) {
client.write(Buffer.from(msg.payload,'base64'));
} else {
client.write(Buffer.from(""+msg.payload));
}
if (node.doend === true) {
end = true;
if (client) { node.status({}); client.destroy(); }
}
}
nodeDone();
});
node.on("close", function(done) {
node.doneClose = done;
this.closing = true;
if (client) { client.destroy(); }
clearTimeout(reconnectTimeout);
if (!node.connected) { done(); }
});
}
else if (node.beserver == "reply") {
node.on("input",function(msg, nodeSend, nodeDone) {
if (msg._session && msg._session.type == "tcp") {
var client = connectionPool[msg._session.id];
if (client) {
if (Buffer.isBuffer(msg.payload)) {
client.write(msg.payload);
} else if (typeof msg.payload === "string" && node.base64) {
client.write(Buffer.from(msg.payload,'base64'));
} else {
client.write(Buffer.from(""+msg.payload));
}
}
}
else {
for (var i in connectionPool) {
if (Buffer.isBuffer(msg.payload)) {
connectionPool[i].write(msg.payload);
} else if (typeof msg.payload === "string" && node.base64) {
connectionPool[i].write(Buffer.from(msg.payload,'base64'));
} else {
connectionPool[i].write(Buffer.from(""+msg.payload));
}
}
}
nodeDone();
});
}
else {
var connectedSockets = [];
node.status({text:RED._("tcpin.status.connections",{count:0})});
var server = net.createServer(function (socket) {
socket.setKeepAlive(true,120000);
if (socketTimeout !== null) { socket.setTimeout(socketTimeout); }
node.log(RED._("tcpin.status.connection-from",{host:socket.remoteAddress, port:socket.remotePort}));
connectedSockets.push(socket);
node.status({text:RED._("tcpin.status.connections",{count:connectedSockets.length})});
socket.on('timeout', function() {
node.log(RED._("tcpin.errors.timeout",{port:node.port}));
socket.end();
});
socket.on('close',function() {
node.log(RED._("tcpin.status.connection-closed",{host:socket.remoteAddress, port:socket.remotePort}));
connectedSockets.splice(connectedSockets.indexOf(socket),1);
node.status({text:RED._("tcpin.status.connections",{count:connectedSockets.length})});
});
socket.on('error',function() {
node.log(RED._("tcpin.errors.socket-error",{host:socket.remoteAddress, port:socket.remotePort}));
connectedSockets.splice(connectedSockets.indexOf(socket),1);
node.status({text:RED._("tcpin.status.connections",{count:connectedSockets.length})});
});
});
node.on("input", function(msg, nodeSend, nodeDone) {
if (msg.payload != null) {
var buffer;
if (Buffer.isBuffer(msg.payload)) {
buffer = msg.payload;
} else if (typeof msg.payload === "string" && node.base64) {
buffer = Buffer.from(msg.payload,'base64');
} else {
buffer = Buffer.from(""+msg.payload);
}
for (var i = 0; i < connectedSockets.length; i += 1) {
if (node.doend === true) { connectedSockets[i].end(buffer); }
else { connectedSockets[i].write(buffer); }
}
}
nodeDone();
});
server.on('error', function(err) {
if (err) {
node.error(RED._("tcpin.errors.cannot-listen",{port:node.port,error:err.toString()}));
}
});
server.listen(node.port, function(err) {
if (err) {
node.error(RED._("tcpin.errors.cannot-listen",{port:node.port,error:err.toString()}));
} else {
node.log(RED._("tcpin.status.listening-port",{port:node.port}));
node.on('close', function() {
for (var c in connectedSockets) {
if (connectedSockets.hasOwnProperty(c)) {
connectedSockets[c].end();
connectedSockets[c].unref();
}
}
server.close();
node.log(RED._("tcpin.status.stopped-listening",{port:node.port}));
});
}
});
}
}
RED.nodes.registerType("briq tcp out",TcpOut);
function TcpGet(n) {
RED.nodes.createNode(this,n);
this.server = n.server;
this.port = Number(n.port);
this.out = n.out;
this.splitc = n.splitc;
if (this.out === "immed") { this.splitc = -1; this.out = "time"; }
if (this.out !== "char") { this.splitc = Number(this.splitc); }
else {
if (this.splitc[0] == '\\') {
this.splitc = parseInt(this.splitc.replace("\\n",0x0A).replace("\\r",0x0D).replace("\\t",0x09).replace("\\e",0x1B).replace("\\f",0x0C).replace("\\0",0x00));
} // jshint ignore:line
if (typeof this.splitc == "string") {
if (this.splitc.substr(0,2) == "0x") {
this.splitc = parseInt(this.splitc);
}
else {
this.splitc = this.splitc.charCodeAt(0);
}
} // jshint ignore:line
}
var node = this;
var clients = {};
this.on("input", function(msg, nodeSend, nodeDone) {
var i = 0;
if ((!Buffer.isBuffer(msg.payload)) && (typeof msg.payload !== "string")) {
msg.payload = msg.payload.toString();
}
var host = node.server || msg.host;
var port = node.port || msg.port;
// Store client information independently
// the clients object will have:
// clients[id].client, clients[id].msg, clients[id].timeout
var connection_id = host + ":" + port;
if (connection_id !== node.last_id) {
node.status({});
node.last_id = connection_id;
}
clients[connection_id] = clients[connection_id] || {
msgQueue: new Denque(),
connected: false,
connecting: false
};
enqueue(clients[connection_id].msgQueue, {msg:msg,nodeSend:nodeSend, nodeDone: nodeDone});
clients[connection_id].lastMsg = msg;
if (!clients[connection_id].connecting && !clients[connection_id].connected) {
var buf;
if (this.out == "count") {
if (this.splitc === 0) { buf = Buffer.alloc(1); }
else { buf = Buffer.alloc(this.splitc); }
}
else { buf = Buffer.alloc(65536); } // set it to 64k... hopefully big enough for most TCP packets.... but only hopefully
clients[connection_id].client = net.Socket();
if (socketTimeout !== null) { clients[connection_id].client.setTimeout(socketTimeout);}
if (host && port) {
clients[connection_id].connecting = true;
clients[connection_id].client.connect(port, host, function() {
//node.log(RED._("tcpin.errors.client-connected"));
node.status({fill:"green",shape:"dot",text:"common.status.connected"});
if (clients[connection_id] && clients[connection_id].client) {
clients[connection_id].connected = true;
clients[connection_id].connecting = false;
let event;
while (event = dequeue(clients[connection_id].msgQueue)) {
clients[connection_id].client.write(event.msg.payload);
event.nodeDone();
}
if (node.out === "time" && node.splitc < 0) {
clients[connection_id].connected = clients[connection_id].connecting = false;
clients[connection_id].client.end();
delete clients[connection_id];
node.status({});
}
}
});
}
else {
node.warn(RED._("tcpin.errors.no-host"));
}
clients[connection_id].client.on('data', function(data) {
if (node.out === "sit") { // if we are staying connected just send the buffer
if (clients[connection_id]) {
const msg = clients[connection_id].lastMsg || {};
msg.payload = data;
nodeSend(RED.util.cloneMessage(msg));
}
}
// else if (node.splitc === 0) {
// clients[connection_id].msg.payload = data;
// node.send(clients[connection_id].msg);
// }
else {
for (var j = 0; j < data.length; j++ ) {
if (node.out === "time") {
if (clients[connection_id]) {
// do the timer thing
if (clients[connection_id].timeout) {
i += 1;
buf[i] = data[j];
}
else {
clients[connection_id].timeout = setTimeout(function () {
if (clients[connection_id]) {
clients[connection_id].timeout = null;
const msg = clients[connection_id].lastMsg || {};
msg.payload = Buffer.alloc(i+1);
buf.copy(msg.payload,0,0,i+1);
nodeSend(msg);
if (clients[connection_id].client) {
node.status({});
clients[connection_id].client.destroy();
delete clients[connection_id];
}
}
}, node.splitc);
i = 0;
buf[0] = data[j];
}
}
}
// count bytes into a buffer...
else if (node.out == "count") {
buf[i] = data[j];
i += 1;
if ( i >= node.splitc) {
if (clients[connection_id]) {
const msg = clients[connection_id].lastMsg || {};
msg.payload = Buffer.alloc(i);
buf.copy(msg.payload,0,0,i);
nodeSend(msg);
if (clients[connection_id].client) {
node.status({});
clients[connection_id].client.destroy();
delete clients[connection_id];
}
i = 0;
}
}
}
// look for a char
else {
buf[i] = data[j];
i += 1;
if (data[j] == node.splitc) {
if (clients[connection_id]) {
const msg = clients[connection_id].lastMsg || {};
msg.payload = Buffer.alloc(i);
buf.copy(msg.payload,0,0,i);
nodeSend(msg);
if (clients[connection_id].client) {
node.status({});
clients[connection_id].client.destroy();
delete clients[connection_id];
}
i = 0;
}
}
}
}
}
});
clients[connection_id].client.on('end', function() {
//console.log("END");
node.status({fill:"grey",shape:"ring",text:"common.status.disconnected"});
if (clients[connection_id] && clients[connection_id].client) {
clients[connection_id].connected = clients[connection_id].connecting = false;
clients[connection_id].client = null;
}
});
clients[connection_id].client.on('close', function() {
//console.log("CLOSE");
if (clients[connection_id]) {
clients[connection_id].connected = clients[connection_id].connecting = false;
}
var anyConnected = false;
for (var client in clients) {
if (clients[client].connected) {
anyConnected = true;
break;
}
}
if (node.doneClose && !anyConnected) {
clients = {};
node.doneClose();
}
});
clients[connection_id].client.on('error', function() {
//console.log("ERROR");
node.status({fill:"red",shape:"ring",text:"common.status.error"});
node.error(RED._("tcpin.errors.connect-fail") + " " + connection_id, msg);
if (clients[connection_id] && clients[connection_id].client) {
clients[connection_id].client.destroy();
delete clients[connection_id];
}
});
clients[connection_id].client.on('timeout',function() {
//console.log("TIMEOUT");
if (clients[connection_id]) {
clients[connection_id].connected = clients[connection_id].connecting = false;
node.status({fill:"grey",shape:"dot",text:"tcpin.errors.connect-timeout"});
//node.warn(RED._("tcpin.errors.connect-timeout"));
if (clients[connection_id].client) {
clients[connection_id].connecting = true;
clients[connection_id].client.connect(port, host, function() {
clients[connection_id].connected = true;
clients[connection_id].connecting = false;
node.status({fill:"green",shape:"dot",text:"common.status.connected"});
});
}
}
});
}
else if (!clients[connection_id].connecting && clients[connection_id].connected) {
if (clients[connection_id] && clients[connection_id].client) {
let event = dequeue(clients[connection_id].msgQueue)
clients[connection_id].client.write(event.msg.payload);
event.nodeDone();
}
}
});
this.on("close", function(done) {
node.doneClose = done;
for (var cl in clients) {
if (clients[cl].hasOwnProperty("client")) {
clients[cl].client.destroy();
}
}
node.status({});
// this is probably not necessary and may be removed
var anyConnected = false;
for (var c in clients) {
if (clients[c].connected) {
anyConnected = true;
break;
}
}
if (!anyConnected) { clients = {}; }
done();
});
}
RED.nodes.registerType("briq tcp request",TcpGet);
function TcpClose(n) {
RED.nodes.createNode(this,n);
this.name = n.name;
var node = this;
node.on("input",function(msg, nodeSend, nodeDone) {
if (msg._session && msg._session.type == "tcp") {
var client = connectionPool[msg._session.id];
if (client) {
client.destroy();
}
}
nodeDone();
});
}
RED.nodes.registerType("briq tcp close", TcpClose);
}
+155
View File
@@ -0,0 +1,155 @@
<script type="text/html" data-template-name="xmpp in">
<div class="form-row">
<label for="node-input-server"><i class="fa fa-bookmark"></i> Connect as</label>
<input type="text" id="node-input-server">
</div>
<div class="form-row">
<label for="node-input-to"><i class="fa fa-envelope"></i> Buddy</label>
<input type="text" id="node-input-to" placeholder="joe@blah.im">
</div>
<div class="form-row">
<label>&nbsp;</label>
<input type="checkbox" id="node-input-join" placeholder="" style="display:inline-block; width:auto; vertical-align:top;">
<label for="node-input-join" style="width:70%;">Is a Chat Room ?</label>
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name">
</div>
</script>
<script type="text/html" data-help-name="xmpp in">
<p>Connects to an XMPP server to receive messages.</p>
<p>The <b>Buddy</b> field is the jid of the buddy or room you want to receive messages from. Leave blank to receive from anyone.</p>
<p>Incoming messages will appear as <code>msg.payload</code> on the first output, while <code>msg.topic</code> will contain who it is from.
If part of a chat room then <code>msg.room</code> may also be set.</p>
<p>The second output will show the presence and status of a user in <code>msg.payload</code>. Again <code>msg.topic</code> will hold the users jid.</p>
</script>
<script type="text/javascript">
RED.nodes.registerType('xmpp in', {
category: 'social-input',
color: "#F4F492",
defaults: {
name: { value: "" },
server: { type: "xmpp-server", required: true },
to: { value: "" },
join: { value: false }
},
inputs: 0,
outputs: 2,
icon: "xmpp.png",
label: function () {
return this.name || "xmpp";
},
labelStyle: function () {
return (this.name) ? "node_label_italic" : "";
}
});
</script>
<script type="text/html" data-template-name="xmpp out">
<div class="form-row">
<label for="node-input-server"><i class="fa fa-bookmark"></i> Connect as</label>
<input type="text" id="node-input-server">
</div>
<div class="form-row">
<label>&nbsp;</label>
<input type="checkbox" id="node-input-sendObject" placeholder="" style="display:inline-block; width:auto; vertical-align:top;">
<label for="node-input-sendObject" style="width:70%;">Send complete msg object ?</label>
</div>
<div class="form-row">
<label for="node-input-to"><i class="fa fa-envelope"></i> To</label>
<input type="text" id="node-input-to" placeholder="joe@blah.im">
</div>
<div class="form-row">
<label>&nbsp;</label>
<input type="checkbox" id="node-input-join" placeholder="" style="display: inline-block; width: auto; vertical-align: top;">
<label for="node-input-join" style="width:70%;">Is a Chat Room ?</label>
</div>
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name">
</div>
<div class="form-tips">The <b>To</b> field is optional. If not set uses the <code>msg.topic</code> property of the message.</div>
</script>
<script type="text/html" data-help-name="xmpp out">
<p>Connects to an XMPP server to send messages.</p>
<p>The <b>To</b> field is optional. If not set the <code>msg.topic</code> property of the message is used.</p>
<p>If you are joining a room then the <b>To</b> field must be supplied.</p>
<p>You may also send a msg with <code>msg.presence</code> to set your presence to one of <i>chat, away, dnd</i> or <i>xa</i>.
If you do so then the <code>msg.payload</code> will set your status message.</p>
</script>
<script type="text/javascript">
RED.nodes.registerType('xmpp out', {
category: 'social-output',
color: "#F4F492",
defaults: {
name: { value: "" },
server: { type: "xmpp-server", required: true },
to: { value: "" },
join: { value: false },
sendObject: { value: false }
},
inputs: 1,
outputs: 0,
icon: "xmpp.png",
align: "right",
label: function () {
return this.name || "xmpp";
},
labelStyle: function () {
return (this.name) ? "node_label_italic" : "";
}
});
</script>
<script type="text/html" data-template-name="xmpp-server">
<div class="form-row node-input-server">
<label for="node-config-input-server"><i class="fa fa-bookmark"></i> Server</label>
<input class="input-append-left" type="text" id="node-config-input-server" placeholder="blah.im" style="width: 40%;" >
<label for="node-config-input-port" style="margin-left: 10px; width: 35px; "> Port</label>
<input type="text" id="node-config-input-port" placeholder="Port" style="width:45px">
</div>
<div class="form-row">
<label for="node-config-input-user"><i class="fa fa-user"></i> JID</label>
<input type="text" id="node-config-input-user" placeholder="joe@blah.im">
</div>
<div class="form-row">
<label for="node-config-input-nickname"><i class="fa fa-user"></i> Nickname</label>
<input type="text" id="node-config-input-nickname" placeholder="Joe (optional)">
</div>
<div class="form-row">
<label for="node-config-input-pass"><i class="fa fa-lock"></i> Password</label>
<input type="password" id="node-config-input-password">
</div>
</script>
<script type="text/javascript">
RED.nodes.registerType('xmpp-server', {
category: 'config',
defaults: {
server: { required: true },
port: { value: 5222, required: true, validate: RED.validators.number() },
user: { type: "text" },
nickname: { value: "" }
},
credentials: {
password: { type: "password" }
},
label: function () {
return this.user;
}
});
</script>
<script type="text/html" data-help-name="xmpp-server">
<p>The connection to an XMPP server to send and receive messages.</p>
<p>Connects to the standard C2S port 5222 on the server.</p>
<p>The JID is the full username of the client used to connect to the server
and must contain the resolvable fdqn of the server.</p>
<p>The nickname is optional.</p>
</script>
+270
View File
@@ -0,0 +1,270 @@
module.exports = function(RED) {
"use strict";
var XMPP = require('simple-xmpp');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
function XMPPServerNode(n) {
RED.nodes.createNode(this,n);
this.server = n.server;
this.port = n.port;
this.nickname = n.nickname;
this.username = n.user;
var credentials = this.credentials;
if (credentials) {
this.password = credentials.password;
}
this.client = new XMPP.SimpleXMPP();
this.connected = false;
var that = this;
this.client.con = function() {
if (that.connected === false ) {
that.connected = true;
that.client.connect({
jid : that.username,
password : that.password,
host : that.server,
port : that.port,
//skipPresence : true,
reconnect : true,
preferred : "PLAIN"
});
}
}
that.client.on('online', function(data) {
that.connected = true;
that.client.setPresence('online', data.jid.user+' is online');
that.log('connected as '+data.jid.user+' to '+data.jid._domain+":5222");
});
that.client.on('close', function() {
that.connected = false;
that.log('connection closed');
});
this.on("close", function(done) {
that.client.setPresence('offline');
that.client.disconnect();
if (that.client.conn) { that.client.conn.end(); }
that.client = null;
done();
});
}
RED.nodes.registerType("xmpp-server",XMPPServerNode,{
credentials: {
password: {type: "password"}
}
});
function XmppInNode(n) {
RED.nodes.createNode(this,n);
this.server = n.server;
this.serverConfig = RED.nodes.getNode(this.server);
this.nick = this.serverConfig.nickname || this.serverConfig.username.split("@")[0];
this.join = n.join || false;
this.sendAll = n.sendObject;
this.from = n.to || "";
var node = this;
var xmpp = this.serverConfig.client;
xmpp.on('online', function(data) {
node.status({fill:"green",shape:"dot",text:"connected"});
if ((node.join) && (node.from !== "")) {
// disable chat history
var to = node.to+'/'+node.nick;
var stanza = new xmpp.Element('presence', {"to": to}).
c('x', { xmlns: 'http://jabber.org/protocol/muc' }).
c('history', { maxstanzas:0, seconds:1 });
xmpp.conn.send(stanza);
xmpp.join(to);
}
});
// xmpp.on('chat', function(from, message) {
// var msg = { topic:from, payload:message };
// if (!node.join && ((node.from === "") || (node.from === from))) {
// node.send([msg,null]);
// }
// });
xmpp.on('stanza', function(stanza) {
if (stanza.is('message')) {
if (stanza.attrs.type == 'chat') {
//console.log(stanza);
var body = stanza.getChild('body');
if (body) {
var msg = { payload:body.getText() };
var ids = stanza.attrs.from.split('/');
if (ids[1].length !== 36) {
msg.topic = stanza.attrs.from
}
else { msg.topic = ids[0]; }
if (!node.join && ((node.from === "") || (node.from === stanza.attrs.from))) {
node.send([msg,null]);
}
}
}
}
});
xmpp.on('groupchat', function(conference, from, message, stamp) {
var msg = { topic:from, payload:message, room:conference };
if (from != node.nick) {
if ((node.join) && (node.from === conference)) {
node.send([msg,null]);
}
}
});
//xmpp.on('chatstate', function(from, state) {
//console.log('%s is currently %s', from, state);
//var msg = { topic:from, payload: {presence:state} };
//node.send([null,msg]);
//});
xmpp.on('buddy', function(jid, state, statusText) {
node.log(jid+" is "+state+" : "+statusText);
var msg = { topic:jid, payload: { presence:state, status:statusText} };
node.send([null,msg]);
});
// xmpp.on('groupbuddy', function(conference, from, state, statusText) {
// //console.log('%s: %s is in %s state - %s',conference, from, state, statusText);
// var msg = { topic:from, payload: { presence:state, status:statusText}, room:conference };
// });
xmpp.on('error', function(err) {
if (RED.settings.verbose) { node.log(err); }
if (err.hasOwnProperty("stanza")) {
if (err.stanza.name === 'stream:error') { node.error("stream:error - bad login id/pwd ?",err); }
else { node.error(err.stanza.name,err); }
node.status({fill:"red",shape:"ring",text:"bad login"});
}
else {
if (err.errno === "ETIMEDOUT") {
node.error("Timeout connecting to server",err);
node.status({fill:"red",shape:"ring",text:"timeout"});
}
else if (err === "XMPP authentication failure") {
node.error(err,err);
node.status({fill:"red",shape:"ring",text:"XMPP authentication failure"});
}
else {
node.error(err.errno,err);
node.status({fill:"red",shape:"ring",text:"error"});
}
}
});
xmpp.on('subscribe', function(from) {
xmpp.acceptSubscription(from);
});
// Now actually make the connection
try {
node.status({fill:"grey",shape:"dot",text:"connecting"});
xmpp.con();
}
catch(e) {
node.error("Bad xmpp configuration");
node.status({fill:"red",shape:"ring",text:"not connected"});
}
node.on("close", function() {
node.status({});
});
}
RED.nodes.registerType("xmpp in",XmppInNode);
function XmppOutNode(n) {
RED.nodes.createNode(this,n);
this.server = n.server;
this.serverConfig = RED.nodes.getNode(this.server);
this.nick = this.serverConfig.nickname || this.serverConfig.username.split("@")[0];
this.join = n.join || false;
this.sendAll = n.sendObject;
this.to = n.to || "";
var node = this;
var xmpp = this.serverConfig.client;
xmpp.on('online', function(data) {
node.status({fill:"green",shape:"dot",text:"connected"});
if ((node.join) && (node.from !== "")) {
// disable chat history
var to = node.to+'/'+node.nick;
var stanza = new xmpp.Element('presence', {"to": to}).
c('x', { xmlns: 'http://jabber.org/protocol/muc' }).
c('history', { maxstanzas:0, seconds:1 });
xmpp.conn.send(stanza);
xmpp.join(to);
}
});
xmpp.on('error', function(err) {
if (RED.settings.verbose) { node.log(err); }
if (err.hasOwnProperty("stanza")) {
if (err.stanza.name === 'stream:error') { node.error("stream:error - bad login id/pwd ?",err); }
else { node.error(err.stanza.name,err); }
node.status({fill:"red",shape:"ring",text:"bad login"});
}
else {
if (err.errno === "ETIMEDOUT") {
node.error("Timeout connecting to server",err);
node.status({fill:"red",shape:"ring",text:"timeout"});
}
else if (err === "XMPP authentication failure") {
node.error(err,err);
node.status({fill:"red",shape:"ring",text:"XMPP authentication failure"});
}
else {
node.error(err.errno,err);
node.status({fill:"red",shape:"ring",text:"error"});
}
}
});
// Now actually make the connection
try {
node.status({fill:"grey",shape:"dot",text:"connecting"});
xmpp.con();
}
catch(e) {
node.error("Bad xmpp configuration");
node.status({fill:"red",shape:"ring",text:"not connected"});
}
node.on("input", function(msg) {
if (msg.presence) {
if (['away', 'dnd', 'xa', 'chat'].indexOf(msg.presence) > -1 ) {
xmpp.setPresence(msg.presence, msg.payload);
}
else { node.warn("Can't set presence - invalid value: "+msg.presence); }
}
else {
var to = node.to || msg.topic || "";
if (to !== "") {
if (node.sendAll) {
xmpp.send(to, JSON.stringify(msg), node.join);
}
else if (msg.payload) {
if (typeof(msg.payload) === "object") {
xmpp.send(to, JSON.stringify(msg.payload), node.join);
}
else {
xmpp.send(to, msg.payload.toString(), node.join);
}
}
}
}
});
node.on("close", function() {
node.status({});
});
}
RED.nodes.registerType("xmpp out",XmppOutNode);
}