-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSPS.js
More file actions
601 lines (559 loc) · 17.4 KB
/
Copy pathWebSPS.js
File metadata and controls
601 lines (559 loc) · 17.4 KB
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
/**
* WebSPS.js - A JavaScript-based implementation of a Programmable Logic Controller
*
* @author Oliver Weinhold
* @copyright Copyright (c) 2026 Oliver Weinhold
* @license GPLv3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* For more information, please visit: https://github.com/OliverWeinhold/WebSPS
*/
// Only for development purposes
//
/** @DEBUG {DEBUG} Only for development purposes. Enables logging to console. Use "DEBUG && console.log()"*/
const DEBUG = false;
export class SPS {
/** @SPSCode {string} Converted JS Code to be executed by the SPS */
#SPSCode;
/** @state {number} The current state of the SPS. 0 = Stopped, 1 = Running 2 = Paused */
#state = 0;
/** @dataReady {boolean} True if output registers were updated after input change */
#dataReady = false;
/** @runtimeTimer {timer} Stores Timeout Timer */
#runtimeTimer;
//Input, Flag and Output Registers
/** @E {array} Internal input Registers */
_E;
/** @A {array} Internal output Registers */
_A;
/** @M {array} Internal flag Registers */
_M;
/** @RuntimeCounter {number} Counter for Runtime */
#RuntimeCounter = 0;
/** @SPSCycleTime {number} Wait time in ms between each SPS cycle */
#SPSCycleTime = 10;
/**
* Constructs a new instance of the SPS class.
*
* @param {number} [Inputs=64] - The number of input registers. Defaults to 64.
* @param {number} [Outputs=64] - The number of output registers. Defaults to 64.
* @param {number} [Flags=64] - The number of flag registers. Defaults to 64.
*/
constructor(Inputs = 64, Outputs = 64, Flags = 64) {
if (Inputs > 256) Inputs = 256;
else if (Inputs < 0) Inputs = 64;
if (Outputs > 256) Outputs = 256;
else if (Outputs < 0) Outputs = 64;
if (Flags > 256) Flags = 256;
else if (Flags < 0) Flags = 64;
this._E = new Array(Inputs).fill(0);
this._A = new Array(Outputs).fill(0);
this._M = new Array(Flags).fill(0);
}
//Runtime is executed every SPSCycleTime ms
#SPSRuntime = () => {
this.#RuntimeCounter += 1;
try {
// Execute the SPS logic
const run = new Function(this.#SPSCode);
run.call(this); // Execute in the context of the SPS instance
this.#dataReady = true;
} catch (e) {
console.error("SPS Runtime Error:", e);
this.#state = 0; // Stop on error
this.#changeSPSState(0);
if (this.onErrorCallback) this.onErrorCallback(e.message);
}
};
//Transition between States
#changeSPSState(newState) {
switch (newState) {
case 0: {
clearInterval(this.#runtimeTimer);
this.#RuntimeCounter = 0;
break;
}
case 1: {
if(this.#runtimeTimer)
this.#runtimeTimer = setInterval(this.#SPSRuntime, this.#SPSCycleTime);
break;
}
case 2: {
clearInterval(this.#runtimeTimer);
break;
}
}
}
/**
* Loads the IL code into the SPS and generates the corresponding JavaScript code.
*
* @param {string|string[]} ImputCode - The IL code to be loaded (Array for multiple networks).
* @param {function} [errorCallback] - The error callback function. Does return an error message. If not provided, the default error callback logs the error to the console.
* @return {number} - Returns 0 if the IL code is valid and the JavaScript code is generated successfully, -1 otherwise.
*/
loadCode(ImputCode, errorCallback) {
let invalidCommand = false;
if (typeof errorCallback !== "function") {
errorCallback = (message) => console.error(message);
}
this.codeInput = ImputCode;
//Code with multiple networks
let codeArray = Array.isArray(this.codeInput)
? this.codeInput.flatMap((element) => {
const ret = generateCodeStructure(element, errorCallback);
if (ret != null) return ret;
else {
invalidCommand = true;
return [];
}
})
: generateCodeStructure(this.codeInput, errorCallback);
if (codeArray != null && codeArray.length > 0 && !invalidCommand) {
this.#SPSCode = generateJSCode(codeArray, errorCallback);
DEBUG && console.log("SPS:loadCode >> SPS Code: \n\n" + this.#SPSCode);
return 0;
} else {
console.error("SPS:loadCode >> Invalid IL Code");
this.#SPSCode = "";
return -1;
}
}
//Setter Methods
/**
* Sets the cycle time of the SPS.
*
* @param {number} delay - The cycle time in milliseconds.
* @return {number} 0 if the cycle time is set successfully, -1 if the cycle time is out of range.
*/
setCycleTime(delay) {
if (delay > 10 || delay < 1000) {
this.#SPSCycleTime = delay;
return 0;
} else {
console.error(
"SPS:setCycleTime >> Cycle Time must be between 10 and 1000ms"
);
return -1;
}
}
/**
* Sets the flags of the SPS.
*
* @param {array} flags - An array of flag values to be set.
* @return {number} 0 if the flags are set successfully.
*/
setFlags(flags) {
this.#dataReady = false;
for (let i = 0; i < this._M.length; i++) {
this._M[i] = flags[i];
}
DEBUG && console.log("SPS:setFlags >> Flags: " + this._M);
return 0;
}
/**
* Sets the input values of the SPS.
*
* @param {array} inputs - An array of the inputs to be set.
* @return {number} 0 if the input values are set successfully.
*/
setInputs(inputs) {
this.#dataReady = false;
for (let i = 0; i < this._E.length; i++) {
this._E[i] = inputs[i];
}
DEBUG && console.log("SPS:setInputs >> Input: " + this._E);
return 0;
}
//Getter Methods
/**
* Get the input states of the SPS.
*
* @return {array} An array of the input states.
*/
getInputs() {
const InputArray = [];
for (let i = 0; i < 8; i++) {
InputArray[i] = this._E[i];
}
DEBUG && console.log("SPS:getInputs >> getInputs: " + this._E);
return InputArray;
}
/**
* Get the current flag states of the SPS.
*
* @return {array} An array of the current flag states.
*/
getFlags() {
const FlagArray = [];
for (let i = 0; i < this._M.length; i++) {
FlagArray[i] = this._M[i];
}
DEBUG && console.log("SPS:getFlags >> Flags: " + this._M);
return FlagArray;
}
/**
* Get the current output states of the SPS.
*
* @return {array} An array of the current output states.
*/
getOutputs = () => {
if (!this.#dataReady && this.#state == 1) {
this.#SPSRuntime();
}
DEBUG && console.log("SPS:getOutputs >> Output: " + this._A);
return this._A;
};
/**
* Returns the current run-state of the SPS.
*
* @return {number} The current state of the SPS. 0 = Stopped, 1 = Running 2 = Paused
*/
getState() {
return this.#state;
}
/**
* Returns the current runtime counter of the SPS (how often the Runtime has been called).
*
* @return {number} The current runtime counter of the SPS.
*/
getRuntimeCounter() {
return this.#RuntimeCounter;
}
//State Methods
/**
* Set the state to started. Starts or continues the SPS.
*
* @return {number} 0 if SPS is started, -1 if SPS is already started
*/
start() {
if (this.#state == 1) return -1; //SPS already started
this.#state = 1;
this.#changeSPSState(this.#state);
DEBUG && console.log("SPS:Start >> State: " + this.#state);
return 0;
}
/**
* Set the state to stopped. Stops the SPS by resetting its state and clearing its input, output, and flag arrays.
*
* @return {number} 0 on successful stop
*/
stop() {
if (this.#state == 0) return -1; //SPS already stopped
this.#state = 0;
this._E.fill(0);
this._A.fill(0);
this._M.fill(0);
DEBUG && console.log(
"SPS:Stop >> State: " +
this.#state +
" at counter: " +
this.#RuntimeCounter
);
this.#changeSPSState(this.#state);
return 0;
}
/**
* Set the state to paused. In Paused state, the SPS will hold the current output and flag states
*
* @return {number} 0 on successful pause
*/
pause() {
if (this.#state == 2) return -1; //SPS already paused
this.#state = 2;
DEBUG && console.log(
"SPS:Pause >> State: " +
this.#state +
" at counter: " +
this.#RuntimeCounter
);
this.#changeSPSState(this.#state);
return 0;
}
/**
* Checks if data is updated.
*
* @return {boolean} True if output registers were updated after input change.
*/
dataAvailable() {
return this.#dataReady;
}
}
// SPS Helper Functions
/**
* Check if IL Code is valid and generates a Map that contains the Commands
*
* @param {String} CodeInput - Code to be validated
* @param {Function} errorCallback - Error callback
* @return {Array} - Array of Commands {type: insType, instruction: instruction, blockNumber: Number of Instruction}
*/
function generateCodeStructure(CodeInput, errorCallback) {
/* InsTypes:
* 0 = Undefined
* 1 = logical operation (U, O, X, NOT, UN, ON)
* 2 = Instruction (S, R, =)
* 3 = Operand (a, e, m)
* 4 = Bracket ((, ))
* 5 = comment (//)
* 6 = End of Network (;)
*/
const validlogicalOperations = ["U", "O", "X", "NOT", "UN", "ON"];
const validInstructions = ["=", "S", "R"];
const validOperands = ["A", "E", "M"];
const validBrackets = ["(", ")"];
//Generate RegEx to check for valid operands with only numbers following
const validOperandsRegex = new RegExp(`^(${validOperands.join("|")})\\d+$`);
let BracketCount = 0;
let invalidCommand = false;
/** commandArray: {type: insType, instruction: instruction, blockNumber: Number of Instruction} */
const commandArray = [];
//Convert Code to upper Case
CodeInput = CodeInput.toUpperCase();
//Remove comments
CodeInput = CodeInput.replace(/\/\/.*$/gm, "");
// Split the code input by line, brackets and spaces
let codeParts = CodeInput.split(/([\s\t\n(){}\[\]])/);
codeParts = codeParts.filter(
(part) => part.trim().length > 0 || /[(){}\[\]]/.test(part)
);
//TODO: Check for commands in right order (first Ops or Inst, then operands)
codeParts.forEach((codePart) => {
//check for Type
if (validlogicalOperations.includes(codePart)) {
commandArray.push({
type: 1,
instruction: codePart,
blockNumber: commandArray.length,
});
} else if (validInstructions.includes(codePart)) {
commandArray.push({
type: 2,
instruction: codePart,
blockNumber: commandArray.length,
});
} else if (validOperandsRegex.test(codePart)) {
commandArray.push({
type: 3,
instruction: codePart,
blockNumber: commandArray.length,
});
} else if (validBrackets.includes(codePart)) {
if (codePart == "(") BracketCount++;
else BracketCount--;
commandArray.push({
type: 4,
instruction: codePart,
blockNumber: commandArray.length,
});
} else {
errorCallback(
"generateCodeStructure >> Unknown command or operand found: " + codePart
);
invalidCommand = true;
return null; // Invalid command or operand found
}
});
//Check if brackets are balanced
if (BracketCount != 0) {
errorCallback("generateCodeStructure >> Invalid bracket number");
invalidCommand = true;
}
//check if invalid command is found
if (invalidCommand) return null;
//Add End of Network to fill empty if bodies
commandArray.push({
type: 6,
instruction: ";",
blockNumber: commandArray.length,
});
return commandArray;
}
/**
* Generates JavaScript code from a given command array.
*
* @param {Array} commandArray - An array of SPS commands to generate JavaScript code from.
* @param {Function} errorCallback - A callback function to handle errors during code generation.
* @return {String} The generated JavaScript code.
*/
function generateJSCode(commandArray, errorCallback) {
let JSCode = "";
let lastInstruction = "";
let isNewBlock = true;
let openIfBlock = false;
for (const command of commandArray) {
if (command.type == 6) {
JSCode += "; // End of Network\n";
continue;
}
if (isNewBlock) {
switch (command.type) {
case 1: {
openIfBlock = true;
isNewBlock = false;
if(command.instruction == "NOT") JSCode += "if( !";
else JSCode += "if( ";
break;
}
case 2: {
if (command.instruction == "S") {
lastInstruction = "S";
isNewBlock = false;
break;
} else if (command.instruction == "R") {
lastInstruction = "R";
isNewBlock = false;
break;
} else {
errorCallback(
"generateJSCode >> Missing logical Operand before =: " +
command.instruction
);
return null;
}
} // Fallthrough intended if not breaking above
case 4: {
if(command.type === 4) { // Only if fallthrough or direct hit
errorCallback(
"generateJSCode >> Bracket without logical Operand: " +
command.instruction
);
return null;
}
}
default: {
if (command.type !== 2) { // Determine if here by default or fallthrough
errorCallback(
"generateJSCode >> Not valid as first command: " +
command.instruction
);
return null;
}
}
}
} else
switch (command.type) {
case 1: {
if (command.instruction == "U") JSCode += " && ";
else if (command.instruction == "O") JSCode += " || ";
else if (command.instruction == "X") JSCode += " !==";
else if (command.instruction == "NOT") JSCode += " !";
else if (command.instruction == "UN") JSCode += " && !";
else if (command.instruction == "ON") JSCode += " || !";
else {
errorCallback(
"generateJSCode >> Unknown logical Operant: " +
command.instruction
);
return null;
}
break;
}
case 2: {
if (command.instruction == "S") {
lastInstruction = "S";
} else if (command.instruction == "R") {
lastInstruction = "R";
} else {
lastInstruction = "=";
}
break;
}
case 3: {
const slicedCommand = [command.instruction[0]];
slicedCommand.push(parseInt(command.instruction.slice(1)) - 1);
if (openIfBlock) {
if (lastInstruction == "S") {
lastInstruction = "";
openIfBlock = false;
isNewBlock = true;
JSCode +=
") { " +
"this._" +
slicedCommand[0] +
"[" +
slicedCommand[1] +
"]" +
" = true; } \n";
} else if (lastInstruction == "R") {
lastInstruction = "";
openIfBlock = false;
isNewBlock = true;
JSCode +=
") { " +
"this._" +
slicedCommand[0] +
"[" +
slicedCommand[1] +
"]" +
" = false; }\n";
} else if (lastInstruction == "=") {
lastInstruction = "";
openIfBlock = false;
isNewBlock = true;
JSCode +=
") { " +
"this._" +
slicedCommand[0] +
"[" +
slicedCommand[1] +
"]" +
" = true; } else { " +
"this._" +
slicedCommand[0] +
"[" +
slicedCommand[1] +
"]" +
" = false; }\n";
} else
JSCode +=
"this._" + slicedCommand[0] + "[" + slicedCommand[1] + "]";
break;
} else {
if (lastInstruction == "S") {
lastInstruction = "";
JSCode +=
"this._" +
slicedCommand[0] +
"[" +
slicedCommand[1] +
"]" +
" = true; ";
isNewBlock = true;
} else if (lastInstruction == "R") {
lastInstruction = "";
JSCode +=
"this._" +
slicedCommand[0] +
"[" +
slicedCommand[1] +
"]" +
" = false; ";
isNewBlock = true;
} else {
errorCallback(
"generateJSCode >> Missing logical Operant before =: " +
command.instruction
);
return null;
}
}
break;
}
case 4: {
if (openIfBlock) {
if (command.instruction == "(") JSCode += " ( ";
else JSCode += " ) ";
}
}
}
}
return JSCode;
}