@teamcymbeline/node-red-contrib-mcprotocol 0.0.0-stage → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/nodes/read.js ADDED
@@ -0,0 +1,307 @@
1
+ /*
2
+ MIT License
3
+
4
+ Copyright (c) 2019, 2020 Steve-Mcl
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+
25
+ module.exports = function(RED) {
26
+ var connection_pool = require("../connection_pool.js");
27
+ function isNumeric(n) {
28
+ return !isNaN(parseFloat(n)) && isFinite(n);
29
+ }
30
+ function mcRead(config) {
31
+ RED.nodes.createNode(this, config);
32
+ this.name = config.name;
33
+ this.topic = config.topic;
34
+ this.connection = config.connection;
35
+ this.address = config.address || ""; //address
36
+ this.addressType = config.addressType || "str";
37
+ this.outputFormat = config.outputFormat || 0;
38
+ this.errorHandling = config.errorHandling;
39
+ this.outputs = config.errorHandling === "output2" ? 2 : 1;//1 output pins if throw or msg.error, 2 outputs if errors to go to seperate output pin
40
+ this.logLevel = RED.settings.logging.console.level;
41
+ this.connectionConfig = RED.nodes.getNode(this.connection);
42
+ var context = this.context();
43
+ var node = this;
44
+ node.busy = false;
45
+ //node.busyMonitor;
46
+ node.busyTimeMax = 1000; //Initial value, will be updated bt selected connection
47
+ //var mcprotocol = require('../mcprotocol.js');
48
+ if (this.connectionConfig) {
49
+ var options = Object.assign({}, node.connectionConfig.options);
50
+ options.logLevel = this.logLevel;
51
+ node.connection = connection_pool.get(
52
+ this.connectionConfig.port,
53
+ this.connectionConfig.host,
54
+ options
55
+ );
56
+ if(options.timeout && isNumeric(options.timeout)) node.busyTimeMax = parseInt(options.timeout);
57
+
58
+ node.status({ fill: "yellow", shape: "ring", text: "initialising" });
59
+
60
+ this.connection.on("error", function(error) {
61
+ console.error(error);
62
+ node.status({ fill: "red", shape: "ring", text: "error" });
63
+ node.busy = false;
64
+ });
65
+ this.connection.on("open", function(error) {
66
+ node.status({ fill: "green", shape: "dot", text: "connected" });
67
+ });
68
+ this.connection.on("close", function(error) {
69
+ node.status({ fill: "red", shape: "dot", text: "not connected" });
70
+ node.busy = false;
71
+ });
72
+ function handleError(err, msg, node, config, dont_send_msg){
73
+ if(typeof err === "string"){
74
+ err = new Error(err);
75
+ }
76
+ if(!config) config = {};
77
+ if(typeof config === "string"){
78
+ config = {
79
+ errorHandling: config
80
+ }
81
+ }
82
+ switch (config.errorHandling) {
83
+ case "throw":
84
+ node.error(err,msg);
85
+ break;
86
+ case "msg":
87
+ msg.error = err;
88
+ if(!dont_send_msg) node.send(msg);//send error on 1st pin
89
+ break;
90
+ case "output2":
91
+ node.send([null,{payload: err}]);//send error on 2nd pin
92
+ break;
93
+
94
+ default:
95
+ node.error(err,msg);
96
+ break;
97
+ }
98
+ }
99
+ function myReply(problem, msg) {
100
+ clearTimeout(node.busyMonitor);
101
+ if (!node.busy) {
102
+ return; //not busy - dont process the reply (node may have timed out)
103
+ }
104
+ node.busy = false; //reset busy - allow node to be triggered
105
+ node.msgMem.mcReadDetails = {};
106
+ node.msgMem.mcReadDetails.request = node.request;
107
+ node.msgMem.mcReadDetails.response = msg;
108
+ node.msgMem.mcReadDetails.timeout = msg.timeout; //TODO
109
+ node.msgMem.mcReadDetails.error = problem;
110
+ node.msgMem.payload = null;
111
+ if(problem){
112
+ msg.problem = true;
113
+ }
114
+ if (msg.timeout) {
115
+ node.status({ fill: "red", shape: "ring", text: "timeout" });
116
+ handleError("timeout", msg, config);
117
+ //node.error("timeout", msg);
118
+ var dbgmsg = {
119
+ f: "myReply(msg)",
120
+ msg: msg,
121
+ error: "timeout"
122
+ };
123
+ // console.error(dbgmsg);
124
+ node.msgMem.mcReadDetails.errorMsg = "timeout";
125
+ // node.send(node.msgMem);
126
+ return;
127
+ }
128
+
129
+ if (problem) {
130
+ node.status({ fill: "grey", shape: "ring", text: "Quality Issue" });
131
+ } else {
132
+ node.status({ fill: "green", shape: "dot", text: "Good" });
133
+ }
134
+
135
+ // msg.deviceCode
136
+ // msg.digitSpec
137
+ // msg.dataType
138
+ // msg.deviceNo
139
+ // msg.isGood
140
+ // msg.quality
141
+ // msg.TAG
142
+ // msg.addr
143
+ // msg.timeTaken
144
+ // msg.timeStamp
145
+ // msg.value
146
+ // msg.valueType
147
+
148
+ var data = msg.value;
149
+ if (data != null && !problem) {
150
+ let iWD = msg.deviceNo;
151
+ let loopBit = 0,
152
+ bitNo = msg.bitOffset;
153
+ let JSONData = {};
154
+ if (node.outputFormat == 0 /*JSON*/) {
155
+ if (msg.valueType == "CHAR") {
156
+ if (msg.deviceCodeNotation == "Hexadecimal") {
157
+ buff_address = `${msg.deviceCode}${Number(iWD)
158
+ .toString(16)
159
+ .toUpperCase()}`;
160
+ } else {
161
+ buff_address = `${msg.deviceCode}${iWD}`;
162
+ }
163
+ JSONData[buff_address] = data;
164
+ } else {
165
+ if(!Array.isArray(data)) data = [data];
166
+ for (var x in data) {
167
+ let buff_address = "";
168
+ if (msg.dataType == "BIT" && msg.deviceCodeType != "BIT") {
169
+ bitNo = msg.bitOffset + loopBit;
170
+ if (bitNo == 16) iWD++;
171
+ if (bitNo >= 16) {
172
+ bitNo = bitNo - 16;
173
+ }
174
+ if (msg.deviceCodeNotation == "Hexadecimal") {
175
+ buff_address = `${msg.deviceCode}${Number(iWD)
176
+ .toString(16)
177
+ .toUpperCase()}.${Number(bitNo)
178
+ .toString(16)
179
+ .toUpperCase()}`;
180
+ } else {
181
+ buff_address = `${msg.deviceCode}${iWD}.${Number(bitNo)
182
+ .toString(16)
183
+ .toUpperCase()}`;
184
+ }
185
+ JSONData[buff_address] = data[x];
186
+ loopBit++;
187
+ if (loopBit >= 16) loopBit = 0;
188
+ } else {
189
+ if (msg.deviceCodeNotation == "Hexadecimal") {
190
+ buff_address = `${msg.deviceCode}${Number(iWD)
191
+ .toString(16)
192
+ .toUpperCase()}`;
193
+ } else {
194
+ buff_address = `${msg.deviceCode}${iWD}`;
195
+ }
196
+ JSONData[buff_address] = data[x];
197
+ iWD += msg.dataTypeByteLength / 2;
198
+ }
199
+ }
200
+ }
201
+ node.msgMem.payload = JSONData;
202
+ } else {
203
+ node.msgMem.payload = data;
204
+ }
205
+ }
206
+ if(problem) {
207
+ handleError(msg.error || "", node.msgMem, node, node.errorHandling);
208
+ } else {
209
+ node.send(node.msgMem);
210
+ }
211
+ }
212
+
213
+ this.on("input", function(msg) {
214
+ if (msg.disconnect === true || msg.topic === "disconnect") {
215
+ this.connection.closeConnection();
216
+ return;
217
+ } else if (msg.connect === true || msg.topic === "connect") {
218
+ this.connection.connect();
219
+ return;
220
+ } else if (msg.reinitialize === true || msg.topic === "reinitialize") {
221
+ this.connection.reinitialize();
222
+ return;
223
+ }
224
+
225
+ if (node.busy) return; //TODO: Consider queueing inputs?
226
+
227
+ node.request = undefined;
228
+ node.msgMem = msg;
229
+
230
+ var addr;
231
+ RED.util.evaluateNodeProperty(
232
+ node.address,
233
+ node.addressType,
234
+ node,
235
+ msg,
236
+ (err, value) => {
237
+ if (err) {
238
+ handleError("Unable to evaluate address", msg, node, node.errorHandling);
239
+ //node.error("Unable to evaluate address", msg);
240
+ node.status({
241
+ fill: "red",
242
+ shape: "ring",
243
+ text: "Unable to evaluate address"
244
+ });
245
+ return;
246
+ } else {
247
+ addr = value;
248
+ }
249
+ }
250
+ );
251
+
252
+ if (addr == "") {
253
+ handleError("address is empty", msg, node, node.errorHandling);
254
+ //node.error("address is empty", msg);
255
+ node.status({ fill: "red", shape: "ring", text: "error" });
256
+ return;
257
+ }
258
+
259
+ try {
260
+ node.status({ fill: "yellow", shape: "ring", text: "read" });
261
+ node.busy = true;
262
+
263
+ node.request = {
264
+ outputFormat: node.outputFormat ? "Array" : "JSON",
265
+ address: addr,
266
+ timeStamp: Date.now()
267
+ };
268
+
269
+ if (node.busyTimeMax) {
270
+ node.busyMonitor = setTimeout(function() {
271
+ if (node.busy) {
272
+ node.status({ fill: "red", shape: "ring", text: "timeout" });
273
+ handleError("timeout", msg, node, node.errorHandling);
274
+ //node.error("timeout", msg || node.msgMem || {});
275
+ node.busy = false;
276
+ return;
277
+ }
278
+ }, node.busyTimeMax);
279
+ }
280
+ this.connection.read(addr, myReply);
281
+ } catch (error) {
282
+ node.busy = false;
283
+ handleError(error, msg, node, node.errorHandling);
284
+ //node.error(error, msg || node.msgMem || {});
285
+ node.status({ fill: "red", shape: "ring", text: "error" });
286
+ var dbgmsg = {
287
+ info: "read.js-->on 'input'",
288
+ connection: `host: ${node.connectionConfig.host}, port: ${node.connectionConfig.port}`,
289
+ address: addr
290
+ };
291
+ node.warn(dbgmsg);
292
+ return;
293
+ }
294
+ });
295
+ node.status({ fill: "green", shape: "ring", text: "ready" });
296
+ } else {
297
+ node.error("configuration not setup");
298
+ node.status({ fill: "red", shape: "ring", text: "error" });
299
+ }
300
+ }
301
+ RED.nodes.registerType("MC Read", mcRead);
302
+ mcRead.prototype.close = function() {
303
+ if (this.connection) {
304
+ this.connection.disconnect();
305
+ }
306
+ };
307
+ };
@@ -0,0 +1,185 @@
1
+ <!--
2
+ MIT License
3
+
4
+ Copyright (c) 2019, 2020 Steve-Mcl
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ -->
24
+
25
+ <script type="text/javascript">
26
+ function setupTypedInput(varName, types, def) {
27
+ let varSel = '#node-input-' + varName;
28
+ let typeSel = varSel + 'Type';
29
+ let varVal = this[varName];
30
+ let typeVal = this[varName + 'Type'];
31
+
32
+ if (typeVal == null || typeVal === 'none') {
33
+ typeVal = def;
34
+ } else if (typeVal === 'string') {
35
+ typeVal = "str";
36
+ } else if (typeVal === 'number') {
37
+ typeVal = "num";
38
+ }
39
+ $(typeSel).val(typeVal);
40
+ $(varSel).typedInput({
41
+ default: def,
42
+ typeField: $(typeSel),
43
+ types: types
44
+ });
45
+ $(varSel).typedInput('type', typeVal);
46
+ }
47
+ RED.nodes.registerType('MC Write', {
48
+ category: 'MITSUBISHI',
49
+ color: '#0090d4',
50
+ defaults: {
51
+ name: { value: "" },
52
+ topic: { value: "" },
53
+ connection: { type: "MC Protocol Connection", required: true },
54
+ data: { value: "" },
55
+ address: { value: "", validate: RED.validators.typedInput("addressType") },
56
+ addressType: { value: "str" },
57
+ data: { value: "", validate: RED.validators.typedInput("dataType") },
58
+ dataType: { value: "str" },
59
+ errorHandling: { value: "throw" },
60
+ outputs: { value: 1 }
61
+ },
62
+ inputs: 1,
63
+ outputs: 1,
64
+ inputLabels: "Trigger request",
65
+ outputLabels: "Write result",
66
+ align: "right",
67
+ icon: "write.png",
68
+ label: function () {
69
+ return this.name || "MC Write";
70
+ },
71
+ oneditprepare: function () {
72
+ var sti = setupTypedInput.bind(this);
73
+ sti('address', ['msg', 'flow', 'global', 'str', 'env'], 'str');//addr
74
+ sti('data', ['msg', 'flow', 'global','num','str', {
75
+ value: 'csv',
76
+ label: 'csv',
77
+ icon: "red/images/typedInput/09.png"
78
+ },], 'num');
79
+ },
80
+ oneditsave: function () {
81
+ var errH = $("#node-input-errorHandling").val();
82
+ this.outputs = errH === "output2" ? 2 : 1;//1 output pins if throw or msg.error, 2 outputs if errors to go to seperate output pin
83
+ }
84
+ });
85
+ </script>
86
+
87
+ <style>
88
+ .mc-protocol-form > .form-row > label {
89
+ width: 120px !important;
90
+ }
91
+ </style>
92
+
93
+ <script type="text/html" data-template-name="MC Write">
94
+ <div class="mc-protocol-form">
95
+ <div class="form-row">
96
+ <label for="node-input-name"><i class="icon-tag"></i> <span data-i18n="write.label.name"> Name</span></label>
97
+ <input type="text" id="node-input-name" placeholder="Name">
98
+ </div>
99
+ <div class="form-row">
100
+ <label for="node-input-connection"><i class="icon-globe"></i><span data-i18n="write.label.connection"> Connection</span></label>
101
+ <input type="text" id="node-input-connection">
102
+ </div>
103
+ <div class="form-row">
104
+ <label for="node-input-address"><i class="fa fa-envelope"></i><span data-i18n="ab-df1-read.label.address"> Address</span></label>
105
+ <input type="hidden" id="node-input-addressType">
106
+ <input style="width: 70%" type="text" id="node-input-address" placeholder="D0">
107
+ </div>
108
+ <div class="form-row">
109
+ <label for="node-input-data"><i class="fa fa-table"></i> <span data-i18n="write.label.data"> Data</span></label>
110
+ <input type="hidden" id="node-input-dataType">
111
+ <input style="width: 70%" type="text" id="node-input-data" >
112
+ </div>
113
+ <div class="form-row">
114
+ <label for="node-input-errorHandling"><i class="fa fa-exclamation"></i><span data-i18n="ab-df1-read.label.errors"> Errors</span></label>
115
+ <select style="width: 70%" id="node-input-errorHandling">
116
+ <option value="throw">Throw (default)</option>
117
+ <option value="msg">Output to msg.error</option>
118
+ <option value="output2">Send to seperate output</option>
119
+ </select>
120
+ </div>
121
+ </div>
122
+ </script>
123
+
124
+ <script type="text/html" data-help-name="MC Write">
125
+ <p>Write data to an MITSUBISHI PLC using mcprotocol protocol</p>
126
+ <h3>Inputs</h3>
127
+ <dl class="message-properties">
128
+ <dt class="required">Connection<span class="property-type">DF1 Connection</span></dt>
129
+ <dd>The PLC connection</dd>
130
+ <dt class="required">Address<span class="property-type">number | string | payload</span></dt>
131
+ <dd>PLC Memory Address</dd>
132
+ <dt class="required">Data<span class="property-type">Array&lt;number&gt; | number | string | payload </span></dt>
133
+ <dd>Data to be written to PLC starting at specified address.</dd>
134
+ <p><i>INFO: To open / close the MC Protocol connection, send boolean <code>true</code> in <code>msg.connect</code> , <code>msg.disconnect</code> or <code>msg.reinitialize</code>. Alternatively, send string <code>connect</code>, <code>disconnect</code> or <code>reinitialize</code> in <code>msg.topic</code> to the any mc read / mc write node.</i></p>
135
+ </dl>
136
+ <h3>Outputs</h3>
137
+ <dl class="message-properties">
138
+ <dt>payload <span class="property-type">boolean</span></dt>
139
+ <dd>Payload will be <code>true</code> if successful</dd>
140
+ <dt>mcWriteDetails <span class="property-type">object</span></dt>
141
+ <dd><code>msg.mcWriteDetails</code> will contain properties like <code>isGood</code>, <code>quality</code>, <code>TAG</code> etc. The user should inspect these to determine if the PLC write command was unsuccessful.</dd>
142
+ <dd>Use a debug node to inspect the object</dd>
143
+ </dl>
144
+ <h3>Details</h3>
145
+ <p>
146
+ If an error occurs the output of this node may still be triggered.
147
+ In this case, the payload maybe invalid but the <code>mcWriteDetails</code> will contain additional information about the problem.
148
+ </p>
149
+ <p>Address format [DS] DEV [DT] DN [.BIT] [,CNT] [:OPTS]...
150
+ <ol>
151
+ <li>[1] DS - {string} Digit specifier (e.g. K4) [optional]</li>
152
+ <li>[2] DEV - {string} Device (Y|X|D|F|W|B|R|etc)</li>
153
+ <li>[3] DT - {string} Data type (REAL|FLOAT|STR|WORD|DWORD|DINT|UINT) [optional]</li>
154
+ <li>[4] DN - {int} Device number</li>
155
+ <li>[5] BIT - {int} Bit number [optional]</li>
156
+ <li>[6] CNT - {int} Count of items [optional]</li>
157
+ <li>[7] OPTS - {JSON} Options for specifying network and station e.g. {N:2,S:3} would attempt to route the message to station 3 on network 2 [optional]</li>
158
+ </ol>
159
+ <i>Notes...<br>DS and DT should not be used together. <br>if CNT is omitted, then <code>1</code> is assumed. <br>DN may be DEC or HEX depending on the notation of the Device e.g. YA, X1E, WBA4, B3D </i>
160
+ </p>
161
+ <p>data must match the address style e.g...
162
+ <table>
163
+ <tr>
164
+ <td>Address Example</td>
165
+ <td>Expected Type</td>
166
+ <td>Notes</td>
167
+ </tr>
168
+ <tr>
169
+ <td>K4Y0</td>
170
+ <td>int</td>
171
+ <td>−32,768 to 32,767</td>
172
+ </tr>
173
+ <tr>
174
+ <td>DSTR0,10</td>
175
+ <td>string</td>
176
+ <td>Upto 10 chars long</td>
177
+ </tr>
178
+ <tr>
179
+ <td>DUINT0,10</td>
180
+ <td>UINT[10]</td>
181
+ <td>10 WD array containing values 0 to 65535</td>
182
+ </tr>
183
+ </table>
184
+ </p>
185
+ </script>