/
condition.js
2113 lines (1850 loc) · 72.6 KB
/
condition.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
"use strict";
/**
* @module opcua.address_space.AlarmsAndConditions
*/
require("set-prototype-of");
const EventEmitter = require("events").EventEmitter;
const util = require("util");
const assert = require("node-opcua-assert").assert;
const _ = require("underscore");
const UAVariable = require("../ua_variable").UAVariable;
const Variant = require("node-opcua-variant").Variant;
const DataType = require("node-opcua-variant").DataType;
const StatusCodes = require("node-opcua-status-code").StatusCodes;
const StatusCode = require("node-opcua-status-code").StatusCode;
const UAObjectType = require("../ua_object_type").UAObjectType;
const UAObject = require("../ua_object").UAObject;
const BaseNode = require("../base_node").BaseNode;
const AttributeIds = require("node-opcua-data-model").AttributeIds;
const NodeClass = require("node-opcua-data-model").NodeClass;
const TimeZone = require("node-opcua-data-model").TimeZone;
const UAStateMachine = require("../state_machine/finite_state_machine").UAStateMachine;
const UATwoStateVariable = require("../ua_two_state_variable").UATwoStateVariable;
const resolveNodeId = require("node-opcua-nodeid").resolveNodeId;
const coerceLocalizedText = require("node-opcua-data-model").coerceLocalizedText;
const LocalizedText = require("node-opcua-data-model").LocalizedText;
const NodeId = require("node-opcua-nodeid").NodeId;
const EventData = require("../address_space_add_event_type").EventData;
const debugLog = require("node-opcua-debug").make_debugLog(__filename);
const doDebug = require("node-opcua-debug").checkDebugFlag(__filename);
const AddressSpace = require("../address_space").AddressSpace;
const Namespace = require("../namespace").Namespace;
const SessionContext = require("../session_context").SessionContext;
const utils = require("node-opcua-utils");
function _visit(self, node, prefix) {
const aggregates = node.getAggregates();
aggregates.forEach(function(aggregate) {
if (aggregate instanceof UAVariable) {
let name = aggregate.browseName.toString();
name = utils.lowerFirstLetter(name);
const key = prefix + name;
// istanbul ignore next
if (doDebug) {
debugLog("adding key =", key);
}
self._map[key] = aggregate.readValue().value;
self._node_index[key] = aggregate;
_visit(self, aggregate, prefix + name + ".");
}
});
}
function _installOnChangeEventHandlers(self, node, prefix) {
const aggregates = node.getAggregates();
aggregates.forEach(function(aggregate) {
if (aggregate instanceof UAVariable) {
let name = aggregate.browseName.toString();
name = utils.lowerFirstLetter(name);
const key = prefix + name;
// istanbul ignore next
if (doDebug) {
debugLog("adding key =", key);
}
aggregate.on("value_changed", function(newDataValue, oldDataValue) {
self._map[key] = newDataValue.value;
self._node_index[key] = aggregate;
});
_installOnChangeEventHandlers(self, aggregate, prefix + name + ".");
}
});
}
function _ensure_condition_values_correctness(self, node, prefix, error) {
const displayError = !!error;
error = error || [];
const aggregates = node.getAggregates();
aggregates.forEach(function(aggregate) {
if (aggregate instanceof UAVariable) {
let name = aggregate.browseName.toString();
name = utils.lowerFirstLetter(name);
const key = prefix + name;
const snapshot_value = self._map[key].toString();
const condition_value = aggregate.readValue().value.toString();
if (snapshot_value !== condition_value) {
error.push(
" Condition Branch0 is not in sync with node values for " +
key +
"\n v1= " +
snapshot_value +
"\n v2= " +
condition_value
);
}
self._node_index[key] = aggregate;
_ensure_condition_values_correctness(self, aggregate, prefix + name + ".", error);
}
});
if (displayError && error.length) {
throw new Error(error.join("\n"));
}
}
function _record_condition_state(self, condition) {
self._map = {};
self._node_index = {};
assert(condition instanceof UAConditionBase);
_visit(self, condition, "");
}
/**
* @class ConditionSnapshot
* @extends EventEmitter
* @param condition
* @param branchId
* @constructor
*/
function ConditionSnapshot(condition, branchId) {
const self = this;
EventEmitter.call(this);
if (condition && branchId) {
assert(branchId instanceof NodeId);
//xx self.branchId = branchId;
self.condition = condition;
self.eventData = new EventData(condition);
// a nodeId/Variant map
_record_condition_state(self, condition);
if (branchId === NodeId.NullNodeId) {
_installOnChangeEventHandlers(self, condition, "");
}
self._set_var("branchId", DataType.NodeId, branchId);
}
}
util.inherits(ConditionSnapshot, EventEmitter);
// /**
// *
// * @return {ConditionSnapshot}
// */
// ConditionSnapshot.prototype.clone = function () {
// var self = this;
// var clone = new ConditionSnapshot();
// clone.branchId = self.branchId;
// clone.condition = self.condition;
// //xx clone.eventData = new EventData(clone.condition);
// clone._map = _.clone(self._map);
// return clone;
// };
const disabledVar = new Variant({
dataType: "StatusCode",
value: StatusCodes.BadConditionDisabled
});
ConditionSnapshot.prototype._constructEventData = function() {
const self = this;
const addressSpace = self.condition.addressSpace;
if (self.branchId === NodeId.NullNodeId) {
_ensure_condition_values_correctness(self, self.condition, "");
}
const isDisabled = !self.condition.getEnabledState();
const eventData = new EventData(self.condition);
Object.keys(self._map).forEach(function(key) {
const node = self._node_index[key];
if (isDisabled && !_varTable.hasOwnProperty(key)) {
eventData.setValue(key, node, disabledVar);
} else {
eventData.setValue(key, node, self._map[key]);
}
});
return eventData;
// self.condition.getAggregates().forEach(function(child){
// if (child instanceof UAVariable) {
// var name = utils.lowerFirstLetter(child.browseName.toString());
// self.eventData[name] =child.readValue().value;
// }
// });
// return self.eventData.clone();
};
/**
* @method resolveSelectClause
* @param selectClause {SelectClause}
*/
ConditionSnapshot.prototype.resolveSelectClause = function(selectClause) {
const self = this;
return self.eventData.resolveSelectClause(selectClause);
};
/**
* @method readValue
* @param nodeId {NodeId}
* @param selectClause {SelectClause}
* @return {Variant}
*/
ConditionSnapshot.prototype.readValue = function(nodeId, selectClause) {
const self = this;
const isDisabled = !self.condition.getEnabledState();
if (isDisabled) {
return disabledVar;
}
const key = nodeId.toString();
const variant = self._map[key];
if (!variant) {
// the value is not handled by us .. let's delegate
// to the eventData helper object
return self.eventData.readValue(nodeId, selectClause);
}
assert(variant instanceof Variant);
return variant;
};
function normalizeName(str) {
return str
.split(".")
.map(utils.lowerFirstLetter)
.join(".");
}
ConditionSnapshot.normalizeName = normalizeName;
// list of Condition variables that should not be published as BadConditionDisabled when the condition
// is in a disabled state.
var _varTable = {
branchId: 1,
eventId: 1,
eventType: 1,
sourceNode: 1,
sourceName: 1,
time: 1,
enabledState: 1,
"enabledState.id": 1,
"enabledState.effectiveDisplayName": 1,
"enabledState.transitionTime": 1,
conditionClassId: 1,
conditionClassName: 1,
conditionName: 1
};
ConditionSnapshot.prototype._get_var = function(varName, dataType) {
const self = this;
if (!self.condition.getEnabledState() && !_varTable.hasOwnProperty(varName)) {
console.log("ConditionSnapshot#_get_var condition enabled =", self.condition.getEnabledState());
return disabledVar;
}
const key = normalizeName(varName);
const variant = self._map[key];
return variant.value;
};
ConditionSnapshot.prototype._set_var = function(varName, dataType, value) {
const self = this;
const key = normalizeName(varName);
// istanbul ignore next
if (!self._map.hasOwnProperty(key)) {
if (doDebug) {
debugLog(" cannot find node ".white.bold.bgRed + varName.cyan);
debugLog(" map=", Object.keys(self._map).join(" "));
}
}
self._map[key] = new Variant({
dataType: dataType,
value: value
});
if (self._map[key + ".sourceTimestamp"]) {
self._map[key + ".sourceTimestamp"] = new Variant({
dataType: DataType.DateTime,
value: new Date()
});
}
const variant = self._map[key];
const node = self._node_index[key];
assert(node instanceof UAVariable);
self.emit("value_changed", node, variant);
};
/**
* @method getBrandId
* @return {NodeId}
*/
ConditionSnapshot.prototype.getBranchId = function() {
const self = this;
return self._get_var("branchId", DataType.NodeId);
};
/**
* @method getEventId
* @return {ByteString}
*/
ConditionSnapshot.prototype.getEventId = function() {
const self = this;
return self._get_var("eventId", DataType.ByteString);
};
/**
* @method getRetain
* @return {Boolean}
*/
ConditionSnapshot.prototype.getRetain = function() {
const self = this;
return self._get_var("retain", DataType.Boolean);
};
/**
*
* @method setRetain
* @param retainFlag {Boolean}
*/
ConditionSnapshot.prototype.setRetain = function(retainFlag) {
const self = this;
retainFlag = !!retainFlag;
return self._set_var("retain", DataType.Boolean, retainFlag);
};
/**
* @method renewEventId
*
*/
ConditionSnapshot.prototype.renewEventId = function() {
const self = this;
const addressSpace = self.condition.addressSpace;
// create a new event Id for this new condition
const eventId = addressSpace.generateEventId();
const ret = self._set_var("eventId", DataType.ByteString, eventId.value);
//xx var branch = self; console.log("MMMMMMMMrenewEventId branch " + branch.getBranchId().toString() + " eventId = " + branch.getEventId().toString("hex"));
return ret;
};
/**
* @method getEnabledState
* @return {Boolean}
*/
ConditionSnapshot.prototype.getEnabledState = function() {
const self = this;
return self._get_twoStateVariable("enabledState");
};
/**
* @method setEnabledState
* @param value {Boolean}
* @return void
*/
ConditionSnapshot.prototype.setEnabledState = function(value) {
const self = this;
return self._set_twoStateVariable("enabledState", value);
};
/**
* @method getEnabledStateAsString
* @return {String}
*/
ConditionSnapshot.prototype.getEnabledStateAsString = function() {
const self = this;
return self._get_var("enabledState", DataType.LocalizedText).text;
};
/**
* @method getComment
* @return {LocalizedText}
*/
ConditionSnapshot.prototype.getComment = function() {
const self = this;
return self._get_var("comment", DataType.LocalizedText);
};
/**
* Set condition comment
*
* Comment contains the last comment provided for a certain state (ConditionBranch). It may
* have been provided by an AddComment Method, some other Method or in some other
* manner. The initial value of this Variable is null, unless it is provided in some other manner. If
* a Method provides as an option the ability to set a Comment, then the value of this Variable is
* reset to null if an optional comment is not provided.
*
* @method setComment
* @param txtMessage {LocalizedText}
*/
ConditionSnapshot.prototype.setComment = function(txtMessage) {
const self = this;
assert(txtMessage);
txtMessage = coerceLocalizedText(txtMessage);
self._set_var("comment", DataType.LocalizedText, txtMessage);
/*
* OPCUA Spec 1.0.3 - Part 9:
* Comment, severity and quality are important elements of Conditions and any change
* to them will cause Event Notifications.
*
*/
self._need_event_raise = true;
};
/**
*
* @method setMessage
* @param txtMessage {LocalizedText}
*/
ConditionSnapshot.prototype.setMessage = function(txtMessage) {
const self = this;
assert(txtMessage);
txtMessage = coerceLocalizedText(txtMessage);
return self._set_var("message", DataType.LocalizedText, txtMessage);
};
/**
* @method setClientUserId
* @param userIdentity {String}
*/
ConditionSnapshot.prototype.setClientUserId = function(userIdentity) {
const self = this;
return self._set_var("clientUserId", DataType.String, userIdentity.toString());
};
/*
*
*
* as per spec 1.0.3 - Part 9
*
* Quality reveals the status of process values or other resources that this Condition instance is
* based upon. If, for example, a process value is “Uncertain”, the associated “LevelAlarm”
* Condition is also questionable. Values for the Quality can be any of the OPC StatusCodes
* defined in Part 8 as well as Good, Uncertain and Bad as defined in Part 4. These
* StatusCodes are similar to but slightly more generic than the description of data quality in the
* various field bus specifications. It is the responsibility of the Server to map internal status
* information to these codes. A Server which supports no quality information shall return Good.
* This quality can also reflect the communication status associated with the system that this
* value or resource is based on and from which this Alarm was received. For communication
* errors to the underlying system, especially those that result in some unavailable Event fields,
* the quality shall be Bad_NoCommunication error.
*
* Quality refers to the quality of the data value(s) upon which this Condition is based. Since a
* Condition is usually based on one or more Variables, the Condition inherits the quality of
* these Variables. E.g., if the process value is “Uncertain”, the “LevelAlarm” Condition is also
* questionable. If more than one variable is represented by a given condition or if the condition
* is from an underlining system and no direct mapping to a variable is available, it is up to the
* application to determine what quality is displayed as part of the condition.
*/
/**
* set the condition quality
* @method setQuality
* @param quality {StatusCode}
*/
ConditionSnapshot.prototype.setQuality = function(quality) {
const self = this;
assert(quality instanceof StatusCode);
assert(quality.hasOwnProperty("value") || "quality must be a StatusCode");
self._set_var("quality", DataType.StatusCode, quality);
/*
* OPCUA Spec 1.0.3 - Part 9:
* Comment, severity and quality are important elements of Conditions and any change
* to them will cause Event Notifications.
*
*/
self._need_event_raise = true;
};
/**
* @method getQuality
* @return {StatusCode}
*/
ConditionSnapshot.prototype.getQuality = function() {
const self = this;
return self._get_var("quality", DataType.StatusCode);
};
/*
* as per spec 1.0.3 - Part 9
* The Severity of a Condition is inherited from the base Event model defined in Part 5. It
* indicates the urgency of the Condition and is also commonly called ‘priority’, especially in
* relation to Alarms in the ProcessConditionClass.
*
* as per spec 1.0.3 - PArt 5
* Severity is an indication of the urgency of the Event. This is also commonly called “priority”.
* Values will range from 1 to 1 000, with 1 being the lowest severity and 1 000 being the highest.
* Typically, a severity of 1 would indicate an Event which is informational in nature, while a value
* of 1 000 would indicate an Event of catastrophic nature, which could potentially result in severe
* financial loss or loss of life.
* It is expected that very few Server implementations will support 1 000 distinct severity levels.
* Therefore, Server developers are responsible for distributing their severity levels across the
* 1 to 1 000 range in such a manner that clients can assume a linear distribution. For example, a
* client wishing to present five severity levels to a user should be able to do the following
* mapping:
* Client Severity OPC Severity
* HIGH 801 – 1 000
* MEDIUM HIGH 601 – 800
* MEDIUM 401 – 600
* MEDIUM LOW 201 – 400
* LOW 1 – 200
* In many cases a strict linear mapping of underlying source severities to the OPC Severity range
* is not appropriate. The Server developer will instead intelligently map the underlying source
* severities to the 1 to 1 000 OPC Severity range in some other fashion. In particular, it is
* recommended that Server developers map Events of high urgency into the OPC severity range
* of 667 to 1 000, Events of medium urgency into the OPC severity range of 334 to 666 and
* Events of low urgency into OPC severities of 1 to 333.
*/
/**
* @method setSeverity
* @param severity {UInt16}
*/
ConditionSnapshot.prototype.setSeverity = function(severity) {
const self = this;
assert(_.isFinite(severity), "expecting a UInt16");
// record automatically last severity
const lastSeverity = self.getSeverity();
self.setLastSeverity(lastSeverity);
self._set_var("severity", DataType.UInt16, severity);
/*
* OPCUA Spec 1.0.3 - Part 9:
* Comment, severity and quality are important elements of Conditions and any change
* to them will cause Event Notifications.
*
*/
self._need_event_raise = true;
};
/**
* @method getSeverity
* @return {UInt16}
*/
ConditionSnapshot.prototype.getSeverity = function() {
const self = this;
assert(self.condition.getEnabledState(), "condition must be enabled");
const value = self._get_var("severity", DataType.UInt16);
return +value;
};
/*
* as per spec 1.0.3 - part 9:
* LastSeverity provides the previous severity of the ConditionBranch. Initially this Variable
* contains a zero value; it will return a value only after a severity change. The new severity is
* supplied via the Severity Property which is inherited from the BaseEventType.
*
*/
/**
* @method setLastSeverity
* @param severity {UInt16}
*/
ConditionSnapshot.prototype.setLastSeverity = function(severity) {
const self = this;
severity = +severity;
return self._set_var("lastSeverity", DataType.UInt16, severity);
};
/**
* @method getLastSeverity
* @return {UInt16}
*/
ConditionSnapshot.prototype.getLastSeverity = function() {
const self = this;
const value = self._get_var("lastSeverity", DataType.UInt16);
return +value;
};
/**
* setReceiveTime
*
* (as per OPCUA 1.0.3 part 5)
*
* ReceiveTime provides the time the OPC UA Server received the Event from the underlying
* device of another Server.
*
* ReceiveTime is analogous to ServerTimestamp defined in Part 4, i.e.
* in the case where the OPC UA Server gets an Event from another OPC UA Server, each Server
* applies its own ReceiveTime. That implies that a Client may get the same Event, having the
* same EventId, from different Servers having different values of the ReceiveTime.
*
* The ReceiveTime shall always be returned as value and the Server is not allowed to return a
* StatusCode for the ReceiveTime indicating an error.
*
* @method setReceiveTime
* @param time {Date} : UTCTime
*/
ConditionSnapshot.prototype.setReceiveTime = function(time) {
assert(time instanceof Date);
const self = this;
return self._set_var("receiveTime", DataType.DateTime, time);
};
/**
* (as per OPCUA 1.0.3 part 5)
* Time provides the time the Event occurred. This value is set as close to the event generator as
* possible. It often comes from the underlying system or device. Once set, intermediate OPC UA
* Servers shall not alter the value.
*
* @method setTime
* @param time {Date}
*/
ConditionSnapshot.prototype.setTime = function(time) {
assert(time instanceof Date);
const self = this;
return self._set_var("time", DataType.DateTime, time);
};
/**
* LocalTime is a structure containing the Offset and the DaylightSavingInOffset flag. The Offset
* specifies the time difference (in minutes) between the Time Property and the time at the location
* in which the event was issued. If DaylightSavingInOffset is TRUE, then Standard/Daylight
* savings time (DST) at the originating location is in effect and Offset includes the DST c orrection.
* If FALSE then the Offset does not include DST correction and DST may or may not have been
* in effect.
* @method setLocalTime
* @param localTime {TimeZone}
*/
ConditionSnapshot.prototype.setLocalTime = function(localTime) {
assert(localTime instanceof TimeZone);
const self = this;
return self._set_var("localTime", DataType.ExtensionObject, new TimeZone(localTime));
};
// read only !
ConditionSnapshot.prototype.getSourceName = function() {
return this._get_var("sourceName", DataType.LocalizedText);
};
/**
* @method getSourceNode
* return {NodeId}
*/
ConditionSnapshot.prototype.getSourceNode = function() {
return this._get_var("sourceNode", DataType.NodeId);
};
/**
* @method getEventType
* return {NodeId}
*/
ConditionSnapshot.prototype.getEventType = function() {
return this._get_var("eventType", DataType.NodeId);
};
/**
* @method getMessage
* return {LocalizedText}
*/
ConditionSnapshot.prototype.getMessage = function() {
return this._get_var("message", DataType.LocalizedText);
};
ConditionSnapshot.prototype.isCurrentBranch = function() {
return this._get_var("branchId") === NodeId.NullNodeId;
};
/**
* @class ConditionSnapshot
* @param varName
* @param value
* @private
*/
ConditionSnapshot.prototype._set_twoStateVariable = function(varName, value) {
value = !!value;
const self = this;
const hrKey = ConditionSnapshot.normalizeName(varName);
const idKey = ConditionSnapshot.normalizeName(varName) + ".id";
const variant = new Variant({ dataType: DataType.Boolean, value: value });
self._map[idKey] = variant;
// also change varName with human readable text
const twoStateNode = self._node_index[hrKey];
if (!twoStateNode) {
throw new Error("Cannot find twoState Varaible with name " + varName);
}
if (!(twoStateNode instanceof UATwoStateVariable)) {
throw new Error("Cannot find twoState Varaible with name " + varName + " " + twoStateNode);
}
const txt = value ? twoStateNode._trueState : twoStateNode._falseState;
const hrValue = new Variant({
dataType: DataType.LocalizedText,
value: coerceLocalizedText(txt)
});
self._map[hrKey] = hrValue;
const node = self._node_index[idKey];
// also change ConditionNode if we are on currentBranch
if (self.isCurrentBranch()) {
assert(twoStateNode instanceof UATwoStateVariable);
twoStateNode.setValue(value);
//xx console.log("Is current branch", twoStateNode.toString(),variant.toString());
//xx console.log(" = ",twoStateNode.getValue());
}
self.emit("value_changed", node, variant);
};
ConditionSnapshot.prototype._get_twoStateVariable = function(varName) {
const self = this;
const key = ConditionSnapshot.normalizeName(varName) + ".id";
const variant = self._map[key];
// istanbul ignore next
if (!variant) {
throw new Error("Cannot find TwoStateVariable with name " + varName);
}
return variant.value;
};
exports.ConditionSnapshot = ConditionSnapshot;
/**
* @class BaseEventType
* @class UAObject
* @constructor
*/
function BaseEventType() {}
util.inherits(BaseEventType, UAObject);
/**
* @method setSourceName
* @param name
*/
BaseEventType.prototype.setSourceName = function(name) {
assert(typeof name === "string");
const self = this;
self.sourceName.setValueFromSource(
new Variant({
dataType: DataType.String,
value: name
})
);
};
/**
* @method setSourceNode
* @param node {NodeId|UAObject}
*/
BaseEventType.prototype.setSourceNode = function(node) {
const self = this;
self.sourceNode.setValueFromSource(
new Variant({
dataType: DataType.NodeId,
value: node.nodeId ? node.nodeId : node
})
);
};
/**
* @class UAConditionBase
* @constructor
* @extends BaseEventType
*/
function UAConditionBase() {}
util.inherits(UAConditionBase, BaseEventType);
UAConditionBase.prototype.nodeClass = NodeClass.Object;
UAConditionBase.typeDefinition = resolveNodeId("ConditionType");
/**
* @method initialize
* @private
*/
UAConditionBase.prototype.initialize = function() {
const self = this;
self._branches = {};
};
/**
* @method post_initialize
* @private
*/
UAConditionBase.prototype.post_initialize = function() {
const self = this;
assert(!self._branch0);
self._branch0 = new ConditionSnapshot(self, NodeId.NullNodeId);
// the condition OPCUA object alway reflects the default branch states
// so we set a mechanism that automatically keeps self in sync
// with the default branch.
// the implication of this convention is that interacting with the condition variable
// shall be made by using branch0, any value change made
// using the standard setValueFromSource mechanism will not be work properly.
self._branch0.on("value_changed", function(node, variant) {
assert(node instanceof UAVariable);
node.setValueFromSource(variant);
});
};
/**
* @method getBranchCount
* @return {Number}
*/
UAConditionBase.prototype.getBranchCount = function() {
const self = this;
return Object.keys(self._branches).length;
};
UAConditionBase.prototype.getBranches = function() {
const self = this;
return Object.keys(self._branches).map(function(x) {
return self._branches[x];
});
};
UAConditionBase.prototype.getBranchIds = function() {
const self = this;
return self.getBranches().map(function(b) {
return b.getBranchId();
});
};
const ec = require("node-opcua-basic-types");
const randomGuid = ec.randomGuid;
const makeNodeId = require("node-opcua-nodeid").makeNodeId;
function _create_new_branch_id() {
return makeNodeId(randomGuid(), 1);
}
/**
* @method createBranch
* @return {ConditionSnapshot}
*/
UAConditionBase.prototype.createBranch = function() {
const self = this;
const branchId = _create_new_branch_id();
const snapshot = new ConditionSnapshot(self, branchId);
self._branches[branchId.toString()] = snapshot;
return snapshot;
};
/**
* @method deleteBranch
* @param branch {ConditionSnapshot}
*/
UAConditionBase.prototype.deleteBranch = function(branch) {
const self = this;
const key = branch.getBranchId().toString();
assert(branch.getBranchId() !== NodeId.NullNodeId, "cannot delete branch zero");
assert(self._branches.hasOwnProperty(key));
delete self._branches[key];
self.emit("branch_deleted", key);
};
const minDate = new Date(1600, 1, 1);
function prepare_date(sourceTimestamp) {
if (!sourceTimestamp || !sourceTimestamp.value) {
return minDate;
}
assert(sourceTimestamp.value instanceof Date);
return sourceTimestamp;
}
function _update_sourceTimestamp(dataValue /*, indexRange*/) {
const self = this;
//xx console.log("_update_sourceTimestamp = "+self.nodeId.toString().cyan+ " " + self.browseName.toString(), self.sourceTimestamp.nodeId.toString().cyan + " " + dataValue.sourceTimestamp);
self.sourceTimestamp.setValueFromSource({
dataType: DataType.DateTime,
value: dataValue.sourceTimestamp
});
}
const makeAccessLevel = require("node-opcua-data-model").makeAccessLevel;
function _install_condition_variable_type(node) {
assert(node instanceof BaseNode);
// from spec 1.03 : 5.3 condition variables
// However, a change in their value is considered important and supposed to trigger
// an Event Notification. These information elements are called ConditionVariables.
if (node.sourceTimestamp) {
node.sourceTimestamp.accessLevel = makeAccessLevel("CurrentRead");
} else {
console.warn("cannot find node.sourceTimestamp", node.browseName.toString());
}
node.accessLevel = makeAccessLevel("CurrentRead");
// from spec 1.03 : 5.3 condition variables
// a condition VariableType has a sourceTimeStamp exposed property
// SourceTimestamp indicates the time of the last change of the Value of this ConditionVariable.
// It shall be the same time that would be returned from the Read Service inside the DataValue
// structure for the ConditionVariable Value Attribute.
assert(node.typeDefinitionObj.browseName.toString() === "ConditionVariableType");
assert(node.sourceTimestamp.browseName.toString() === "SourceTimestamp");
node.on("value_changed", _update_sourceTimestamp);
}
/**
* @method getEnabledState
* @return {Boolean}
*/
UAConditionBase.prototype.getEnabledState = function() {
const conditionNode = this;
return conditionNode.enabledState.getValue();
};
/**
* @method getEnabledStateAsString
* @return {String}
*/
UAConditionBase.prototype.getEnabledStateAsString = function() {
const conditionNode = this;
return conditionNode.enabledState.getValueAsString();
};
UAConditionBase.prototype.evaluateConditionsAfterEnabled = function() {
assert(this.getEnabledState() === true);
throw new Error("Unimplemented , please override");
};
/**
* @method _setEnabledState
* @param requestedEnabledState {Boolean}
* @return {StatusCode} StatusCodes.Good if successful or BadConditionAlreadyEnabled/BadConditionAlreadyDisabled
* @private
*/
UAConditionBase.prototype._setEnabledState = function(requestedEnabledState) {
const conditionNode = this;
assert(_.isBoolean(requestedEnabledState));
const enabledState = conditionNode.getEnabledState();
if (enabledState && requestedEnabledState) {
return StatusCodes.BadConditionAlreadyEnabled;
}
if (!enabledState && !requestedEnabledState) {
return StatusCodes.BadConditionAlreadyDisabled;
}
conditionNode._branch0.setEnabledState(requestedEnabledState);
//conditionNode.enabledState.setValue(requestedEnabledState);
//xx assert(conditionNode.enabledState.id.readValue().value.value === requestedEnabledState,"sanity check 1");
//xx assert(conditionNode.currentBranch().getEnabledState() === requestedEnabledState,"sanity check 2");
if (!requestedEnabledState) {
// as per Spec 1.0.3 part 9:
//* When the Condition instance enters the Disabled state, the Retain Property of this
// Condition shall be set to FALSE by the Server to indicate to the Client that the
// Condition instance is currently not of interest to Clients.
// TODO : shall we really set retain to false or artificially expose the retain false as false
// whist enabled state is false ?
conditionNode._previousRetainFlag = conditionNode.currentBranch().getRetain();
conditionNode.currentBranch().setRetain(false);
// install the mechanism by which all condition values will be return
// as Null | BadConditionDisabled;
const statusCode = StatusCodes.BadConditionDisabled;
// a notification must be send
conditionNode.raiseConditionEvent(conditionNode.currentBranch(), true);
} else {
//* When the Condition instance enters the enabled state, the Condition shall be
// evaluated and all of its Properties updated to reflect the current values. If this
// evaluation causes the Retain Property to transition to TRUE for any ConditionBranch,
// then an Event Notification shall be generated for that ConditionBranch.
conditionNode.evaluateConditionsAfterEnabled();
// todo evaluate branches
// conditionNode.evaluateBranches();
// restore retain flag
if (conditionNode.hasOwnProperty("_previousRetainFlag")) {
conditionNode.currentBranch().setRetain(conditionNode._previousRetainFlag);
}
// todo send notification for branches with retain = true
let nb_condition_resent = 0;
if (conditionNode.currentBranch().getRetain()) {
nb_condition_resent += conditionNode._resend_conditionEvents();
}
if (nb_condition_resent === 0) {
// a notification must be send
conditionNode.raiseConditionEvent(conditionNode.currentBranch(), true);
}
}
return StatusCodes.Good;
};
/**
*
* @method setEnabledState
* @param requestedEnabledState {Boolean}
* @private
*/
UAConditionBase.prototype.setEnabledState = function(requestedEnabledState) {