@ali-pay/node-red-contrib-s7 3.2.0

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/red/s7.js ADDED
@@ -0,0 +1,712 @@
1
+ //@ts-check
2
+ /*
3
+ Copyright: (c) 2016-2020, St-One Ltda., Guilherme Francescon Cittolin <guilherme@st-one.io>
4
+ GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
5
+ */
6
+
7
+ function nrInputShim(node, fn) {
8
+ node.on('input', function (msg, send, done) {
9
+ send = send || node.send;
10
+ done = done || (err => err && node.error(err, msg));
11
+ fn(msg, send, done);
12
+ });
13
+ }
14
+
15
+ /**
16
+ * Compares values for equality, includes special handling for arrays. Fixes #33
17
+ * @param {number|string|Array|Date} a
18
+ * @param {number|string|Array|Date} b
19
+ */
20
+ function equals(a, b) {
21
+ if (a === b) return true;
22
+ if (a == null || b == null) return false;
23
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
24
+ if (Array.isArray(a) && Array.isArray(b)) {
25
+ if (a.length != b.length) return false;
26
+
27
+ for (var i = 0; i < a.length; ++i) {
28
+ if (a[i] !== b[i]) return false;
29
+ }
30
+ return true;
31
+ }
32
+ return false;
33
+ }
34
+
35
+ var MIN_CYCLE_TIME = 50;
36
+
37
+ var tools = require('../src/tools.js');
38
+
39
+ module.exports = function (RED) {
40
+ "use strict";
41
+
42
+ var nodes7 = require('@st-one-io/nodes7');
43
+ var EventEmitter = require('events').EventEmitter;
44
+
45
+ // ---------- Discovery Endpoints ----------
46
+
47
+ RED.httpAdmin.get('/__node-red-contrib-s7/discover/available/iso-on-tcp', RED.auth.needsPermission('s7.discover'), function (req, res) {
48
+ tools.isPnToolsAvailable().then(function (available) {
49
+ res.json(available).end();
50
+ }).catch(() => {
51
+ res.status(500).end();
52
+ });
53
+ });
54
+
55
+ RED.httpAdmin.get('/__node-red-contrib-s7/discover/iso-on-tcp', RED.auth.needsPermission('s7.discover'), function (req, res) {
56
+ tools.listDevicesPN().then(function (devices) {
57
+ res.json(devices).end();
58
+ }).catch(() => {
59
+ res.status(500).end();
60
+ });
61
+ });
62
+
63
+ RED.httpAdmin.get('/__node-red-contrib-s7/flashled/iso-on-tcp/:mac', RED.auth.needsPermission('s7.discover'), function (req, res) {
64
+ let mac_addr = (req.params.mac || '').replace(/-/g, ':');
65
+ if (!/^([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2}$/.test(mac_addr)) {
66
+ res.status(400).end();
67
+ return;
68
+ }
69
+
70
+ tools.flashLedPN(mac_addr).then(function () {
71
+ res.status(204).end();
72
+ }).catch(() => {
73
+ res.status(500).end();
74
+ });
75
+ });
76
+
77
+ // ---------- S7 Endpoint ----------
78
+
79
+ function createTranslationTable(vars) {
80
+ var res = {};
81
+
82
+ vars.forEach(function (elm) {
83
+ if (!elm.name || !elm.addr) {
84
+ //skip incomplete entries
85
+ return;
86
+ }
87
+ res[elm.name] = elm.addr;
88
+ });
89
+
90
+ return res;
91
+ }
92
+
93
+ function generateStatus(status, val) {
94
+ var obj;
95
+
96
+ if (typeof val != 'string' && typeof val != 'number' && typeof val != 'boolean') {
97
+ val = RED._("s7.endpoint.status.online");
98
+ }
99
+
100
+ switch (status) {
101
+ case 'online':
102
+ obj = {
103
+ fill: 'green',
104
+ shape: 'dot',
105
+ text: val.toString()
106
+ };
107
+ break;
108
+ case 'badvalues':
109
+ obj = {
110
+ fill: 'yellow',
111
+ shape: 'dot',
112
+ text: RED._("s7.endpoint.status.badvalues")
113
+ };
114
+ break;
115
+ case 'offline':
116
+ obj = {
117
+ fill: 'red',
118
+ shape: 'dot',
119
+ text: RED._("s7.endpoint.status.offline")
120
+ };
121
+ break;
122
+ case 'connecting':
123
+ obj = {
124
+ fill: 'yellow',
125
+ shape: 'dot',
126
+ text: RED._("s7.endpoint.status.connecting")
127
+ };
128
+ break;
129
+ default:
130
+ obj = {
131
+ fill: 'grey',
132
+ shape: 'dot',
133
+ text: RED._("s7.endpoint.status.unknown")
134
+ };
135
+ }
136
+ return obj;
137
+ }
138
+
139
+ function validateTSAP(num) {
140
+ num = num.toString();
141
+ if (num.length != 2) return false;
142
+ if (!(/^[0-9a-fA-F]+$/.test(num))) return false;
143
+ var i = parseInt(num, 16);
144
+ if (isNaN(i) || i < 0 || i > 0xff) return false;
145
+ return true;
146
+ }
147
+
148
+ function S7Endpoint(config) {
149
+ EventEmitter.call(this);
150
+ var node = this;
151
+ var oldValues = {};
152
+ var status;
153
+ var readInProgress = false;
154
+ var readDeferred = 0;
155
+ var connected = false;
156
+ var currentCycleTime = config.cycletime;
157
+ var transport = config.transport || 'iso-on-tcp';
158
+
159
+ RED.nodes.createNode(this, config);
160
+
161
+ //avoids warnings when we have a lot of S7In nodes
162
+ this.setMaxListeners(0);
163
+
164
+ node.endpoint = null;
165
+ let connOpts;
166
+ let itemGroup;
167
+ let s7ConnOpts = { timeout: parseInt(config.timeout) }
168
+
169
+ if (transport === 'mpi-s7') {
170
+
171
+ node.adapter = RED.nodes.getNode(config.adapter);
172
+ if (!node.adapter) {
173
+ return node.error(RED._("s7.error.missingconfig"));
174
+ }
175
+
176
+ s7ConnOpts.maxJobs = 1;
177
+
178
+ connOpts = {
179
+ customTransport: async () => node.adapter.getStream(config.busaddr),
180
+ s7ConnOpts
181
+ }
182
+
183
+ } else if (transport === 'iso-on-tcp') {
184
+
185
+ switch (config.connmode) {
186
+ case "rack-slot":
187
+ connOpts = {
188
+ host: config.address,
189
+ port: Number(config.port),
190
+ rack: Number(config.rack),
191
+ slot: Number(config.slot),
192
+ s7ConnOpts: s7ConnOpts
193
+ }
194
+ break;
195
+ case "tsap":
196
+ if (!validateTSAP(config.localtsaphi) ||
197
+ !validateTSAP(config.localtsaplo) ||
198
+ !validateTSAP(config.remotetsaphi) ||
199
+ !validateTSAP(config.remotetsaplo)) {
200
+ node.error(RED._("s7.error.invalidtsap", config));
201
+ return;
202
+ }
203
+
204
+ let localTSAP = parseInt(config.localtsaphi, 16) << 8;
205
+ localTSAP += parseInt(config.localtsaplo, 16);
206
+ let remoteTSAP = parseInt(config.remotetsaphi, 16) << 8;
207
+ remoteTSAP += parseInt(config.remotetsaplo, 16);
208
+
209
+ connOpts = {
210
+ host: config.address,
211
+ port: config.port,
212
+ srcTSAP: localTSAP,
213
+ dstTSAP: remoteTSAP,
214
+ s7ConnOpts: s7ConnOpts
215
+ }
216
+ break;
217
+ default:
218
+ node.error(RED._("s7.error.invalidconntype", config));
219
+ return;
220
+ }
221
+ } else {
222
+ node.error(RED._("s7.error.invalidconntype", config));
223
+ return;
224
+ }
225
+
226
+ node._vars = createTranslationTable(config.vartable);
227
+
228
+ node.getStatus = function getStatus() {
229
+ return status;
230
+ };
231
+
232
+ node.writeVar = function writeVar(obj) {
233
+ itemGroup.writeItems(obj.name, obj.val)
234
+ .then(() => obj.done())
235
+ .catch(e => obj.done(e))
236
+ };
237
+
238
+ /**
239
+ * updates the current cycle time on the fly. A value of 0
240
+ * disables the cyclic reading of variables, and for positive values
241
+ * a minimum of 50 ms is enforced
242
+ *
243
+ * @param {number} interval the cycle time interval, in ms
244
+ * @returns {string|undefined} an string with the error if any, or undefined
245
+ */
246
+ node.updateCycleTime = function updateCycleTime(interval) {
247
+ let time = parseInt(interval);
248
+
249
+ if (isNaN(time) || time < 0) {
250
+ return RED._("s7.error.invalidtimeinterval", { interval: interval });
251
+ }
252
+
253
+ clearInterval(node._td);
254
+
255
+ // don't set a new timer if value is zero
256
+ if (!time) return;
257
+
258
+ if (time < MIN_CYCLE_TIME) {
259
+ node.warn(RED._("s7.info.cycletimetooshort", { min: MIN_CYCLE_TIME }), {});
260
+ time = MIN_CYCLE_TIME;
261
+ }
262
+
263
+ currentCycleTime = time;
264
+ node._td = setInterval(doCycle, time);
265
+ }
266
+
267
+ function manageStatus(newStatus) {
268
+ if (status == newStatus) return;
269
+
270
+ status = newStatus;
271
+ node.emit('__STATUS__', {
272
+ status: status
273
+ });
274
+ }
275
+
276
+ function cycleCallback(values) {
277
+ readInProgress = false;
278
+
279
+ if (readDeferred && connected) {
280
+ doCycle();
281
+ readDeferred = 0;
282
+ }
283
+
284
+ manageStatus('online');
285
+
286
+ var changed = false;
287
+ node.emit('__ALL__', values);
288
+ Object.keys(values).forEach(function (key) {
289
+ if (!equals(oldValues[key], values[key])) {
290
+ changed = true;
291
+ node.emit(key, values[key]);
292
+ node.emit('__CHANGED__', {
293
+ key: key,
294
+ value: values[key]
295
+ });
296
+ oldValues[key] = values[key];
297
+ }
298
+ });
299
+ if (changed) node.emit('__ALL_CHANGED__', values);
300
+ }
301
+
302
+ function doCycle() {
303
+ if (!readInProgress && connected) {
304
+ itemGroup.readAllItems().then(cycleCallback).catch(e => {
305
+ node.error(e, {});
306
+ readInProgress = false;
307
+ });
308
+ readInProgress = true;
309
+ } else {
310
+ readDeferred++;
311
+ }
312
+ }
313
+ node.doCycle = doCycle;
314
+
315
+ function onConnect() {
316
+ readInProgress = false;
317
+ readDeferred = 0;
318
+ connected = true;
319
+
320
+ manageStatus('online');
321
+
322
+ node.updateCycleTime(currentCycleTime);
323
+ }
324
+
325
+ function onDisconnect() {
326
+ manageStatus('offline');
327
+ connected = false;
328
+ }
329
+
330
+ node.on('close', done => {
331
+ manageStatus('offline');
332
+ if (!node.endpoint) done();
333
+
334
+ node.endpoint.disconnect().then(done).catch(e => {
335
+ node.error(e);
336
+ });
337
+ });
338
+
339
+ manageStatus('offline');
340
+
341
+ node.endpoint = new nodes7.S7Endpoint(connOpts);
342
+ node.endpoint.on('connecting', () => manageStatus('connecting'));
343
+ node.endpoint.on('connect', onConnect);
344
+ node.endpoint.on('disconnect', onDisconnect);
345
+ node.endpoint.on('error', (e => {
346
+ manageStatus('offline');
347
+ node.error(e && e.toString(), {});
348
+ }));
349
+
350
+ itemGroup = new nodes7.S7ItemGroup(node.endpoint);
351
+ itemGroup.setTranslationCB(k => node._vars[k]);
352
+ node.itemGroup = itemGroup;
353
+
354
+ let varKeys = Object.keys(node._vars)
355
+ if (!varKeys || !varKeys.length) {
356
+ node.warn(RED._("s7.info.novars"), {});
357
+ return;
358
+ } else {
359
+ itemGroup.addItems(varKeys);
360
+ }
361
+
362
+ }
363
+ RED.nodes.registerType("s7 endpoint", S7Endpoint);
364
+
365
+ // ---------- S7 In ----------
366
+
367
+ function S7In(config) {
368
+ var node = this;
369
+ var statusVal;
370
+ RED.nodes.createNode(this, config);
371
+
372
+ node.endpoint = RED.nodes.getNode(config.endpoint);
373
+ if (!node.endpoint) {
374
+ return node.error(RED._("s7.error.missingconfig"));
375
+ }
376
+
377
+ function sendMsg(data, key, status) {
378
+ if (key === undefined) key = '';
379
+ if (data instanceof Date) data = data.getTime();
380
+ var msg = [
381
+ {
382
+ payload: data,
383
+ topic: key
384
+ },
385
+ {
386
+ payload: {
387
+ name: node.endpoint.name,
388
+ ip: node.endpoint.endpoint._connOptsTcp.host,
389
+ status: node.endpoint.getStatus(),
390
+ },
391
+ topic: ''
392
+ },
393
+ ];
394
+ statusVal = status !== undefined ? status : data;
395
+ node.send(msg);
396
+ node.status(generateStatus(node.endpoint.getStatus(), statusVal));
397
+ }
398
+
399
+ function onChanged(variable) {
400
+ sendMsg(variable.value, variable.key, null);
401
+ }
402
+
403
+ function onDataSplit(data) {
404
+ Object.keys(data).forEach(function (key) {
405
+ sendMsg(data[key], key, null);
406
+ });
407
+ }
408
+
409
+ function onData(data) {
410
+ sendMsg(data, config.mode == 'single' ? config.variable : '');
411
+ }
412
+
413
+ function onDataSelect(data) {
414
+ onData(data[config.variable]);
415
+ }
416
+
417
+ function onEndpointStatus(s) {
418
+ node.status(generateStatus(s.status, statusVal));
419
+
420
+ // 只触发 ['online', 'offline'] 的事件
421
+ if (!['online', 'offline'].includes(node.endpoint.getStatus())) return;
422
+ var msg = [
423
+ {
424
+ payload: {},
425
+ topic: ''
426
+ },
427
+ {
428
+ payload: {
429
+ name: node.endpoint.name,
430
+ ip: node.endpoint.endpoint._connOptsTcp.host,
431
+ status: node.endpoint.getStatus(),
432
+ },
433
+ topic: ''
434
+ },
435
+ ];
436
+ node.send(msg);
437
+ }
438
+
439
+ node.status(generateStatus(node.endpoint.getStatus(), statusVal));
440
+ node.endpoint.on('__STATUS__', onEndpointStatus);
441
+
442
+ if (config.diff) {
443
+ switch (config.mode) {
444
+ case 'all-split':
445
+ node.endpoint.on('__CHANGED__', onChanged);
446
+ break;
447
+ case 'single':
448
+ node.endpoint.on(config.variable, onData);
449
+ break;
450
+ case 'all':
451
+ default:
452
+ node.endpoint.on('__ALL_CHANGED__', onData);
453
+ }
454
+ } else {
455
+ switch (config.mode) {
456
+ case 'all-split':
457
+ node.endpoint.on('__ALL__', onDataSplit);
458
+ break;
459
+ case 'single':
460
+ node.endpoint.on('__ALL__', onDataSelect);
461
+ break;
462
+ case 'all':
463
+ default:
464
+ node.endpoint.on('__ALL__', onData);
465
+ }
466
+ }
467
+
468
+ node.on('close', function (done) {
469
+ node.endpoint.removeListener('__ALL__', onDataSelect);
470
+ node.endpoint.removeListener('__ALL__', onDataSplit);
471
+ node.endpoint.removeListener('__ALL__', onData);
472
+ node.endpoint.removeListener('__ALL_CHANGED__', onData);
473
+ node.endpoint.removeListener('__CHANGED__', onChanged);
474
+ node.endpoint.removeListener('__STATUS__', onEndpointStatus);
475
+ node.endpoint.removeListener(config.variable, onData);
476
+ done();
477
+ });
478
+ }
479
+ RED.nodes.registerType("s7 in", S7In);
480
+
481
+ // ---------- S7 Out ----------
482
+
483
+ function S7Out(config) {
484
+ var node = this;
485
+ var statusVal;
486
+ RED.nodes.createNode(this, config);
487
+
488
+ node.endpoint = RED.nodes.getNode(config.endpoint);
489
+ if (!node.endpoint) {
490
+ return node.error(RED._("s7.error.missingconfig"));
491
+ }
492
+
493
+ function onEndpointStatus(s) {
494
+ node.status(generateStatus(s.status, statusVal));
495
+ }
496
+
497
+ function onNewMsg(msg, send, done) {
498
+ var writeObj = {
499
+ name: config.variable || msg.variable,
500
+ val: msg.payload,
501
+ done: (error) => {
502
+
503
+ const variable = config.variable || msg.variable
504
+ const payload = msg.payload
505
+
506
+ const variables = Array.isArray(variable) ? variable : [variable]
507
+ const payloads = Array.isArray(payload) ? payload : [payload]
508
+
509
+ const values = {}
510
+ variables.forEach((key, index) => {
511
+ values[key] = payloads[index]
512
+ })
513
+
514
+ // 调用 s7-out 后的返回消息
515
+ const message = {
516
+ payload: {
517
+ error: error, // 错误
518
+ variable: variable, // 写入的键
519
+ payload: payload, // 写入的值
520
+ values: values, // 写入的键值对
521
+ newValues: {}, // plc的最新键值对
522
+ bingo: false, // plc的最新值跟写入值是否一致
523
+ wrongValues: {}, // 跟写入值不一致的键值对
524
+ }
525
+ }
526
+
527
+ // 处理错误 done(r) 不生效;需要使用 node.error(e)
528
+ // https://nodered.org/docs/creating-nodes/node-js#handling-errors
529
+ if (error) {
530
+ node.error(error)
531
+ node.send(message)
532
+ return
533
+ }
534
+
535
+ // 读取最新的值
536
+ node.endpoint.itemGroup.readAllItems()
537
+ .then(newValues => {
538
+ // 过滤变量
539
+ for (const key in newValues) {
540
+ if (variables.includes(key)) {
541
+ message.payload.newValues[key] = newValues[key]
542
+
543
+ // 重要!需要跟PLC约定:读取完数据1秒后再清空,避免本程序做二次读取校验时读取不到当时写入的数据
544
+ if (newValues[key] !== values[key]) message.payload.wrongValues[key] = newValues[key]
545
+ }
546
+ }
547
+
548
+ // 数据是否完全写入成功
549
+ const v1 = Object.keys(message.payload.values).length
550
+ const v2 = Object.keys(message.payload.newValues).length
551
+ const v3 = Object.keys(message.payload.wrongValues).length
552
+ message.payload.bingo = v1 === v2 && v3 === 0
553
+ })
554
+ .catch(e => {
555
+ node.error(e)
556
+ })
557
+ .finally(() => {
558
+ node.send(message)
559
+ })
560
+ }
561
+ };
562
+
563
+ // Test for the case we're writing multiple vars
564
+ if (Array.isArray(writeObj.name)) {
565
+
566
+ if (!Array.isArray(writeObj.val) || writeObj.val.length !== writeObj.name.length) {
567
+ node.error(RED._("s7.error.valmismatch"));
568
+ node.status(generateStatus('badvalues', statusVal));
569
+ return;
570
+ }
571
+
572
+ for (const elm of writeObj.name) {
573
+ if (!node.endpoint._vars[elm]) {
574
+ node.error(RED._("s7.error.varunknown", { var: elm }));
575
+ node.status(generateStatus('badvalues', statusVal));
576
+ return;
577
+ }
578
+ }
579
+
580
+ } else if (!node.endpoint._vars[writeObj.name]) {
581
+ node.error(RED._("s7.error.varunknown", { var: writeObj.name }));
582
+ node.status(generateStatus('badvalues', statusVal));
583
+ return;
584
+ }
585
+
586
+ statusVal = writeObj.val;
587
+ node.endpoint.writeVar(writeObj);
588
+ node.status(generateStatus(node.endpoint.getStatus(), statusVal));
589
+ }
590
+
591
+ nrInputShim(node, onNewMsg);
592
+
593
+ node.status(generateStatus(node.endpoint.getStatus(), statusVal));
594
+ node.endpoint.on('__STATUS__', onEndpointStatus);
595
+
596
+ node.on('close', function (done) {
597
+ node.endpoint.removeListener('__STATUS__', onEndpointStatus);
598
+ done();
599
+ });
600
+
601
+ }
602
+ RED.nodes.registerType("s7 out", S7Out);
603
+
604
+
605
+ // ---------- S7 Control ----------
606
+
607
+ function S7Control(config) {
608
+ var node = this;
609
+ var statusVal;
610
+ RED.nodes.createNode(this, config);
611
+
612
+ node.endpoint = RED.nodes.getNode(config.endpoint);
613
+ if (!node.endpoint) {
614
+ return node.error(RED._("s7.error.missingconfig"));
615
+ }
616
+
617
+ function onEndpointStatus(s) {
618
+ node.status(generateStatus(s.status, statusVal));
619
+ }
620
+
621
+ function onMessage(msg, send, done) {
622
+ var res;
623
+ let func = config.function || msg.function;
624
+ switch (func) {
625
+ case 'cycletime':
626
+ res = node.endpoint.updateCycleTime(msg.payload);
627
+ if (res) {
628
+ done(res);
629
+ } else {
630
+ send(msg);
631
+ done();
632
+ }
633
+ break;
634
+ case 'trigger':
635
+ node.endpoint.doCycle();
636
+ send(msg);
637
+ done();
638
+ break;
639
+
640
+ case 'ssl':
641
+ node.endpoint.endpoint
642
+ .getSSL(Number(msg && msg.payload && msg.payload.id || 0), Number(msg && msg.payload && msg.payload.index || 0)).then(res => {
643
+ msg.payload = res;
644
+ send(msg);
645
+ done();
646
+ }).catch(e => {
647
+ done(e);
648
+ })
649
+ break;
650
+
651
+ case 'list-blocks':
652
+ node.endpoint.endpoint
653
+ .listAllBlocks().then(res => {
654
+ msg.payload = res;
655
+ send(msg);
656
+ done();
657
+ }).catch(e => {
658
+ done(e);
659
+ })
660
+ break;
661
+
662
+ case 'upload-block':
663
+ node.endpoint.endpoint
664
+ .uploadBlock(msg && msg.payload && msg.payload.type, Number(msg && msg.payload && msg.payload.number)).then(res => {
665
+ msg.payload = res;
666
+ send(msg);
667
+ done();
668
+ }).catch(e => {
669
+ done(e);
670
+ })
671
+ break;
672
+
673
+ case 'upload-all-blocks':
674
+ node.endpoint.endpoint
675
+ .uploadAllBlocks().then(res => {
676
+ msg.payload = res;
677
+ send(msg);
678
+ done();
679
+ }).catch(e => {
680
+ done(e);
681
+ })
682
+ break;
683
+
684
+ case 'all-block-info':
685
+ node.endpoint.endpoint
686
+ .getAllBlockInfo().then(res => {
687
+ msg.payload = res;
688
+ send(msg);
689
+ done();
690
+ }).catch(e => {
691
+ done(e);
692
+ })
693
+ break;
694
+
695
+ default:
696
+ node.error(RED._("s7.error.invalidcontrolfunction", { function: config.function }), msg);
697
+ }
698
+ }
699
+
700
+ node.status(generateStatus(node.endpoint.getStatus(), statusVal));
701
+
702
+ nrInputShim(node, onMessage);
703
+ node.endpoint.on('__STATUS__', onEndpointStatus);
704
+
705
+ node.on('close', function (done) {
706
+ node.endpoint.removeListener('__STATUS__', onEndpointStatus);
707
+ done();
708
+ });
709
+
710
+ }
711
+ RED.nodes.registerType("s7 control", S7Control);
712
+ };