-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
ua_variable.ts
2083 lines (1788 loc) · 76.7 KB
/
ua_variable.ts
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
/**
* @module node-opcua-address-space
*/
// tslint:disable:no-bitwise
// tslint:disable:no-console
// tslint:disable:max-line-length
import * as chalk from "chalk";
import { assert } from "node-opcua-assert";
import * as _ from "underscore";
import { isValidDataEncoding } from "node-opcua-data-model";
import { convertAccessLevelFlagToByte, QualifiedNameLike } from "node-opcua-data-model";
import { NodeClass } from "node-opcua-data-model";
import { AccessLevelFlag } from "node-opcua-data-model";
import { makeAccessLevelFlag } from "node-opcua-data-model";
import { AttributeIds } from "node-opcua-data-model";
import { isDataEncoding } from "node-opcua-data-model";
import { extractRange, sameDataValue } from "node-opcua-data-value";
import { DataValue, DataValueLike } from "node-opcua-data-value";
import { coerceClock, getCurrentClock, PreciseClock } from "node-opcua-date-time";
import { checkDebugFlag, make_debugLog } from "node-opcua-debug";
import { ExtensionObject } from "node-opcua-extension-object";
import { findBuiltInType } from "node-opcua-factory";
import { NodeId } from "node-opcua-nodeid";
import { NumericRange } from "node-opcua-numeric-range";
import { WriteValue, WriteValueOptions } from "node-opcua-service-write";
import { StatusCode, StatusCodes, CallbackT } from "node-opcua-status-code";
import {
EnumDefinition,
EnumField,
HistoryReadDetails,
HistoryReadResult,
HistoryReadResultOptions,
Range,
ReadAtTimeDetails,
ReadEventDetails,
ReadProcessedDetails,
ReadRawModifiedDetails,
StructureDefinition,
StructureDescription
} from "node-opcua-types";
import * as utils from "node-opcua-utils";
import { lowerFirstLetter } from "node-opcua-utils";
import { Variant, VariantLike } from "node-opcua-variant";
import { DataType } from "node-opcua-variant";
import { sameVariant, VariantArrayType } from "node-opcua-variant";
import { StatusCodeCallback } from "node-opcua-status-code";
import {
AddressSpace,
BindVariableOptions,
ContinuationPoint,
DataValueCallback,
HistoricalDataConfiguration,
IVariableHistorian, Permissions,
PseudoSession,
UADataType as UADataTypePublic,
UAVariable as UAVariablePublic, UAVariableType
} from "../source";
import { BaseNode } from "./base_node";
import { _clone, apply_condition_refresh, BaseNode_toString, ToStringBuilder, UAVariable_toString } from "./base_node_private";
import { SessionContext } from "./session_context";
import { EnumerationInfo, IEnumItem, UADataType } from "./ua_data_type";
const debugLog = make_debugLog(__filename);
const doDebug = checkDebugFlag(__filename);
function isGoodish(statusCode: StatusCode) {
return statusCode.value < 0x10000000;
}
export function adjust_accessLevel(accessLevel: any): AccessLevelFlag {
accessLevel = utils.isNullOrUndefined(accessLevel) ? "CurrentRead | CurrentWrite" : accessLevel;
accessLevel = makeAccessLevelFlag(accessLevel);
assert(_.isFinite(accessLevel));
return accessLevel;
}
export function adjust_userAccessLevel(userAccessLevel: any, accessLevel: any): AccessLevelFlag {
userAccessLevel = utils.isNullOrUndefined(userAccessLevel) ? "CurrentRead | CurrentWrite" : userAccessLevel;
userAccessLevel = makeAccessLevelFlag(userAccessLevel);
accessLevel = utils.isNullOrUndefined(accessLevel) ? "CurrentRead | CurrentWrite" : accessLevel;
accessLevel = makeAccessLevelFlag(accessLevel);
return makeAccessLevelFlag(accessLevel & userAccessLevel);
}
function adjust_samplingInterval(minimumSamplingInterval: number): number {
assert(_.isFinite(minimumSamplingInterval));
return minimumSamplingInterval;
}
function is_Variant(v: any): boolean {
return v instanceof Variant;
}
function is_StatusCode(v: any): boolean {
return v && v.constructor &&
(
v.constructor.name === "ConstantStatusCode" ||
v.constructor.name === "StatusCode" ||
v.constructor.name === "ModifiableStatusCode"
);
}
function is_Variant_or_StatusCode(v: any): boolean {
if (is_Variant(v)) {
// /@@assert(v.isValid());
}
return is_Variant(v) || is_StatusCode(v);
}
function _dataType_toUADataType(
addressSpace: AddressSpace,
dataType: DataType
): UADataType {
assert(addressSpace);
assert(dataType !== DataType.Null);
const dataTypeNode = addressSpace.findDataType(DataType[dataType]);
/* istanbul ignore next */
if (!dataTypeNode) {
throw new Error(" Cannot find DataType " + DataType[dataType] + " in address Space");
}
return dataTypeNode as UADataType;
}
/*=
*
* @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: AddressSpace,
dataTypeNodeId: NodeId,
variantDataType: DataType,
nodeId: NodeId
): boolean {
if (variantDataType === DataType.ExtensionObject) {
return true;
}
if (variantDataType === DataType.Null) {
return true;
}
let builtInType: string;
let builtInUADataType: UADataTypePublic;
const destUADataType = addressSpace.findNode(dataTypeNodeId) as UADataType;
assert(destUADataType instanceof UADataType);
if (destUADataType.isAbstract || destUADataType.nodeId.namespace !== 0) {
builtInUADataType = destUADataType;
} else {
builtInType = findBuiltInType(destUADataType.symbolicName).name;
builtInUADataType = addressSpace.findDataType(builtInType)!;
}
assert(builtInUADataType instanceof UADataType);
const enumerationUADataType = addressSpace.findDataType("Enumeration");
if (!enumerationUADataType) {
throw new Error("cannot find Enumeration DataType node in standard address space");
}
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(chalk.green(" ---------- Type match !!! "), " on ", nodeId.toString());
} else {
/* istanbul ignore next*/
console.log(chalk.red(" ---------- Type mismatch "), " on ", nodeId.toString());
}
console.log(chalk.cyan(" Variable data Type is = "), destUADataType.browseName.toString());
console.log(chalk.cyan(" which matches basic Type = "), builtInUADataType.browseName.toString());
console.log(chalk.yellow(" Actual dataType = "), variantUADataType.browseName.toString());
}
return (dest_isSuperTypeOf_variant);
}
/**
* 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] {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.
*
*/
export class UAVariable extends BaseNode implements UAVariablePublic {
public readonly nodeClass = NodeClass.Variable;
public dataType: NodeId;
public $historicalDataConfiguration?: HistoricalDataConfiguration;
public varHistorian?: IVariableHistorian;
/**
* @internal
*/
public _dataValue: DataValue;
public accessLevel: number;
public userAccessLevel: number;
public valueRank: number;
public minimumSamplingInterval: number;
public historizing: boolean;
public semantic_version: number;
public _permissions: any | null;
public arrayDimensions: any;
public $extensionObject?: any;
public _timestamped_get_func: any;
public _timestamped_set_func: any;
public _get_func: any;
public _set_func: any;
public refreshFunc?: (callback: DataValueCallback) => void;
public __waiting_callbacks?: any[];
get typeDefinitionObj(): UAVariableType {
return super.typeDefinitionObj as UAVariableType;
}
constructor(options: any) {
super(options);
this.dataType = this.resolveNodeId(options.dataType); // DataType (NodeId)
assert(this.dataType instanceof NodeId);
this.valueRank = options.valueRank || 0; // UInt32
assert(typeof this.valueRank === "number");
this.arrayDimensions = options.arrayDimensions || null;
assert(_.isNull(this.arrayDimensions) || _.isArray(this.arrayDimensions));
this.accessLevel = adjust_accessLevel(options.accessLevel);
this.userAccessLevel = adjust_userAccessLevel(options.userAccessLevel, options.accessLevel);
this.minimumSamplingInterval = adjust_samplingInterval(options.minimumSamplingInterval);
this.historizing = !!options.historizing; // coerced to boolean
this._dataValue = new DataValue({ statusCode: StatusCodes.UncertainInitialValue, value: {} });
// xx options.value = options.value || { dataType: DataType.Null };
if (options.value) {
this.bindVariable(options.value);
}
this._permissions = null;
if (options.permissions) {
this.setPermissions(options.permissions);
}
this.setMaxListeners(5000);
this.semantic_version = 0;
}
public isReadable(context: SessionContext): boolean {
return (this.accessLevel & AccessLevelFlag.CurrentRead) === AccessLevelFlag.CurrentRead;
}
public isUserReadable(context: SessionContext): boolean {
assert(context instanceof SessionContext);
if (context.checkPermission) {
assert(context.checkPermission instanceof Function);
return context.checkPermission(this, "CurrentRead");
}
return (this.userAccessLevel & AccessLevelFlag.CurrentRead) === AccessLevelFlag.CurrentRead;
}
public isWritable(context: SessionContext): boolean {
assert(context instanceof SessionContext);
return ((this.accessLevel & AccessLevelFlag.CurrentWrite) === AccessLevelFlag.CurrentWrite);
}
public isUserWritable(context: SessionContext): boolean {
assert(context instanceof SessionContext);
if (context.checkPermission) {
assert(context.checkPermission instanceof Function);
return context.checkPermission(this, "CurrentWrite");
}
return ((this.userAccessLevel & AccessLevelFlag.CurrentWrite) === AccessLevelFlag.CurrentWrite);
}
/**
*
*
* 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 BadAttributeIdInvalid 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)
*/
public readValue(context?: SessionContext | null, indexRange?: NumericRange, dataEncoding?: string) {
if (!context) {
context = SessionContext.defaultContext;
}
if (!this.isReadable(context)) {
return new DataValue({ statusCode: StatusCodes.BadNotReadable });
}
if (!this.isUserReadable(context)) {
return new DataValue({ statusCode: StatusCodes.BadUserAccessDenied });
}
if (!isValidDataEncoding(dataEncoding)) {
return new DataValue({ statusCode: StatusCodes.BadDataEncodingInvalid });
}
if (this._timestamped_get_func) {
assert(this._timestamped_get_func.length === 0);
this._dataValue = this._timestamped_get_func();
}
let dataValue = this._dataValue;
if (isGoodish(dataValue.statusCode)) {
// note : extractRange will clone the dataValue
dataValue = extractRange(dataValue, indexRange);
}
/* istanbul ignore next */
if (dataValue.statusCode.equals(StatusCodes.BadWaitingForInitialData)
|| dataValue.statusCode.equals(StatusCodes.UncertainInitialValue)
) {
debugLog(chalk.red(" Warning: UAVariable#readValue ")
+ chalk.cyan(this.browseName.toString()) +
" (" + chalk.yellow(this.nodeId.toString()) + ") exists but dataValue has not been defined");
}
return dataValue;
}
public isEnumeration(): boolean {
// DataType must be one of Enumeration
const dataTypeNode = this.addressSpace.findDataType(this.dataType) as UADataType;
if (!dataTypeNode) {
throw new Error(" Cannot find DataType " + this.dataType.toString() + " in standard address Space");
}
const enumerationNode = this.addressSpace.findDataType("Enumeration")!;
if (!enumerationNode) {
throw new Error(" Cannot find 'Enumeration' DataType in standard address Space");
}
return dataTypeNode.isSupertypeOf(enumerationNode);
}
public isExtensionObject(): boolean {
// DataType must be one of Structure
const dataTypeNode = this.addressSpace.findDataType(this.dataType) as UADataType;
if (!dataTypeNode) {
throw new Error(" Cannot find DataType " + this.dataType.toString() + " in standard address Space");
}
const structureNode = this.addressSpace.findDataType("Structure")!;
if (!structureNode) {
throw new Error(" Cannot find 'Structure' DataType in standard address Space");
}
return dataTypeNode.isSupertypeOf(structureNode);
}
public _getEnumerationInfo(): EnumerationInfo {
// DataType must be one of Enumeration
assert(this.isEnumeration(), "Variable is not an enumeration");
const dataTypeNode = this.addressSpace.findDataType(this.dataType)! as UADataType;
return dataTypeNode._getEnumerationInfo();
}
public asyncRefresh(...args: any[]): any {
const oldestDate = args[0] as Date;
const callback = args[1] as DataValueCallback;
if (!this.refreshFunc) {
// no refresh func
const dataValue = this.readValue();
dataValue.serverTimestamp = oldestDate;
dataValue.serverPicoseconds = 0;
if (oldestDate.getTime() <= dataValue.serverTimestamp!.getTime()) {
return callback(null, dataValue);
} else {
// fake
return callback(null, dataValue);
}
}
if (this._dataValue.serverTimestamp && (oldestDate.getTime() <= this._dataValue.serverTimestamp!.getTime())) {
const dataValue = this.readValue();
dataValue.serverTimestamp = oldestDate;
dataValue.serverPicoseconds = 0;
return callback(null, dataValue);
}
this.refreshFunc.call(this, (err: Error | null, dataValue?: DataValueLike) => {
if (err || !dataValue) {
dataValue = { statusCode: StatusCodes.BadNoDataAvailable };
}
if (dataValue !== this._dataValue) {
this._internal_set_dataValue(coerceDataValue(dataValue), null);
}
callback(err, this._dataValue);
});
}
public readEnumValue(): IEnumItem {
const value = this.readValue().value.value as number;
const enumInfo = this._getEnumerationInfo();
const enumV = enumInfo.valueIndex[value];
return { value, name: enumV ? enumV.name : "?????" };
}
public writeEnumValue(value: string | number): void {
const enumInfo = this._getEnumerationInfo();
if (_.isString(value)) {
if (!enumInfo.nameIndex.hasOwnProperty(value)) {
const possibleValues = Object.keys(enumInfo.nameIndex).join(",");
throw new Error("UAVariable#writeEnumValue: cannot find value " +
value + " in [" + possibleValues + "]");
}
const valueIndex = enumInfo.nameIndex[value].value;
value = valueIndex;
}
if (_.isFinite(value)) {
const possibleValues = Object.keys(enumInfo.nameIndex).join(",");
if (!enumInfo.valueIndex[value]) {
throw new Error("UAVariable#writeEnumValue : value out of range " + value +
" in [" + possibleValues + "]"
);
}
this.setValueFromSource({
dataType: DataType.Int32,
value
});
} else {
throw new Error("UAVariable#writeEnumValue: value type mismatch");
}
}
public readAttribute(
context: SessionContext | null,
attributeId: AttributeIds,
indexRange?: NumericRange,
dataEncoding?: string
): DataValue {
if (!context) {
context = SessionContext.defaultContext;
}
assert(context instanceof SessionContext);
const options: DataValueLike = {};
if (attributeId !== AttributeIds.Value) {
if (indexRange && indexRange.isDefined()) {
options.statusCode = StatusCodes.BadIndexRangeNoData;
return new DataValue(options);
}
if (isDataEncoding(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);
}
}
/**
* 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]
*/
public setValueFromSource(
variant: VariantLike,
statusCode?: StatusCode,
sourceTimestamp?: Date
) {
// istanbul ignore next
if (variant.hasOwnProperty("value")) {
if (variant.dataType === null || variant.dataType === undefined) {
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({
serverPicoseconds: now.picoseconds,
serverTimestamp: now.timestamp,
sourcePicoseconds: now.picoseconds,
sourceTimestamp: now.timestamp,
statusCode: statusCode || StatusCodes.Good
});
dataValue.value = variant as Variant;
this._internal_set_dataValue(dataValue);
}
public writeValue(context: SessionContext, dataValue: DataValue, ...args: any[]): any {
if (!context) {
context = SessionContext.defaultContext;
}
if (!dataValue.sourceTimestamp) {
dataValue.sourceTimestamp = this._dataValue.sourceTimestamp;
dataValue.sourcePicoseconds = this._dataValue.sourcePicoseconds;
/*
if (false) {
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
let indexRange: NumericRange | null = null;
let callback: StatusCodeCallback;
if (args.length === 1) {
indexRange = new NumericRange();
callback = args[0];
} else if (args.length === 2) {
indexRange = args[0];
callback = args[1];
} else {
throw new Error("Invalid Number of args");
}
assert(_.isFunction(callback));
assert(dataValue instanceof DataValue);
// index range could be string
indexRange = NumericRange.coerce(indexRange);
// test write permission
if (!this.isWritable(context)) {
return callback!(null, StatusCodes.BadNotWritable);
}
if (!this.isUserWritable(context)) {
return callback!(null, StatusCodes.BadUserAccessDenied);
}
// adjust special case
const variant = adjustVariant.call(this, dataValue.value);
const statusCode = this.checkVariantCompatibility(variant);
if (statusCode.isNot(StatusCodes.Good)) {
return callback!(null, statusCode);
}
const write_func = this._timestamped_set_func || ((
dataValue1: DataValue,
indexRange1: NumericRange,
callback1: (err: Error | null, statusCode: StatusCode, dataValue?: DataValue | null | undefined) => void
) => {
// xx assert(!indexRange,"indexRange Not Implemented");
return _default_writable_timestamped_set_func.call(this, dataValue1, callback1);
});
if (!write_func) {
console.log(" warning " + this.nodeId.toString() + " " + this.browseName.toString() + " has no setter. \n");
console.log("Please make sure to bind the variable or to pass a valid value: new Variant({}) during construction time");
return callback!(null, StatusCodes.BadNotWritable);
}
assert(write_func);
write_func.call(this, dataValue, indexRange, (
err: Error | null,
statusCode1: StatusCode,
correctedDataValue: DataValue) => {
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(this._dataValue.value.dataType, this._dataValue.value.value));
const destArr = this._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
this._dataValue.value.value = null;
}
this._internal_set_dataValue(correctedDataValue, indexRange);
// xx this._dataValue = correctedDataValue;
}
callback!(err, statusCode1);
});
}
public writeAttribute(
context: SessionContext,
writeValueOptions: WriteValueOptions | WriteValue,
callback?: (err: Error | null, statusCode?: StatusCode) => void
): any {
if (!callback) {
throw new Error("Internal error");
}
const writeValue: WriteValue = writeValueOptions instanceof WriteValue
? writeValueOptions as WriteValue
: new WriteValue(writeValueOptions);
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 variable has no historizing in place reject
if (!(this as any)["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:
super.writeAttribute(context, writeValue, callback);
break;
}
}
/**
* @method checkVariantCompatibility
* note:
* this method is overridden in address-space-data-access
* @return {StatusCode}
*/
public checkVariantCompatibility(value: Variant): StatusCode {
// test dataType
if (!this._validate_DataType(value.dataType)) {
return StatusCodes.BadTypeMismatch;
}
return StatusCodes.Good;
}
/**
* @method touchValue
* touch the source timestamp of a Variable and cascade up the change
* to the parent variable if any.
*
* @param [optionalNow=null] {Object}
* @param optionalNow.timestamp {Date}
* @param optionalNow.picoseconds {Number}
*/
public touchValue(optionalNow?: PreciseClock): void {
const variable = this;
const now = optionalNow || getCurrentClock();
variable._dataValue.sourceTimestamp = now.timestamp;
variable._dataValue.sourcePicoseconds = now.picoseconds;
variable._dataValue.serverTimestamp = now.timestamp;
variable._dataValue.serverPicoseconds = now.picoseconds;
variable._dataValue.statusCode = StatusCodes.Good;
if (variable.minimumSamplingInterval === 0) {
// xx console.log("xxx touchValue = ",variable.browseName.toString(),variable._dataValue.value.value);
if (variable.listenerCount("value_changed") > 0) {
const clonedDataValue = variable.readValue();
variable.emit("value_changed", clonedDataValue);
}
}
if (variable.parent && variable.parent.nodeClass === NodeClass.Variable) {
(variable.parent as UAVariable).touchValue(now);
}
}
/**
* setPermissions
* set the role and permissions
*
* @example
*
* const permissions = {
* CurrentRead: [ "*" ], // all users can read
* CurrentWrite: [ "!*", "Administrator" ] // no one except administrator can write
* };
* node.setPermissions(permissions);
*/
public setPermissions(permissions: Permissions): void {
this._permissions = permissions;
}
/**
* bind a variable with a get and set functions.
*
* @method bindVariable
* @param options
* @param [options.dataType=null] the nodeId of the dataType
* @param [options.accessLevel] AccessLevelFlagItem
* @param [options.userAccessLevel] AccessLevelFlagItem
* @param [options.set] the variable setter function
* @param [options.get] the variable getter function. the function must return a Variant or a status code
* @param [options.timestamped_get] the getter function. this function must return a object with the following
* @param [options.historyRead]
*
* properties:
* - value: a Variant or a status code
* - sourceTimestamp
* - sourcePicoseconds
* @param [options.timestamped_set]
* @param [options.refreshFunc] the variable asynchronous getter function.
* @param [overwrite {Boolean} = false] set overwrite to true to overwrite existing binding
* @return void
*
*
* ### Providing read access to the underlying value
*
* #### Variation 1
*
* In this variation, the user provides a function that returns a Variant with the current value.
*
* The sourceTimestamp will be set automatically.
*
* The get function is called synchronously.
*
* @example
*
*
* ```javascript
* ...
* var options = {
* get : () => {
* return new Variant({...});
* },
* set : function(variant) {
* // store the variant somewhere
* return StatusCodes.Good;
* }
* };
* ...
* engine.bindVariable(nodeId,options):
* ...
* ```
*
*
* #### Variation 2:
*
* This variation can be used when the user wants to specify a specific '''sourceTimestamp''' associated
* with the current value of the UAVariable.
*
* The provided ```timestamped_get``` function should return an object with three properties:
* * value: containing the variant value or a error StatusCode,
* * sourceTimestamp
* * sourcePicoseconds
*
* ```javascript
* ...
* var myDataValue = new DataValue({
* value: {dataType: DataType.Double , value: 10.0},
* sourceTimestamp : new Date(),
* sourcePicoseconds: 0
* });
* ...
* var options = {
* timestamped_get : () => { return myDataValue; }
* };
* ...
* engine.bindVariable(nodeId,options):
* ...
* // record a new value
* myDataValue.value.value = 5.0;
* myDataValue.sourceTimestamp = new Date();
* ...
* ```
*
*
* #### Variation 3:
*
* This variation can be used when the value associated with the variables requires a asynchronous function call to be
* extracted. In this case, the user should provide an async method ```refreshFunc```.
*
*
* The ```refreshFunc``` shall do whatever is necessary to fetch the most up to date version of the variable value, and
* call the ```callback``` function when the data is ready.
*
*
* The ```callback``` function follow the standard callback function signature:
* * the first argument shall be **null** or **Error**, depending of the outcome of the fetch operation,
* * the second argument shall be a DataValue with the new UAVariable Value, a StatusCode, and time stamps.
*
*
* Optionally, it is possible to pass a sourceTimestamp and a sourcePicoseconds value as a third and fourth arguments
* of the callback. When sourceTimestamp and sourcePicoseconds are missing, the system will set their default value
* to the current time..
*
*
* ```javascript
* ...
* var options = {
* refreshFunc : function(callback) {
* ... do_some_async_stuff_to_get_the_new_variable_value
* var dataValue = new DataValue({
* value: new Variant({...}),
* statusCode: StatusCodes.Good,
* sourceTimestamp: new Date()
* });
* callback(null,dataValue);
* }
* };
* ...
* variable.bindVariable(nodeId,options):
* ...
* ```
*
* ### Providing write access to the underlying value
*
* #### Variation1 - provide a simple synchronous set function
*
*
* #### Notes
* to do : explain return StatusCodes.GoodCompletesAsynchronously;
*
*/
public bindVariable(
options?: BindVariableOptions,
overwrite?: boolean
): void {
if (overwrite) {
this._timestamped_set_func = null;
this._timestamped_get_func = null;
this._get_func = null;
this._set_func = null;
this.refreshFunc = undefined;
this._historyRead = UAVariable.prototype._historyRead;
}
options = options || {};
assert(!_.isFunction(this._timestamped_set_func), "UAVariable already bound");
assert(!_.isFunction(this._timestamped_get_func), "UAVariable already bound");
bind_getter.call(this, options);
bind_setter.call(this, options);
if (options.historyRead) {
assert(!_.isFunction(this._historyRead) ||
this._historyRead === UAVariable.prototype._historyRead);
assert(_.isFunction(options.historyRead));