forked from Elius94/modbus-tcp-faker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
672 lines (626 loc) · 17.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import {
ConsoleManager,
OptionPopup,
InputPopup,
PageBuilder,
ConfirmPopup,
Button,
Progress,
} from "console-gui-tools";
//import { ConsoleManager, OptionPopup, InputPopup, PageBuilder, ConfirmPopup } from '../console-gui-tools/src/ConsoleGui.js'
const GUI = new ConsoleManager({
title: "MODBUS PLC SIMULATOR", // Title of the console
logPageSize: 20, // Number of lines to show in logs page
changeLayoutKey: "ctrl+l", // Change layout with ctrl+l to switch to the logs page
enableMouse: true,
layoutOptions: {
showTitle: true, // Show title in the top of the console
type: "double", // Type of layout: single, double, triple
direction: "horizontal", // Direction of the layout: horizontal, vertical
boxColor: "green", // Color of the console box
boxed: true, // Boxed console
},
});
import _ from "lodash";
import modbus from "jsmodbus";
import net from "net";
import fs from "fs";
const ipAddress = "192.168.0.39";
//const ipAddress = '127.0.0.1';
const port = 502;
const unitId = 1;
let connected = false;
let hrCounter = 0;
let run = false;
let runProgressive = false;
let runRead = false;
let prog = 4;
let lastErr = "";
let selectedChannel = "";
let typedVal = 0;
const glideStorage = {
from: 0,
to: 0,
step: 1,
timers: {},
};
let solidOnscreenValues = {
"SOLID LIFE COUNTER": 0,
"DGx HOUR CONTER LOW WORD (LLLL)": 0,
};
//Create a TCP Device
const options = {
host: ipAddress,
port: port,
};
const socket = new net.Socket();
const client = new modbus.client.TCP(socket, unitId);
// Read modbus.json file to store the modbus channels
const modbusChannels = fs.readFileSync("modbus.json");
const channels = _.orderBy(JSON.parse(modbusChannels), "name", "asc");
// remove duplicates from an array
const removeDuplicates = (array) => {
return array.filter((a, b) => array.indexOf(a) === b);
};
let reverseChannels = {};
let rawChannels = {};
channels.forEach((c, i) => {
if (!reverseChannels[c.address]) {
reverseChannels[c.address] = [];
}
rawChannels[c.address] = 0;
reverseChannels[c.address].push(c);
});
const channelsNames = removeDuplicates(channels.map((c, i) => c.name));
const startAddr = Number(Object.keys(reverseChannels)[0]);
const size =
Number(
Object.keys(reverseChannels)[Object.keys(reverseChannels).length - 1]
) -
startAddr +
1;
const echoChannelAddress = false;
function parseMessages(response) {
response.forEach((r, i) => {
try {
if (reverseChannels[startAddr + i]) {
if (reverseChannels[startAddr + i][0].type === "bit") {
reverseChannels[startAddr + i].forEach((c, j) => {
const v = getSingleBit(rawChannels[startAddr + i], c.offset);
if (rawChannels[startAddr + i] !== v) {
rawChannels[startAddr + i] = setSingleBit(
rawChannels[startAddr + i],
c.offset,
v
);
manageMessage(c.name, rawChannels[startAddr + i]);
}
});
} else {
if (rawChannels[startAddr + i] !== r) {
rawChannels[startAddr + i] = r;
manageMessage(
reverseChannels[startAddr + i][0].name,
rawChannels[startAddr + i]
);
}
}
}
} catch (e) {
GUI.error(e.message);
}
});
}
function manageMessage(channel, value) {
switch (channel) {
case "SOLID LIFE COUNTER":
solidOnscreenValues[channel] = value;
drawGui();
break;
case "DGx HOUR CONTER LOW WORD (LLLL)":
solidOnscreenValues[channel] = value;
drawGui();
break;
default:
GUI.log(`[${channel}]: ${value}`);
break;
}
}
function writeCommand(command, value) {
if (connected) {
GUI.log(`[${command}]: ${value}`);
const _obj = channels.find((e) => e.name === command);
const _addr = _obj.address;
if (_obj.type === "bit") {
let currentValue = rawChannels[_obj.address];
const _val = setSingleBit(currentValue, _obj.offset, value);
currentValue = _val;
client
.writeSingleRegister(_addr, _val, (err, response) => {
if (err) {
GUI.error(err.message);
}
})
.catch((err) => {
GUI.error(err.message);
});
} else {
rawChannels[_obj.address] = value;
client
.writeSingleRegister(_addr, value, (err, response) => {
if (err) {
GUI.error(err.message);
}
})
.catch((err) => {
GUI.error(err.message);
});
}
} else {
GUI.error("Not connected");
}
}
// Function to generate a random uint16 value
function randomUint16() {
return Math.floor(Math.random() * 3000);
}
function getIncrementalValue(value) {
return value + 1;
}
function setSingleBit(input, bitPosition, value) {
let _in = input;
if (value) {
return (_in |= 1 << bitPosition);
} else {
return (_in &= ~(1 << bitPosition));
}
}
function getSingleBit(input, bitPosition) {
return (input >> bitPosition) & 1;
}
function glideToValue(value, target, step) {
if (value < target) {
value += step;
if (value > target) {
value = target;
}
} else if (value > target) {
value -= step;
if (value < target) {
value = target;
}
}
return value;
}
function glide(chan, from, to, step) {
return setInterval(() => {
const _ch = channels.find((e) => e.name === chan);
if (connected && _ch.type !== "bit") {
rawChannels[_ch.address] = glideToValue(
rawChannels[_ch.address],
to,
step
);
client
.writeSingleRegister(
_ch.address,
rawChannels[_ch.address],
(err, response) => {
if (err) {
GUI.error(err.message);
}
}
)
.catch((err) => {
GUI.error(err.message);
});
}
}, 100);
}
socket.on("connect", function () {
connected = true;
GUI.info("Connected to modbus server");
//drawGui()
});
socket.on("end", function () {
connected = false;
GUI.error("Disconnected from modbus server");
//drawGui()
});
// Write all the channels to the modbus server every 250ms
setInterval(function () {
if (connected && run) {
// Split channels into two arrays
const channels1 = channels.slice(0, channels.length / 2);
const channels2 = channels.slice(channels.length / 2, channels.length);
const values1 = channels1.map((channel) => {
if (echoChannelAddress) {
return channel.address;
} else {
if (channel.type == "decimal") {
return randomUint16();
} else if (channel.type == "bit") {
return randomUint16();
} else if (channel.type == "integer") {
return randomUint16();
}
}
});
const values2 = channels2.map((channel) => {
if (echoChannelAddress) {
return channel.address;
} else {
if (channel.type == "decimal") {
return randomUint16();
} else if (channel.type == "bit") {
return randomUint16();
} else if (channel.type == "integer") {
return randomUint16();
}
}
});
client
.writeMultipleRegisters(channels1[0].address, values1)
.catch((err) => {
GUI.error(JSON.stringify(err));
})
.then((v) => {
hrCounter++;
});
client
.writeMultipleRegisters(channels2[0].address, values2)
.catch((err) => {
GUI.error(JSON.stringify(err));
})
.then((v) => {
hrCounter++;
drawGui();
});
}
}, 250);
// Reading the modbus channels every 500ms
setInterval(function () {
if (connected && runRead) {
client
.readHoldingRegisters(startAddr, size)
.then((r) => {
if (r.response.body.values) parseMessages(r.response.body.values);
})
.catch((err) => {
GUI.error(JSON.stringify(err));
});
}
}, 500);
// Progressive from PLC
setInterval(function () {
if (connected && runProgressive) {
client
.writeSingleRegister(1042, prog)
.catch((err) => {
GUI.error(JSON.stringify(err));
})
.then((v) => {
hrCounter++;
drawGui();
});
}
}, 1000);
socket.on("error", (err) => {
GUI.error(JSON.stringify(err));
});
socket.connect(options);
/**
* @description Updates the console screen
*
*/
const updateConsole = async () => {
const p = new PageBuilder();
p.addRow({
text: `Modbus TCP server simulator app! Welcome...`,
color: "yellow",
});
if (connected)
p.addRow({
text: `Connected to TCP Server: ${ipAddress}:${port} - id: ${unitId}`,
color: "green",
});
p.addRow(
{ text: `Holding Register Setted: `, color: "magenta" },
{ text: `${hrCounter}`, color: "white" }
);
// Print if simulator is running or not
if (!run) {
p.addRow(
{ text: `Simulator is not running! `, color: "red" },
{ text: `press 'space' to start`, color: "white" }
);
} else {
p.addRow(
{ text: `Simulator is running! `, color: "green" },
{ text: `press 'space' to stop`, color: "white" }
);
}
// Print if progressive counter is running or not
if (!runProgressive) {
p.addRow(
{ text: `Progressive counter [hr1044] is not running! `, color: "red" },
{ text: `press 'p' to start it`, color: "white" }
);
} else {
p.addRow(
{ text: `Progressive counter [hr1044] is running! `, color: "green" },
{ text: `press 'p' to stop it`, color: "white" }
);
}
// Print if progressive counter is running or not
if (!runRead) {
p.addRow(
{ text: `HR Reading and parsing is off! `, color: "red" },
{ text: `press 'r' to start it`, color: "white" }
);
} else {
p.addRow(
{ text: `HR Reading and parsing is on! `, color: "green" },
{ text: `press 'r' to stop it`, color: "white" }
);
}
// Print solid Messages to show in the console (solidOnscreenValues)
p.addSpacer();
if (Object.keys(solidOnscreenValues).length > 0) {
p.addRow({ text: `Solid Data: `, color: "magenta" });
Object.keys(solidOnscreenValues).forEach((value) => {
p.addRow({
text: `${value}: ${solidOnscreenValues[value]}`,
color: "white",
});
});
}
// Spacer
p.addSpacer(2);
if (lastErr.length > 0) {
p.addRow({ text: lastErr, color: "red" });
}
p.addSpacer(2);
// Print the commands
p.addRow({ text: `Commands: `, color: "white", bg: "bgBlack" });
p.addRow(
{ text: ` 'space'`, color: "white", bold: true },
{ text: ` - start/stop the simulator`, color: "gray", italic: true }
);
p.addRow(
{ text: ` 'r'`, color: "white", bold: true },
{
text: ` - start/stop the HR reading and parsing`,
color: "gray",
italic: true,
}
);
p.addRow(
{ text: ` 'p'`, color: "white", bold: true },
{
text: ` - start/stop progressive counter (PLC isAlive)`,
color: "gray",
italic: true,
}
);
p.addRow(
{ text: ` 's'`, color: "white", bold: true },
{ text: ` - send command value`, color: "gray", italic: true }
);
p.addRow(
{ text: ` 'g'`, color: "white", bold: true },
{ text: ` - make a glide on channel`, color: "gray", italic: true }
);
p.addRow(
{ text: ` 'h'`, color: "white", bold: true },
{ text: ` - clear all glide actions`, color: "gray", italic: true }
);
p.addRow(
{ text: ` 'c'`, color: "white", bold: true },
{ text: ` - reconnect to server`, color: "gray", italic: true }
);
p.addRow(
{ text: ` 'q'`, color: "white", bold: true },
{ text: ` - quit the app`, color: "gray", italic: true }
);
p.addSpacer(2);
GUI.setPage(p, 0);
};
GUI.on("exit", () => {
closeApp();
});
GUI.on("keypressed", (key) => {
switch (key.name) {
case "c":
{
if (connected) {
socket.destroy();
connected = false;
}
socket.connect(options);
}
break;
case "space":
run = !run;
drawGui();
break;
case "p":
runProgressive = !runProgressive;
drawGui();
break;
case "r":
runRead = !runRead;
drawGui();
break;
case "s":
new OptionPopup(
"popupSelectCommand",
"Select Modbus Channel",
channelsNames,
selectedChannel
)
.show()
.on("confirm", (_selectedChannel) => {
selectedChannel = _selectedChannel;
GUI.warn(`Selected: ${selectedChannel}`);
const _chan = channels.find((c) => c.name == selectedChannel);
if ((_chan && _chan.type === "decimal") || _chan.type === "integer") {
typedVal = rawChannels[_chan.address];
} else if (_chan && _chan.type == "bit") {
typedVal = getSingleBit(rawChannels[_chan.address], _chan.offset);
}
new InputPopup(
"popupTypeVal",
`Type value for "${selectedChannel}"`,
typedVal,
true
)
.show()
.on("confirm", (_val) => {
typedVal = _val;
GUI.warn(`NEW VALUE: ${typedVal}`);
writeCommand(selectedChannel, typedVal);
drawGui();
});
});
break;
case "g":
{
new OptionPopup(
"popupSelectCommandGlide",
"[Glide] Select Modbus Channel",
channelsNames,
selectedChannel
)
.show()
.on("confirm", (_selectedChannel) => {
selectedChannel = _selectedChannel;
GUI.warn(`Selected: ${selectedChannel}`);
const _chan = channels.find((c) => c.name == selectedChannel);
if (
(_chan && _chan.type === "decimal") ||
_chan.type === "integer"
) {
typedVal = rawChannels[_chan.address];
} else if (_chan && _chan.type == "bit") {
typedVal = getSingleBit(rawChannels[_chan.address], _chan.offset);
}
new InputPopup(
"popupTypeValFrom",
`Type start value for "${selectedChannel}"`,
glideStorage.from,
true
)
.show()
.on("confirm", (_val) => {
glideStorage.from = _val;
GUI.warn(`FROM: ${glideStorage.from}`);
new InputPopup(
"popupTypeValTo",
`Type target value for "${selectedChannel}"`,
glideStorage.to,
true
)
.show()
.on("confirm", (_val) => {
glideStorage.to = _val;
GUI.warn(`TO: ${glideStorage.to}`);
glideStorage.timers[selectedChannel] = glide(
selectedChannel,
glideStorage.from,
glideStorage.to,
glideStorage.step
);
drawGui();
});
});
});
}
break;
case "h":
Object.keys(glideStorage.timers).forEach((timer) => {
clearInterval(glideStorage.timers[timer]);
});
break;
case "q":
new ConfirmPopup("popupQuit", "Are you sure you want to quit?")
.show()
.on("confirm", () => closeApp());
break;
default:
break;
}
});
const addButtons = () => {
const btnSimStartProps = {
text: "Simulate Engine Start",
style: {
color: "magentaBright",
borderColor: "magentaBright",
bold: true,
},
}
const btnSimStart = new Button("btnSimStart", btnSimStartProps.text, btnSimStartProps.text.length + 4, 3, 3, 11, btnSimStartProps.style)
btnSimStart.on("click", () => {
console.warn("Engine Started");
if (Object.keys(glideStorage.timers).includes("ENGINE SPEED")) {
clearInterval(glideStorage.timers["ENGINE SPEED"]);
delete glideStorage.timers["ENGINE SPEED"];
}
glideStorage.timers["ENGINE SPEED"] = glide(
"ENGINE SPEED",
100,
1800,
10
);
})
const btnSimStopProps = {
text: "Simulate Engine Stop",
style: {
color: "redBright",
borderColor: "redBright",
bold: true,
},
}
const btnSimStop = new Button("btnSimStop", btnSimStopProps.text, btnSimStopProps.text.length + 4, 3, 4 + btnSimStart.absoluteValues.width, 11, btnSimStopProps.style)
btnSimStop.on("click", () => {
console.error("Engine Stopped");
if (Object.keys(glideStorage.timers).includes("ENGINE SPEED")) {
clearInterval(glideStorage.timers["ENGINE SPEED"]);
delete glideStorage.timers["ENGINE SPEED"];
}
glideStorage.timers["ENGINE SPEED"] = glide(
"ENGINE SPEED",
1800,
0,
100
);
})
const p2Style = {
background: "bgBlack",
borderColor: "yellow",
color: "magenta",
boxed: true,
showTitle: true,
showValue: true,
showPercentage: true,
showMinMax: true,
}
const p2 = new Progress("prog3", 25, 2, 3, 31, p2Style, "precision", "horizontal", true)
p2.setText("Engine Speed")
p2.setValue(0)
p2.setMin(0)
p2.setMax(2000)
p2.on("valueChanged", (value) => {
writeCommand("ENGINE SPEED", Math.round(value));
})
}
const drawGui = () => {
updateConsole();
};
const closeApp = () => {
console.clear();
process.exit();
};
drawGui();
addButtons();