-
-
Notifications
You must be signed in to change notification settings - Fork 478
/
ua_variable.js
1816 lines (1514 loc) · 63.1 KB
/
ua_variable.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
*/
const assert = require("node-opcua-assert").assert;
const util = require("util");
const _ = require("underscore");
const utils = require("node-opcua-utils");
const NodeClass = require("node-opcua-data-model").NodeClass;
const AttributeIds = require("node-opcua-data-model").AttributeIds;
const extractRange = require("node-opcua-data-value").extractRange;
const is_valid_dataEncoding = require("node-opcua-data-model").is_valid_dataEncoding;
const is_dataEncoding = require("node-opcua-data-model").is_dataEncoding;
const AccessLevelFlag = require("node-opcua-data-model").AccessLevelFlag;
const makeAccessLevel = require("node-opcua-data-model").makeAccessLevel;
const NodeId = require("node-opcua-nodeid").NodeId;
const DataValue = require("node-opcua-data-value").DataValue;
const sameDataValue = require("node-opcua-data-value").sameDataValue;
const Variant = require("node-opcua-variant").Variant;
const DataType = require("node-opcua-variant").DataType;
const VariantArrayType = require("node-opcua-variant").VariantArrayType;
const NumericRange = require("node-opcua-numeric-range").NumericRange;
const StatusCodes = require("node-opcua-status-code").StatusCodes;
const write_service = require("node-opcua-service-write");
const WriteValue = write_service.WriteValue;
const getCurrentClock = require("node-opcua-date-time").getCurrentClock;
const coerceClock = require("node-opcua-date-time").coerceClock;
const findBuiltInType = require("node-opcua-factory").findBuiltInType;
const BaseNode = require("./base_node").BaseNode;
const SessionContext = require("./session_context").SessionContext;
const debug = require("node-opcua-debug");
const debugLog = debug.make_debugLog(__filename);
const doDebug = debug.checkDebugFlag(__filename);
function isGoodish(statusCode) {
return statusCode.value < 0x10000000;
}
function adjust_accessLevel(accessLevel) {
accessLevel = utils.isNullOrUndefined(accessLevel) ? "CurrentRead | CurrentWrite" : accessLevel;
accessLevel = makeAccessLevel(accessLevel);
assert(_.isFinite(accessLevel.value));
return accessLevel;
}
function adjust_userAccessLevel(userAccessLevel, accessLevel) {
userAccessLevel = utils.isNullOrUndefined(userAccessLevel) ? "CurrentRead | CurrentWrite" : userAccessLevel;
userAccessLevel = makeAccessLevel(userAccessLevel);
accessLevel = utils.isNullOrUndefined(accessLevel) ? "CurrentRead | CurrentWrite" : accessLevel;
accessLevel = makeAccessLevel(accessLevel);
return makeAccessLevel(accessLevel.value & userAccessLevel.value);
}
function adjust_samplingInterval(minimumSamplingInterval) {
assert(_.isFinite(minimumSamplingInterval));
return minimumSamplingInterval;
}
function is_Variant(v) {
return v instanceof Variant;
}
function is_StatusCode(v) {
return v && v.constructor &&
(
v.constructor.name === "ConstantStatusCode" ||
v.constructor.name === "StatusCode" ||
v.constructor.name === "ModifiableStatusCode"
);
}
function is_Variant_or_StatusCode(v) {
if (is_Variant(v)) {
// /@@assert(v.isValid());
}
return is_Variant(v) || is_StatusCode(v);
}
const UADataType = require("./ua_data_type").UADataType;
function _dataType_toUADataType(addressSpace, dataType) {
assert(addressSpace);
assert(dataType && dataType.hasOwnProperty("key"));
const dataTypeNode = addressSpace.findDataType(dataType.key);
/* istanbul ignore next */
if (!dataTypeNode) {
throw new Error(" Cannot find DataType " + dataType.key + " in address Space");
}
return dataTypeNode;
}
/*=
*
* @param addressSpace
* @param dataTypeNodeId : the nodeId matching the dataType of the destination variable.
* @param variantDataType: the dataType of the variant to write to the destination variable
* @param nodeId
* @return {boolean} true if the variant dataType is compatible with the Variable DataType
*/
function validateDataType(addressSpace, dataTypeNodeId, variantDataType, nodeId) {
if (variantDataType === DataType.ExtensionObject) {
return true;
}
let builtInType, builtInUADataType;
const destUADataType = addressSpace.findNode(dataTypeNodeId);
assert(destUADataType instanceof UADataType);
if (destUADataType.isAbstract || destUADataType.nodeId.namespace !== 0) {
builtInUADataType = destUADataType;
} else {
builtInType = findBuiltInType(destUADataType.browseName).name;
builtInUADataType = addressSpace.findDataType(builtInType);
}
assert(builtInUADataType instanceof UADataType);
const enumerationUADataType = addressSpace.findDataType("Enumeration");
if (destUADataType.isSupertypeOf(enumerationUADataType)) {
return true;
}
// The value supplied for the attribute is not of the same type as the value.
const variantUADataType = _dataType_toUADataType(addressSpace, variantDataType);
assert(variantUADataType instanceof UADataType);
const dest_isSuperTypeOf_variant = variantUADataType.isSupertypeOf(builtInUADataType);
/* istanbul ignore next */
if (doDebug) {
if (dest_isSuperTypeOf_variant) {
/* istanbul ignore next*/
console.log(" ---------- Type match !!! ".green, " on ", nodeId.toString());
} else {
/* istanbul ignore next*/
console.log(" ---------- Type mismatch ".red, " on ", nodeId.toString());
}
console.log(" Variable data Type is = ".cyan, destUADataType.browseName.toString());
console.log(" which matches basic Type = ".cyan, builtInUADataType.browseName.toString());
console.log(" Actual dataType = ".yellow, variantUADataType.browseName.toString());
}
return (dest_isSuperTypeOf_variant);
}
const sameVariant = require("node-opcua-variant").sameVariant;
/**
* A OPCUA Variable Node
*
* @class UAVariable
* @constructor
* @extends BaseNode
* @param options {Object}
* @param options.value
* @param options.browseName {string}
* @param options.dataType {NodeId|String}
* @param options.valueRank {Int32}
* @param options.arrayDimensions {null|Array<Integer>}
* @param options.accessLevel {AccessLevel}
* @param options.userAccessLevel {AccessLevel}
* @param [options.minimumSamplingInterval = -1]
* @param [options.historizing = false] {Boolean}
* @param [options.permissions]
* @param options.parentNodeId {NodeId}
*
* The AccessLevel Attribute is used to indicate how the Value of a Variable can be accessed (read/write) and if it
* contains current and/or historic data. The AccessLevel does not take any user access rights into account,
* i.e. although the Variable is writable this may be restricted to a certain user / user group.
* The AccessLevel is an 8-bit unsigned integer with the structure defined in the following table:
*
* Field Bit Description
* CurrentRead 0 Indicates if the current value is readable
* (0 means not readable, 1 means readable).
* CurrentWrite 1 Indicates if the current value is writable
* (0 means not writable, 1 means writable).
* HistoryRead 2 Indicates if the history of the value is readable
* (0 means not readable, 1 means readable).
* HistoryWrite 3 Indicates if the history of the value is writable (0 means not writable, 1 means writable).
* SemanticChange 4 Indicates if the Variable used as Property generates SemanticChangeEvents (see 9.31).
* Reserved 5:7 Reserved for future use. Shall always be zero.
*
* The first two bits also indicate if a current value of this Variable is available and the second two bits
* indicates if the history of the Variable is available via the OPC UA server.
*
*/
function UAVariable(options) {
const self = this;
BaseNode.apply(this, arguments);
// assert(self.typeDefinition.value === self.resolveNodeId("VariableTypeNode").value);
/**
* @property dataType
* @type {NodeId}
*/
self.dataType = self.resolveNodeId(options.dataType); // DataType (NodeId)
assert(self.dataType instanceof NodeId);
/**
* @property valueRank
* @type {number} UInt32
* This Attribute indicates whether the Value Attribute of the Variable is an array and how many dimensions
* the array has.
* It may have the following values:
* n > 1: the Value is an array with the specified number of dimensions.
* OneDimension (1): The value is an array with one dimension.
* OneOrMoreDimensions (0): The value is an array with one or more dimensions.
* Scalar (?1): The value is not an array.
* Any (?2): The value can be a scalar or an array with any number of dimensions.
* ScalarOrOneDimension (?3): The value can be a scalar or a one dimensional array.
* NOTE All DataTypes are considered to be scalar, even if they have array-like semantics
* like ByteString and String.
*/
self.valueRank = options.valueRank || 0; // UInt32
assert(typeof self.valueRank === "number");
/**
* This Attribute specifies the length of each dimension for an array value. T
* @property arrayDimensions
* @type {number[]} UInt32
* The Attribute is intended to describe the capability of the Variable, not the current size.
* The number of elements shall be equal to the value of the ValueRank Attribute. Shall be null
* if ValueRank ? 0.
* A value of 0 for an individual dimension indicates that the dimension has a variable length.
* For example, if a Variable is defined by the following C array:
* Int32 myArray[346];
* then this Variables DataType would point to an Int32, the Variable�s ValueRank has the
* value 1 and the ArrayDimensions is an array with one entry having the value 346.
* Note that the maximum length of an array transferred on the wire is 2147483647 (max Int32)
* and a multidimentional array is encoded as a one dimensional array.
*/
self.arrayDimensions = options.arrayDimensions || null;
assert(_.isNull(self.arrayDimensions) || _.isArray(self.arrayDimensions));
/**
* @property accessLevel
* @type {number}
* The AccessLevel Attribute is used to indicate how the Value of a Variable can be accessed
* (read/write) and if it contains current and/or historic data. The AccessLevel does not take
* any user access rights into account, i.e. although the Variable is writable this may be
* restricted to a certain user / user group. The AccessLevelType is defined in 8.57.
*/
self.accessLevel = adjust_accessLevel(options.accessLevel);
/**
* @property userAccessLevel
* @type {number}
* The UserAccessLevel Attribute is used to indicate how the Value of a Variable can be accessed
* (read/write) and if it contains current or historic data taking user access rights into account.
* The AccessLevelType is defined in 8.57.
*/
self.userAccessLevel = adjust_userAccessLevel(options.userAccessLevel, options.accessLevel);
/**
* The MinimumSamplingInterval Attribute indicates how 'current' the Value of the Variable will
* be kept.
* @property minimumSamplingInterval
* @type {number} [Optional]
* It specifies (in milliseconds) how fast the Server can reasonably sample the value
* for changes (see Part 4 for a detailed description of sampling interval).
* A MinimumSamplingInterval of 0 indicates that the Server is to monitor the item continuously.
* A MinimumSamplingInterval of -1 means indeterminate.
*/
self.minimumSamplingInterval = adjust_samplingInterval(options.minimumSamplingInterval);
self.parentNodeId = options.parentNodeId;
/**
* The Historizing Attribute indicates whether the Server is actively collecting data for the
* history of the Variable.
* @property historizing
* @type {Boolean}
* This differs from the AccessLevel Attribute which identifies if the
* Variable has any historical data. A value of TRUE indicates that the Server is actively
* collecting data. A value of FALSE indicates the Server is not actively collecting data.
* Default value is FALSE.
*/
self.historizing = !!options.historizing; // coerced to boolean
self._dataValue = new DataValue({statusCode: StatusCodes.BadWaitingForInitialData, value: {}});
if (options.value) {
self.bindVariable(options.value);
}
if (options.permissions) {
self.setPermissions(options.permissions);
}
this.setMaxListeners(5000);
self.semantic_version = 0;
self.permission = null;
}
util.inherits(UAVariable, BaseNode);
UAVariable.prototype.nodeClass = NodeClass.Variable;
/**
*
* @method isReadable
* @param context {SesionContext}
* @return {boolean}
*/
UAVariable.prototype.isReadable = function (context) {
assert(context instanceof SessionContext);
return this.accessLevel.has("CurrentRead");
};
/**
*
* @method isUserReadable
* @param context {SesionContext}
* @return {boolean}
*/
UAVariable.prototype.isUserReadable = function (context) {
const self = this;
assert(context instanceof SessionContext);
if (context.checkPermission) {
assert(context.checkPermission instanceof Function);
return context.checkPermission(self, "CurrentRead");
}
return this.userAccessLevel.has("CurrentRead");
};
/**
* @method isWritable
*
* @param context {SessionContext}
* @return {boolean}
*/
UAVariable.prototype.isWritable = function (context) {
assert(context instanceof SessionContext);
return this.accessLevel.has("CurrentWrite");
};
/**
*
* @method isUserWritable
* @param context {SessionContext}
* @return {boolean}
*/
UAVariable.prototype.isUserWritable = function (context) {
const self = this;
assert(context instanceof SessionContext);
if (context.checkPermission) {
assert(context.checkPermission instanceof Function);
return context.checkPermission(self, "CurrentWrite");
}
return this.userAccessLevel.has("CurrentWrite");
};
/**
*
* @method readValue
* @param [context] {SessionContext}
* @param [indexRange] {NumericRange|null}
* @param [dataEncoding] {String}
* @return {DataValue}
*
*
* from OPC.UA.Spec 1.02 part 4
* 5.10.2.4 StatusCodes
* Table 51 defines values for the operation level statusCode contained in the DataValue structure of
* each values element. Common StatusCodes are defined in Table 166.
*
* Table 51 Read Operation Level Result Codes
*
* Symbolic Id Description
*
* BadNodeIdInvalid The syntax of the node id is not valid.
* BadNodeIdUnknown The node id refers to a node that does not exist in the server address space.
* BadAttributeIdInvalid Bad_AttributeIdInvalid The attribute is not supported for the specified node.
* BadIndexRangeInvalid The syntax of the index range parameter is invalid.
* BadIndexRangeNoData No data exists within the range of indexes specified.
* BadDataEncodingInvalid The data encoding is invalid.
* This result is used if no dataEncoding can be applied because an Attribute other than
* Value was requested or the DataType of the Value Attribute is not a subtype of the
* Structure DataType.
* BadDataEncodingUnsupported The server does not support the requested data encoding for the node.
* This result is used if a dataEncoding can be applied but the passed data encoding is not
* known to the Server.
* BadNotReadable The access level does not allow reading or subscribing to the Node.
* BadUserAccessDenied User does not have permission to perform the requested operation. (table 165)
*/
UAVariable.prototype.readValue = function (context, indexRange, dataEncoding) {
if (!context) {
context = SessionContext.defaultContext;
}
const self = this;
if (!self.isReadable(context)) {
return new DataValue({statusCode: StatusCodes.BadNotReadable});
}
if (!self.isUserReadable(context)) {
return new DataValue({statusCode: StatusCodes.BadUserAccessDenied});
}
if (!is_valid_dataEncoding(dataEncoding)) {
return new DataValue({statusCode: StatusCodes.BadDataEncodingInvalid});
}
if (self._timestamped_get_func) {
assert(self._timestamped_get_func.length === 0);
self._dataValue = self._timestamped_get_func();
}
let dataValue = self._dataValue;
if (isGoodish(dataValue.statusCode)) {
dataValue = extractRange(dataValue, indexRange);
}
/* istanbul ignore next */
if (dataValue.statusCode.equals(StatusCodes.BadWaitingForInitialData)) {
debugLog(" Warning: UAVariable#readValue ".red + self.browseName.toString().cyan + " (" + self.nodeId.toString().yellow + ") exists but dataValue has not been defined");
}
return dataValue;
};
UAVariable.prototype._getEnumValues = function () {
const self = this;
// DataType must be one of Enumeration
const dataTypeNode = self.addressSpace.findDataType(self.dataType);
const enumerationNode = self.addressSpace.findDataType("Enumeration");
assert(dataTypeNode.isSupertypeOf(enumerationNode));
return dataTypeNode._getDefinition();
};
UAVariable.prototype.readEnumValue = function readEnumValue() {
const self = this;
const indexes = self._getEnumValues();
const value = self.readValue().value.value;
return {value: value, name: indexes.valueIndex[value].name};
};
/***
* @method writeEnumValue
* @param value {String|Number}
*/
UAVariable.prototype.writeEnumValue = function writeEnumValue(value) {
const self = this;
const indexes = self._getEnumValues();
if (_.isString(value)) {
if (!indexes.nameIndex.hasOwnProperty(value)) {
throw new Error("UAVariable#writeEnumValue: cannot find value " + value);
}
const valueIndex = indexes.nameIndex[value].value;
value = valueIndex;
}
if (_.isFinite(value)) {
if (!indexes.valueIndex[value]) {
throw new Error("UAVariable#writeEnumValue : value out of range", value);
}
self.setValueFromSource({dataType: DataType.Int32, value: value});
return StatusCodes.Good;
} else {
throw new Error("UAVariable#writeEnumValue: value type mismatch");
}
};
UAVariable.prototype._readDataType = function () {
assert(this.dataType instanceof NodeId);
const options = {
value: {dataType: DataType.NodeId, value: this.dataType},
statusCode: StatusCodes.Good
};
return new DataValue(options);
};
UAVariable.prototype._readValueRank = function () {
assert(typeof this.valueRank === "number");
const options = {
value: {dataType: DataType.Int32, value: this.valueRank},
statusCode: StatusCodes.Good
};
return new DataValue(options);
};
UAVariable.prototype._readArrayDimensions = function () {
assert(_.isArray(this.arrayDimensions) || this.arrayDimensions === null);
const options = {
value: {dataType: DataType.UInt32, arrayType: VariantArrayType.Array, value: this.arrayDimensions},
statusCode: StatusCodes.Good
};
return new DataValue(options);
};
UAVariable.prototype._readAccessLevel = function (context) {
assert(context instanceof SessionContext);
const options = {
value: {dataType: DataType.Byte, value: AccessLevelFlag.toByte(this.accessLevel)},
statusCode: StatusCodes.Good
};
return new DataValue(options);
};
UAVariable.prototype._readUserAccessLevel = function (context) {
assert(context instanceof SessionContext);
const options = {
value: {dataType: DataType.Byte, value: AccessLevelFlag.toByte(this.userAccessLevel)},
statusCode: StatusCodes.Good
};
return new DataValue(options);
};
UAVariable.prototype._readMinimumSamplingInterval = function () {
// expect a Duration => Double
const options = {};
if (this.minimumSamplingInterval === undefined) {
options.statusCode = StatusCodes.BadAttributeIdInvalid;
} else {
options.value = {dataType: DataType.Double, value: this.minimumSamplingInterval};
options.statusCode = StatusCodes.Good;
}
return new DataValue(options);
};
UAVariable.prototype._readHistorizing = function () {
assert(typeof(this.historizing) === "boolean");
const options = {
value: {dataType: DataType.Boolean, value: !!this.historizing},
statusCode: StatusCodes.Good
};
return new DataValue(options);
};
/**
* @method readAttribute
* @param context {SessionContext}
* @param attributeId {AttributeIds} the attributeId to read
* @param indexRange {NumericRange | null}
* @param dataEncoding {String}
* @return {DataValue}
*/
UAVariable.prototype.readAttribute = function (context, attributeId, indexRange, dataEncoding) {
if (!context) {
context = SessionContext.defaultContext;
}
assert(context instanceof SessionContext);
const options = {};
if (attributeId !== AttributeIds.Value) {
if (indexRange && indexRange.isDefined()) {
options.statusCode = StatusCodes.BadIndexRangeNoData;
return new DataValue(options);
}
if (is_dataEncoding(dataEncoding)) {
options.statusCode = StatusCodes.BadDataEncodingInvalid;
return new DataValue(options);
}
}
switch (attributeId) {
case AttributeIds.Value:
return this.readValue(context, indexRange, dataEncoding);
case AttributeIds.DataType:
return this._readDataType();
case AttributeIds.ValueRank:
return this._readValueRank();
case AttributeIds.ArrayDimensions:
return this._readArrayDimensions();
case AttributeIds.AccessLevel:
return this._readAccessLevel(context);
case AttributeIds.UserAccessLevel:
return this._readUserAccessLevel(context);
case AttributeIds.MinimumSamplingInterval:
return this._readMinimumSamplingInterval();
case AttributeIds.Historizing:
return this._readHistorizing();
default:
return BaseNode.prototype.readAttribute.call(this, context, attributeId);
}
};
UAVariable.prototype._validate_DataType = function (variantDataType) {
return validateDataType(this.addressSpace, this.dataType, variantDataType, this.nodeId);
};
function check_valid_array(dataType, array) {
if (_.isArray(array)) {
return true;
}
switch (dataType) {
case DataType.Double:
return array instanceof Float64Array;
case DataType.Float:
return array instanceof Float32Array;
case DataType.Int32:
return array instanceof Int32Array;
case DataType.Int16:
return array instanceof Int16Array;
case DataType.SByte:
return array instanceof Int8Array;
case DataType.UInt32:
return array instanceof Uint32Array;
case DataType.UInt16:
return array instanceof Uint16Array;
case DataType.Byte:
return array instanceof Uint8Array || array instanceof Buffer;
}
return false;
}
/**
* setValueFromSource is used to let the device sets the variable values
* this method also records the current time as sourceTimestamp and serverTimestamp.
* the method broadcasts an "value_changed" event
* @method setValueFromSource
* @param variant {Variant}
* @param [statusCode {StatusCode} = StatusCodes.Good]
* @param [sourceTimestamp= Now]
*/
UAVariable.prototype.setValueFromSource = function (variant, statusCode, sourceTimestamp) {
const self = this;
// istanbul ignore next
if (variant.hasOwnProperty("value")) {
if (!variant.dataType) {
throw new Error("Variant must provide a valid dataType" + variant.toString());
}
}
// if (variant.hasOwnProperty("value")) {
// if (variant.dataType === DataType.UInt32) {
// if (!_.isFinite(variant.value)) {
// throw new Error("Expecting an number");
// }
// }
// }
variant = Variant.coerce(variant);
const now = coerceClock(sourceTimestamp, 0);
const dataValue = new DataValue({
sourceTimestamp: now.timestamp,
sourcePicoseconds: now.picoseconds,
serverTimestamp: now.timestamp,
serverPicoseconds: now.picoseconds,
statusCode: statusCode || StatusCodes.Good
});
dataValue.value = variant;
self._internal_set_dataValue(dataValue, null);
};
function _apply_default_timestamps(dataValue) {
const now = getCurrentClock();
assert(dataValue instanceof DataValue);
if (!dataValue.sourceTimestamp) {
dataValue.sourceTimestamp = now.timestamp;
dataValue.sourcePicoseconds = now.picoseconds;
}
if (!dataValue.serverTimestamp) {
dataValue.serverTimestamp = now.timestamp;
dataValue.serverPicoseconds = now.picoseconds;
}
}
/**
* @method isValueInRange
* note:
* this method is overridden in address-space-data-access
* @return {StatusCode}
*/
UAVariable.prototype.isValueInRange = function () {
return StatusCodes.Good;
};
function adjustVariant(uaVariable, variant) {
const self = uaVariable;
// convert Variant( Scalar|ByteString) => Variant(Array|ByteArray)
const addressSpace = self.addressSpace;
const basicType = addressSpace.findCorrespondingBasicDataType(uaVariable.dataType);
if (basicType === DataType.Byte && uaVariable.valueRank === 1) {
if (variant.arrayType === VariantArrayType.Scalar && variant.dataType === DataType.ByteString) {
if ((uaVariable.dataType.value === DataType.Byte.value) && (self.dataType.namespace === 0)) { // Byte
variant.arrayType = VariantArrayType.Array;
variant.dataType = DataType.Byte;
assert(variant.dataType === DataType.Byte);
assert(!variant.value || variant.value instanceof Buffer);
}
}
}
if (basicType === DataType.ByteString && uaVariable.valueRank === -1 /* Scalar*/) {
if (variant.arrayType === VariantArrayType.Array && variant.dataType === DataType.Byte) {
if ((self.dataType.value === DataType.ByteString.value) && (self.dataType.namespace === 0)) { // Byte
variant.arrayType = VariantArrayType.Scalar;
variant.dataType = DataType.ByteString;
assert(variant.dataType === DataType.ByteString);
assert(!variant.value || variant.value instanceof Buffer);
}
}
}
return variant;
}
/**
* @method writeValue
* @param context {SessionContext}
* @param dataValue {DataValue}
* @param [indexRange] {NumericRange}
* @param callback {Function}
* @param callback.err {Error|null}
* @param callback.statusCode {StatusCode}
* @async
*
*/
UAVariable.prototype.writeValue = function (context, dataValue, indexRange, callback) {
const self = this;
if (!context) {
context = SessionContext.defaultContext;
}
if (!dataValue.sourceTimestamp) {
if (context.currentTime) {
dataValue.sourceTimestamp = context.currentTime;
dataValue.sourcePicoseconds = 0;
} else {
const clock = getCurrentClock();
dataValue.sourceTimestamp = clock.timestamp;
dataValue.sourcePicoseconds = clock.picoseconds;
}
}
if (context.currentTime && !dataValue.serverTimestamp) {
dataValue.serverTimestamp = context.currentTime;
dataValue.serverPicoseconds = 0;
}
assert(context instanceof SessionContext);
// adjust arguments if optional indexRange Parameter is not given
if (!_.isFunction(callback) && _.isFunction(indexRange)) {
callback = indexRange;
indexRange = new NumericRange();
}
assert(_.isFunction(callback));
assert(dataValue instanceof DataValue);
indexRange = NumericRange.coerce(indexRange);
// test write permission
if (!self.isWritable(context)) {
return callback(null, StatusCodes.BadNotWritable);
}
if (!self.isUserWritable(context)) {
return callback(null, StatusCodes.BadUserAccessDenied);
}
// adjust special case
const variant = adjustVariant(self, dataValue.value);
const statusCode = self.isValueInRange(variant);
if (statusCode.isNot(StatusCodes.Good)) {
return callback(null, statusCode);
}
if (!self._timestamped_set_func) {
console.log(" warning " + self.nodeId.toString() + " has no _timestamped_set_func");
return callback(null, StatusCodes.BadNotWritable);
}
assert(self._timestamped_set_func);
self._timestamped_set_func(dataValue, indexRange, function (err, statusCode, correctedDataValue) {
if (!err) {
correctedDataValue = correctedDataValue || dataValue;
assert(correctedDataValue instanceof DataValue);
//xx assert(correctedDataValue.serverTimestamp);
if (indexRange && !indexRange.isEmpty()) {
if (!indexRange.isValid()) {
return callback(null, StatusCodes.BadIndexRangeInvalid);
}
const newArr = correctedDataValue.value.value;
// check that source data is an array
if (correctedDataValue.value.arrayType !== VariantArrayType.Array) {
return callback(null, StatusCodes.BadTypeMismatch);
}
// check that destination data is also an array
assert(check_valid_array(self._dataValue.value.dataType, self._dataValue.value.value));
const destArr = self._dataValue.value.value;
const result = indexRange.set_values(destArr, newArr);
if (result.statusCode.isNot(StatusCodes.Good)) {
return callback(null, result.statusCode);
}
correctedDataValue.value.value = result.array;
// scrap original array so we detect range
self._dataValue.value.value = null;
}
self._internal_set_dataValue(correctedDataValue, indexRange);
//xx self._dataValue = correctedDataValue;
}
callback(err, statusCode);
});
};
/**
* @method writeAttribute
* @param context {SessionContext}
* @param writeValue {WriteValue}
* @param writeValue.nodeId {NodeId}
* @param writeValue.attributeId {AttributeId}*
* @param writeValue.value {DataValue}
* @param writeValue.indexRange {NumericRange}
* @param callback {Function}
* @param callback.err {Error|null}
* @param callback.statusCode {StatusCode}
* @async
*/
UAVariable.prototype.writeAttribute = function (context, writeValue, callback) {
assert(context instanceof SessionContext);
assert(writeValue instanceof WriteValue);
assert(writeValue.value instanceof DataValue);
assert(writeValue.value.value instanceof Variant);
assert(_.isFunction(callback));
// Spec 1.0.2 Part 4 page 58
// If the SourceTimestamp or the ServerTimestamp is specified, the Server shall
// use these values.
//xx _apply_default_timestamps(writeValue.value);
switch (writeValue.attributeId) {
case AttributeIds.Value:
this.writeValue(context, writeValue.value, writeValue.indexRange, callback);
break;
case AttributeIds.Historizing:
if (!writeValue.value.value.dataType === DataType.Boolean) {
return callback(null, StatusCodes.BadNotSupported)
}
// if the uavariable has no historization in place reject
if (!this["hA Configuration"]) {
return callback(null, StatusCodes.BadNotSupported)
}
// check if user is allowed to do that !
// TODO
this.historizing = !!writeValue.value.value.value; // yes ! indeed !
return callback(null, StatusCodes.Good);
default:
BaseNode.prototype.writeAttribute.call(this, context, writeValue, callback);
break;
}
};
function _not_writable_timestamped_set_func(dataValue, callback) {
assert(dataValue instanceof DataValue);
callback(null, StatusCodes.BadNotWritable, null);
}
function _default_writable_timestamped_set_func(dataValue, callback) {
/* jshint validthis: true */
assert(dataValue instanceof DataValue);
callback(null, StatusCodes.Good, dataValue);
}
function turn_sync_to_async(f, numberOfArgs) {
if (f.length <= numberOfArgs) {
return function (data, callback) {
const r = f.call(this,data);
setImmediate(function () {
return callback(null, r);
});
};
} else {
assert(f.length === numberOfArgs + 1);
return f;
}
}
const _default_minimumSamplingInterval = 1000;
// variation #3 :
function _Variable_bind_with_async_refresh(options) {
/* jshint validthis: true */
const self = this;
assert(self instanceof UAVariable);
assert(_.isFunction(options.refreshFunc));
assert(!options.get, "a getter shall not be specified when refreshFunc is set");
assert(!options.timestamped_get, "a getter shall not be specified when refreshFunc is set");
assert(!self.asyncRefresh);
assert(!self.refreshFunc);
self.refreshFunc = options.refreshFunc;
function coerceDataValue(dataValue) {
if (dataValue instanceof DataValue) {
return dataValue;
}
return new DataValue(dataValue);
}
self.asyncRefresh = function (callback) {
self.refreshFunc.call(self, function (err, dataValue) {
if (err || !dataValue) {
dataValue = {statusCode: StatusCodes.BadNoDataAvailable};
}
dataValue = coerceDataValue(dataValue);
self._internal_set_dataValue(dataValue, null);
callback(err, self._dataValue);
});
};
//assert(self._dataValue.statusCode === StatusCodes.BadNodeIdUnknown);
self._dataValue.statusCode = StatusCodes.UncertainInitialValue;
// TO DO : REVISIT THIS ASSUMPTION
if (false && self.minimumSamplingInterval === 0) {
// when a getter /timestamped_getter or async_getter is provided
// samplingInterval cannot be 0, as the item value must be scanned to be updated.
self.minimumSamplingInterval = _default_minimumSamplingInterval; // MonitoredItem.minimumSamplingInterval;
debugLog("adapting minimumSamplingInterval on " + self.browseName.toString() + " to " + self.minimumSamplingInterval);
}
}
// variation 2
function _Variable_bind_with_timestamped_get(options) {