forked from riclolsen/json-scada
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcs_data_processor.js
1464 lines (1394 loc) · 56 KB
/
cs_data_processor.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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* A process that watches for raw data updates from protocols using a MongoDB change stream.
* Converts raw protocol values into analogs/statuses then updates realtime, soe and historical data.
* {json:scada} - Copyright (c) 2020-2025 - Ricardo L. Olsen
* This file is part of the JSON-SCADA distribution (https://github.com/riclolsen/json-scada).
*
* 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, version 3.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict'
const AppDefs = require('./app-defs')
const Log = require('./simple-logger')
const LoadConfig = require('./load-config')
const Redundancy = require('./redundancy')
const sqlFilesPath = '../../sql/'
const fs = require('fs')
const { MongoClient, Double } = require('mongodb')
const Queue = require('queue-fifo')
const { setInterval } = require('timers')
const MongoStatus = { HintMongoIsConnected: false }
const LowestPriorityThatBeeps = 1 // will beep for priorities zero and one
process.on('uncaughtException', (err) =>
Log.log('Uncaught Exception:' + JSON.stringify(err))
)
const args = process.argv.slice(2)
var inst = null
if (args.length > 0) inst = parseInt(args[0])
var logLevel = null
if (args.length > 1) logLevel = parseInt(args[1])
var confFile = null
if (args.length > 2) confFile = args[2]
const jsConfig = LoadConfig(confFile, logLevel, inst)
let DivideProcessingExpression = {}
if (
AppDefs.ENV_PREFIX + 'DIVIDE_EXP' in process.env &&
process.env[AppDefs.ENV_PREFIX + DIVIDE_EXP].trim() !== ''
) {
try {
DivideProcessingExpression = JSON.parse(
process.env[AppDefs.ENV_PREFIX + 'DIVIDE_EXP']
)
Log.log(
'Divide Processing Expression: ' +
JSON.stringify(DivideProcessingExpression)
)
} catch (e) {
DivideProcessingExpression = {}
Log.log('Divide Processing Expression: ERROR!' + e)
process.exit(1)
}
}
const beepPointKey = -1
const cntUpdatesPointKey = -2
const invalidDetectCycle = 43000
Log.log('Connecting to MongoDB server...')
const pipeline = [
{
$project: { documentKey: false },
},
{
$match: {
$and: [
{ 'fullDocument.value': { $exists: true } },
DivideProcessingExpression,
{
'updateDescription.updatedFields.sourceDataUpdate': { $exists: true },
},
{
$or: [{ operationType: 'update' }],
},
],
},
},
]
;(async () => {
let collection = null
let histCollection = null
let sqlHistQueue = new Queue() // queue of historical values to insert on postgreSQL
let sqlRtDataQueue = new Queue() // queue of realtime values to insert on postgreSQL
let mongoRtDataQueue = new Queue() // queue of realtime values to insert on MongoDB
let digitalUpdatesCount = 0
let clientMongo = null
// mark as frozen unchanged analog values greater than 1 after timeout
setInterval(async function () {
if (collection && MongoStatus.HintMongoIsConnected && clientMongo) {
collection
.updateMany(
{
$and: [
{ type: 'analog' },
{ invalid: false },
{ frozen: false },
{ frozenDetectTimeout: { $gt: 0.0 } },
{ timeTag: { $ne: null } },
{ $expr: { $gt: [{ $abs: '$value' }, 1.0] } },
{
$expr: {
$lt: [
'$timeTag',
{
$subtract: [
new Date(),
{ $multiply: ['$frozenDetectTimeout', 1000.0] },
],
},
],
},
},
],
},
{ $set: { frozen: true } }
)
.catch(function (err) {
Log.log('Error on Mongodb query!', err)
})
}
}, 17317)
// process updates to mongo/realtimeData
async function processRtDataMongoUpdates() {
if (
!collection ||
!clientMongo ||
!MongoStatus.HintMongoIsConnected ||
mongoRtDataQueue.isEmpty()
) {
setTimeout(processRtDataMongoUpdates, 150)
return
}
let cnt = 0
let updArr = []
while (!mongoRtDataQueue.isEmpty()) {
const upd = mongoRtDataQueue.peek()
mongoRtDataQueue.dequeue()
const _id = upd._id
delete upd._id // remove _id for update
let addToSet = null
if ('$addToSet' in upd) {
addToSet = upd.$addToSet
delete upd.$addToSet
}
updArr.push({
updateOne: {
filter: { _id: _id },
update: { $set: upd },
},
})
cnt++
if (addToSet) {
updArr.push({
updateOne: {
filter: { _id: _id },
update: { $addToSet: addToSet },
},
})
cnt++
}
}
const res = await collection
.bulkWrite(updArr, {
ordered: false,
writeConcern: {
w: 0,
},
})
.catch(function (err) {
Log.log('Error on Mongodb query!', err)
})
if (cnt) Log.log('Mongo Updates ' + cnt)
setTimeout(processRtDataMongoUpdates, 150)
}
processRtDataMongoUpdates()
// write values to sql files for later insertion on postgreSQL, and mongo hist
async function processSqlAndMongoHistUpdates() {
if (!histCollection || !clientMongo || !MongoStatus.HintMongoIsConnected) {
setTimeout(processSqlAndMongoHistUpdates, 333)
return
}
try {
let doInsertData = false
let sqlTransaction =
'START TRANSACTION;\n' +
'INSERT INTO hist (tag, time_tag, value, value_json, time_tag_at_source, flags) VALUES '
let cntH = 0
let insertArr = []
while (!sqlHistQueue.isEmpty()) {
doInsertData = true
let entry = sqlHistQueue.peek()
sqlHistQueue.dequeue()
sqlTransaction = sqlTransaction + '\n(' + entry.sql + '),'
insertArr.push(entry.obj)
cntH++
}
if (cntH) Log.log('PGSQL/Mongo Hist updates ' + cntH)
if (doInsertData) {
histCollection
.insertMany(insertArr, { ordered: false, writeConcern: { w: 0 } })
.catch(function (err) {
Log.log('Error on Mongodb query!', err)
})
sqlTransaction = sqlTransaction.substring(0, sqlTransaction.length - 1) // remove last comma
sqlTransaction = sqlTransaction + ' \n'
// this cause problems when tag/time repeated on same transaction
// sqlTransaction = sqlTransaction + "ON CONFLICT (tag, time_tag) DO UPDATE SET value=EXCLUDED.value, value_json=EXCLUDED.value_json, time_tag_at_source=EXCLUDED.time_tag_at_source, flags=EXCLUDED.flags;\n";
sqlTransaction =
sqlTransaction + 'ON CONFLICT (tag, time_tag) DO NOTHING;\n'
sqlTransaction = sqlTransaction + 'COMMIT;\n'
fs.writeFile(
sqlFilesPath +
'pg_hist_' +
new Date().getTime() +
'_' +
jsConfig.Instance +
'.sql',
sqlTransaction,
(err) => {
if (err) Log.log('Error writing SQL file!')
}
)
}
doInsertData = false
sqlTransaction = ''
let cntR = 0
sqlTransaction =
sqlTransaction +
'WITH ordered_values AS ( SELECT DISTINCT ON (tag) tag, time_tag, json_data FROM (VALUES '
while (!sqlRtDataQueue.isEmpty()) {
doInsertData = true
let sql = sqlRtDataQueue.peek()
sqlRtDataQueue.dequeue()
sqlTransaction = sqlTransaction + '\n (' + sql + '),'
cntR++
}
sqlTransaction = sqlTransaction.substring(0, sqlTransaction.length - 1) // remove last comma
sqlTransaction = sqlTransaction + ' \n'
sqlTransaction =
sqlTransaction +
`) AS t(tag, time_tag, json_data)
ORDER BY tag, time_tag DESC
)
INSERT INTO realtime_data (tag, time_tag, json_data)
SELECT tag, time_tag::timestamptz, json_data::jsonb
FROM ordered_values
ON CONFLICT (tag) DO UPDATE
SET time_tag = EXCLUDED.time_tag,
json_data = EXCLUDED.json_data;
`
if (cntR) Log.log('PGSQL RT updates ' + cntR)
if (doInsertData) {
fs.writeFile(
sqlFilesPath +
'pg_rtdata_' +
new Date().getTime() +
'_' +
jsConfig.Instance +
'.sql',
sqlTransaction,
(err) => {
if (err) Log.log('Error writing SQL file!')
}
)
}
} catch (e) {
Log.log('Error in processSqlAndMongoHistUpdates: ' + e)
}
setTimeout(processSqlAndMongoHistUpdates, 333)
}
processSqlAndMongoHistUpdates()
let invalidDetectIntervalHandle = null
let latencyIntervalHandle = null
let resumeToken = null
while (true) {
if (clientMongo === null)
await MongoClient.connect(
jsConfig.mongoConnectionString,
jsConfig.MongoConnectionOptions
)
.then(async (client) => {
clientMongo = client
clientMongo.on('topologyClosed', () => {
MongoStatus.HintMongoIsConnected = false
clientMongo = null
Log.log('MongoDB server topologyClosed')
})
MongoStatus.HintMongoIsConnected = true
Log.log('Connected correctly to MongoDB server')
if (resumeToken)
Log.log('resumeToken: ' + JSON.stringify(resumeToken))
let latencyAccTotal = 0
let latencyTotalCnt = 0
let latencyAccMinute = 0
let latencyMinuteCnt = 0
let latencyPeak = 0
clearInterval(latencyIntervalHandle)
latencyIntervalHandle = setInterval(function () {
latencyAccMinute = 0
latencyMinuteCnt = 0
}, 60000)
// specify db and collections
const db = client.db(jsConfig.mongoDatabaseName)
collection = db.collection(jsConfig.RealtimeDataCollectionName)
histCollection = db.collection(jsConfig.HistCollectionName)
const changeStream = collection.watch(pipeline, {
fullDocument: 'updateLookup',
resumeAfter: resumeToken,
})
await createSpecialTags(collection)
Redundancy.Start(5000, clientMongo, db, jsConfig, MongoStatus)
// periodically, mark invalid data when supervised points not updated within specified period (invalidDetectTimeout) for the point
// check also stopped protocol driver instances
clearInterval(invalidDetectIntervalHandle)
invalidDetectIntervalHandle = setInterval(async function () {
if (clientMongo !== null && MongoStatus.HintMongoIsConnected) {
collection
.updateMany(
{
$expr: {
$and: [
{ $eq: ['$origin', 'supervised'] },
{ $ne: ['$substituted', true] },
{ $eq: ['$invalid', false] },
{
$lt: [
'$sourceDataUpdate.timeTag',
{
$subtract: [
new Date(),
{ $multiply: [1000, '$invalidDetectTimeout'] },
],
},
],
},
],
},
},
{ $set: { invalid: true } }
)
.catch(function (err) {
Log.log('Error on Mongodb query!', err)
})
// look for client drivers instance not updating keep alive, if found invalidate all related data points of all its connections
const results = await db
.collection(jsConfig.ProtocolDriverInstancesCollectionName)
.find({
$expr: {
$and: [
{
$in: [
'$protocolDriver',
[
'IEC60870-5-104',
'IEC60870-5-101',
'IEC60870-5-103',
'DNP3',
'MQTT-SPARKPLUG-B',
'OPC-UA',
'OPC-DA',
'TELEGRAF-LISTENER',
'PLCTAG',
'PLC4X',
'MODBUS',
'IEC61850',
'ICCP',
],
],
},
{ $eq: ['$enabled', true] },
{
$lt: [
'$activeNodeKeepAliveTimeTag',
{
$subtract: [new Date(), { $multiply: [1000, 15] }],
},
],
},
],
},
})
.toArray()
if (results && results.length > 0)
for (let i = 0; i < results.length; i++) {
Log.log('PROTOCOL INSTANCE NOT RUNNING DETECTED!')
let instance = results[i]
Log.log(
'Driver Name: ' +
instance?.protocolDriver +
' Instance Number: ' +
instance?.protocolDriverInstanceNumber
)
// find all connections related to his instance
const res = await db
.collection(jsConfig.ProtocolConnectionsCollectionName)
.find({
protocolDriver: instance?.protocolDriver,
protocolDriverInstanceNumber:
instance?.protocolDriverInstanceNumber,
})
.toArray()
if (res && res.length > 0)
for (let i = 0; i < res.length; i++) {
let connection = res[i]
Log.log(
'Data invalidated for connection: ' +
connection?.protocolConnectionNumber
)
await db
.collection(jsConfig.RealtimeDataCollectionName)
.updateMany(
{
origin: 'supervised',
protocolSourceConnectionNumber:
connection?.protocolConnectionNumber,
invalid: false,
},
{
$set: {
invalid: true,
},
}
)
.catch(function (err) {
Log.log('Error on Mongodb query!', err)
})
}
}
}
}, invalidDetectCycle)
try {
changeStream.on('error', (change) => {
if (clientMongo) clientMongo.close()
clientMongo = null
Log.log('Error on ChangeStream!')
})
changeStream.on('close', (change) => {
clientMongo = null
Log.log('Closed ChangeStream!')
})
changeStream.on('end', (change) => {
if (clientMongo) clientMongo.close()
clientMongo = null
Log.log('Ended ChangeStream!')
})
// start listen to changes
changeStream.on('change', (change) => {
try {
resumeToken = changeStream.resumeToken
if (change.operationType === 'delete') return
// // for older versions of mongodb
// if (
// change.operationType === 'replace' &&
// !change?.updateDescription?.updatedFields &&
// change.fullDocument.sourceDataUpdate
// ) {
// change['updateDescription'] = {
// updatedFields: {
// sourceDataUpdate: change.fullDocument.sourceDataUpdate,
// },
// }
// }
let isSOE = false
let alarmRange = 0
if (change.operationType === 'insert') {
// document inserted
Log.log(
'INSERT ' +
change.fullDocument._id +
' ' +
change.fullDocument.tag +
' ' +
value
)
sqlRtDataQueue.enqueue(
"'" +
change.fullDocument.tag +
"'," +
"'" +
new Date().toISOString() +
"'," +
"to_json('" +
JSON.stringify(change.fullDocument) +
"'::text)"
)
}
if (!Redundancy.ProcessStateIsActive())
// when inactive, ignore changes
return
if (
!(
'sourceDataUpdate' in change.updateDescription.updatedFields
)
)
// if not a Source Data Update (protocol update), return
return
let delay =
new Date().getTime() -
change.updateDescription.updatedFields.sourceDataUpdate.timeTag.getTime()
latencyAccTotal += delay
latencyTotalCnt++
latencyAccMinute += delay
latencyMinuteCnt++
if (delay > latencyPeak) latencyPeak = delay
// consider SOE when digital changes has field timestamp
// or analog with isEvent true
if (
'timeTagAtSource' in
change.updateDescription.updatedFields.sourceDataUpdate
)
if (
change.updateDescription.updatedFields.sourceDataUpdate
.timeTagAtSource !== null
)
if (
change.fullDocument.type === 'digital' ||
(change.fullDocument.type === 'analog' &&
change.fullDocument.isEvent)
) {
if (
change.updateDescription.updatedFields.sourceDataUpdate.timeTagAtSource.getFullYear() >
1899
) {
isSOE = true
}
}
// check quality bits set by the protocol driver
let invalid = false,
transient = false,
overflow = false,
nottopical = false,
carry = false,
substituted = false,
blocked = false
if (
typeof change.updateDescription.updatedFields.sourceDataUpdate
.invalidAtSource === 'boolean'
) {
invalid =
change.updateDescription.updatedFields.sourceDataUpdate
.invalidAtSource
}
if (
typeof change.updateDescription.updatedFields.sourceDataUpdate
.notTopicalAtSource === 'boolean'
) {
invalid =
invalid ||
change.updateDescription.updatedFields.sourceDataUpdate
.notTopicalAtSource
nottopical =
change.updateDescription.updatedFields.sourceDataUpdate
.notTopicalAtSource
}
if (
typeof change.updateDescription.updatedFields.sourceDataUpdate
.overflowAtSource === 'boolean'
) {
invalid =
invalid ||
change.updateDescription.updatedFields.sourceDataUpdate
.overflowAtSource
overflow =
change.updateDescription.updatedFields.sourceDataUpdate
.overflowAtSource
}
if (
typeof change.updateDescription.updatedFields.sourceDataUpdate
.transientAtSource === 'boolean'
) {
invalid =
invalid ||
change.updateDescription.updatedFields.sourceDataUpdate
.transientAtSource
transient =
change.updateDescription.updatedFields.sourceDataUpdate
.transientAtSource
}
if (
typeof change.updateDescription.updatedFields.sourceDataUpdate
.carryAtSource === 'boolean'
) {
carry =
change.updateDescription.updatedFields.sourceDataUpdate
.carryAtSource
}
if (
typeof change.updateDescription.updatedFields.sourceDataUpdate
.substitutedAtSource === 'boolean'
) {
substituted =
change.updateDescription.updatedFields.sourceDataUpdate
.substitutedAtSource
}
if (
typeof change.updateDescription.updatedFields.sourceDataUpdate
.blockedAtSource === 'boolean'
) {
blocked =
change.updateDescription.updatedFields.sourceDataUpdate
.blockedAtSource
}
let value =
change.updateDescription.updatedFields.sourceDataUpdate
.valueAtSource
let valueString =
change.updateDescription.updatedFields.sourceDataUpdate
?.valueStringAtSource || ''
let valueJson =
change.updateDescription.updatedFields.sourceDataUpdate
?.valueJsonAtSource || ''
let alarmed = change.fullDocument.alarmed
// avoid undefined, null or NaN values
if (value === null || value === undefined || isNaN(value)) {
value = 0.0
invalid = true
}
// Qualifier to be shown in valueString
let txtQualif = ''
txtQualif = txtQualif + (invalid ? '[IV]' : '')
txtQualif = txtQualif + (transient ? '[TR]' : '')
txtQualif = txtQualif + (overflow ? '[OV]' : '')
txtQualif = txtQualif + (nottopical ? '[NT]' : '')
txtQualif = txtQualif + (carry ? '[CR]' : '')
txtQualif = txtQualif + (substituted ? '[SB]' : '')
txtQualif = txtQualif + (blocked ? '[BK]' : '')
if (change.fullDocument.type === 'digital') {
// test for double point status
if (
'asduAtSource' in
change.updateDescription.updatedFields.sourceDataUpdate
) {
if (
change.updateDescription.updatedFields.sourceDataUpdate.asduAtSource.indexOf(
'M_DP_'
) === 0
) {
if (value === 0 || value === 3) {
transient = true
invalid = true
if (txtQualif.indexOf('[IV]') < 0)
txtQualif = txtQualif + (transient ? '[IV]' : '')
if (txtQualif.indexOf('[TR]') < 0)
txtQualif = txtQualif + (transient ? '[TR]' : '')
if (txtQualif !== '') txtQualif = ' ' + txtQualif
}
value = (value & 0x01) == 0 ? 1 : 0
}
}
// process inversions (kconv1=-1)
if (change.fullDocument.kconv1 === -1)
value = value === 0 ? 1 : 0
if (
value != change.fullDocument.value &&
!change.fullDocument.alarmDisabled
)
alarmed = true
if (value)
valueString =
change.fullDocument.stateTextTrue +
(change.fullDocument.unit != ''
? ' ' + change.fullDocument.unit
: '') +
txtQualif
else
valueString =
change.fullDocument.stateTextFalse +
(change.fullDocument.unit != ''
? ' ' + change.fullDocument.unit
: '') +
txtQualif
} else if (change.fullDocument.type === 'analog') {
if (txtQualif != '') txtQualif = ' ' + txtQualif
// apply conversion factors
value =
change.updateDescription.updatedFields.sourceDataUpdate
.valueAtSource *
change.fullDocument.kconv1 +
change.fullDocument.kconv2
if ('zeroDeadband' in change.fullDocument)
if (
change.fullDocument.zeroDeadband !== 0 &&
Math.abs(value) < change.fullDocument.zeroDeadband
)
value = 0.0
valueString =
'' +
parseFloat(value.toFixed(4)) +
' ' +
change.fullDocument.unit +
txtQualif
if (
'asduAtSource' in
change.updateDescription.updatedFields.sourceDataUpdate
)
if (
change.updateDescription.updatedFields.sourceDataUpdate.asduAtSource.indexOf(
'M_BO_'
) === 0
) {
// test for bitstring
valueString =
value.toString(2) +
' ' +
change.fullDocument.unit +
txtQualif
}
let hysteresis = 0
if (change.fullDocument?.hysteresis)
hysteresis = parseFloat(change.fullDocument.hysteresis)
// check for limits
if (
// value != change.fullDocument.value &&
'hiLimit' in change.fullDocument &&
change.fullDocument.hiLimit !== null &&
'loLimit' in change.fullDocument &&
change.fullDocument.loLimit !== null &&
!change.fullDocument.alarmDisabled
) {
if (value > change.fullDocument.hiLimit + hysteresis) {
alarmRange = 1
} else if (
value <
change.fullDocument.loLimit - hysteresis
) {
alarmRange = -1
} else if (
value < change.fullDocument.hiLimit - hysteresis &&
value > change.fullDocument.loLimit + hysteresis
) {
alarmed = false
alarmRange = 0
} else if (change.fullDocument?.alarmRange)
// keep the old range if out of range
alarmRange = change.fullDocument.alarmRange
// create a SOE entry for the limits alarm/normalization when analog alarm condition changes
//if (alarmed != change.fullDocument.alarmed)
//if (
// change.fullDocument.value <= change.fullDocument.hiLimit + hysteresis &&
// value > change.fullDocument.hiLimit + hysteresis
// ||
// change.fullDocument.value >= change.fullDocument.hiLimit - hysteresis &&
// value < change.fullDocument.hiLimit - hysteresis
// ||
// change.fullDocument.value >= change.fullDocument.loLimit - hysteresis &&
// value < change.fullDocument.loLimit - hysteresis
// ||
// change.fullDocument.value <= change.fullDocument.loLimit + hysteresis &&
// value > change.fullDocument.loLimit + hysteresis
// )
if (!change.fullDocument.alarmDisabled)
if (change.fullDocument?.alarmRange != alarmRange) {
if (alarmRange != 0) alarmed = true
const eventDate = new Date()
const eventText =
parseFloat(value.toFixed(3)) +
' ' +
change.fullDocument.unit +
(Math.abs(value) >
Math.abs(change.fullDocument?.value)
? ' ⤉'
: Math.abs(value) <
Math.abs(change.fullDocument?.value)
? ' ⤈'
: '') +
(alarmed ? ' 🚩' : ' 🆗')
db.collection(jsConfig.SoeDataCollectionName)
.insertOne(
{
tag: change.fullDocument.tag,
pointKey: change.fullDocument._id,
group1: change.fullDocument.group1,
description: change.fullDocument.description,
eventText: eventText,
invalid: false,
priority: change.fullDocument.priority,
timeTag: eventDate,
timeTagAtSource: eventDate,
timeTagAtSourceOk: true,
ack: alarmed ? 0 : 1, // enter as acknowledged when normalized
},
{
writeConcern: {
w: 0,
},
}
)
.catch(function (err) {
Log.log('Error on Mongodb query!', err)
})
}
}
// analog tags can produce SOE events when marked as isEvent and valid value change, or having source timestamp
if (!change.fullDocument.alarmDisabled)
if (
(change.fullDocument?.isEvent === true &&
!invalid &&
value !== change.fullDocument?.value) ||
isSOE
) {
const eventText =
parseFloat(value.toFixed(3)) +
' ' +
change.fullDocument.unit +
(Math.abs(value) > Math.abs(change.fullDocument?.value)
? ' ↑'
: Math.abs(value) <
Math.abs(change.fullDocument?.value)
? ' ↓'
: '')
db.collection(jsConfig.SoeDataCollectionName)
.insertOne(
{
tag: change.fullDocument.tag,
pointKey: change.fullDocument._id,
group1: change.fullDocument.group1,
description: change.fullDocument.description,
eventText: eventText,
invalid: false,
priority: change.fullDocument.priority,
timeTag: new Date(),
timeTagAtSource: isSOE
? change.updateDescription.updatedFields
.sourceDataUpdate.timeTagAtSource
: new Date(),
timeTagAtSourceOk: isSOE
? change.updateDescription.updatedFields
.sourceDataUpdate.timeTagAtSourceOk
: false,
ack: 1, // enter as acknowledged as it is not an alarm
},
{
writeConcern: {
w: 0,
},
}
)
.catch(function (err) {
Log.log('Error on Mongodb query!', err)
})
}
}
let alarmTime = null
// if changed to alarmed state, or digital change or soe, register new alarm tag
if (!change.fullDocument.alarmDisabled && alarmed) {
if (
!change.fullDocument.alarmed ||
(change.fullDocument.type === 'digital' &&
value !== change.fullDocument.value) ||
(change.fullDocument.type === 'digital' && isSOE)
) {
alarmTime = new Date()
}
}
// update only realtimeData if changed or for SOE, must not be historical backfill
if (
(isSOE ||
change.updateDescription.updatedFields.sourceDataUpdate
?.rangeCheck ||
value !== change.fullDocument.value ||
valueString !== change.fullDocument.valueString ||
invalid !== change.fullDocument.invalid) &&
!change.updateDescription.updatedFields.sourceDataUpdate
?.isHistorical
) {
let dt = new Date()
if (!change.fullDocument.alarmDisabled) {
if (
(alarmed &&
isSOE &&
change.fullDocument?.isEvent === true &&
change.fullDocument.type === 'digital' &&
value != 0) ||
(alarmed &&
change.fullDocument?.isEvent === false &&
change.fullDocument.type === 'digital') ||
(alarmed && change.fullDocument?.alarmed === false)
) {
// a new alarm, then update beep var
Log.log('NEW BEEP, tag: ' + change.fullDocument.tag)
if (change.fullDocument.priority === 0)
// signal an important beep (for alarm of priority 0)
mongoRtDataQueue.enqueue({
_id: beepPointKey,
beepType: new Double(2), // this is an important beep
value: new Double(1),
valueString: 'Beep Active',
timeTag: dt,
$addToSet: {
beepGroup1List: change.fullDocument.group1,
},
})
else if (
change.fullDocument.priority <= LowestPriorityThatBeeps
)
mongoRtDataQueue.enqueue({
_id: beepPointKey,
value: new Double(1),
valueString: 'Beep Active',
timeTag: dt,
$addToSet: {
beepGroup1List: change.fullDocument.group1,
},
})
}
if (change.fullDocument.type === 'digital') {
digitalUpdatesCount++
mongoRtDataQueue.enqueue({
_id: cntUpdatesPointKey,
value: new Double(digitalUpdatesCount),
valueString: '' + digitalUpdatesCount + ' Updates',
timeTag: dt,
})
}
}
// historianPeriod<0 or update is not for historical record, excludes from historian
let insertIntoHistorian = true
if ('historianPeriod' in change.fullDocument) {
if (
change.fullDocument.historianPeriod < 0 ||
change.updateDescription.updatedFields.sourceDataUpdate
?.isNotForHistorical
) {
insertIntoHistorian = false
} else {
// historianPeriod >= 0, will test dead band for analogs
if (
change.fullDocument?.type === 'analog' &&
'historianDeadBand' in change.fullDocument
) {
if (
'historianLastValue' in change.fullDocument &&
change.fullDocument.historianLastValue !== null &&
change.fullDocument.historianDeadBand > 0
) {
// test for variation less than absolute dead band
if (
Math.abs(