/
ua_variable_impl.ts
2323 lines (2102 loc) · 91.7 KB
/
ua_variable_impl.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
/* eslint-disable max-statements */
/* eslint-disable complexity */
/**
* @module node-opcua-address-space
*/
// tslint:disable:no-bitwise
// tslint:disable:no-console
// tslint:disable:max-line-length
import * as chalk from "chalk";
import {
BindExtensionObjectOptions,
CloneExtraInfo,
ContinuationData,
defaultCloneExtraInfo,
defaultCloneFilter,
GetFunc,
SetFunc,
VariableDataValueGetterSync,
VariableDataValueSetterWithCallback
} from "node-opcua-address-space-base";
import { assert } from "node-opcua-assert";
import {
isValidDataEncoding,
convertAccessLevelFlagToByte,
QualifiedNameLike,
NodeClass,
AccessLevelFlag,
makeAccessLevelFlag,
AttributeIds,
isDataEncoding,
QualifiedName
} from "node-opcua-data-model";
import { extractRange, sameDataValue, DataValue, DataValueLike, DataValueT } from "node-opcua-data-value";
import { coerceClock, getCurrentClock, PreciseClock } from "node-opcua-date-time";
import { checkDebugFlag, make_debugLog, make_errorLog, make_warningLog } from "node-opcua-debug";
import { ExtensionObject } from "node-opcua-extension-object";
import { NodeId } from "node-opcua-nodeid";
import { NumericRange } from "node-opcua-numeric-range";
import { WriteValue } from "node-opcua-service-write";
import { StatusCode, StatusCodes, CallbackT } from "node-opcua-status-code";
import {
HistoryReadDetails,
HistoryReadResult,
PermissionType,
ReadAtTimeDetails,
ReadEventDetails,
ReadProcessedDetails,
ReadRawModifiedDetails,
WriteValueOptions
} from "node-opcua-types";
import * as utils from "node-opcua-utils";
import {
Variant,
VariantLike,
DataType,
sameVariant,
VariantArrayType,
adjustVariant,
verifyRankAndDimensions
} from "node-opcua-variant";
import { StatusCodeCallback } from "node-opcua-status-code";
import {
IAddressSpace,
BindVariableOptions,
IVariableHistorian,
TimestampGetFunc,
TimestampSetFunc,
UADataType,
UAVariable,
UAVariableType,
CloneOptions,
CloneFilter,
ISessionContext,
BaseNode,
UAVariableT
} from "node-opcua-address-space-base";
import { UAHistoricalDataConfiguration } from "node-opcua-nodeset-ua";
import { SessionContext } from "../source/session_context";
import { convertToCallbackFunction1 } from "../source/helpers/multiform_func";
import { BaseNodeImpl, InternalBaseNodeOptions } from "./base_node_impl";
import { _clone, ToStringBuilder, UAVariable_toString } from "./base_node_private";
import { EnumerationInfo, IEnumItem, UADataTypeImpl } from "./ua_data_type_impl";
import { apply_condition_refresh, ConditionRefreshCache } from "./apply_condition_refresh";
import {
extractPartialData,
incrementElement,
propagateTouchValueDownward,
propagateTouchValueDownwardArray,
propagateTouchValueUpward,
setExtensionObjectPartialValue,
_bindExtensionObject,
_bindExtensionObjectArrayOrMatrix,
_installExtensionObjectBindingOnProperties,
_touchValue
} from "./ua_variable_impl_ext_obj";
const debugLog = make_debugLog(__filename);
const warningLog = make_warningLog(__filename);
const doDebug = checkDebugFlag(__filename);
const errorLog = make_errorLog(__filename);
export function adjust_accessLevel(accessLevel: string | number | null): AccessLevelFlag {
accessLevel = utils.isNullOrUndefined(accessLevel) ? "CurrentRead | CurrentWrite" : accessLevel;
accessLevel = makeAccessLevelFlag(accessLevel);
assert(isFinite(accessLevel));
return accessLevel;
}
export function adjust_userAccessLevel(
userAccessLevel: string | number | null | undefined,
accessLevel: string | number | null
): AccessLevelFlag | undefined {
if (userAccessLevel === undefined) {
return undefined;
}
userAccessLevel = adjust_accessLevel(userAccessLevel);
accessLevel = adjust_accessLevel(accessLevel);
return makeAccessLevelFlag(accessLevel & userAccessLevel);
}
function adjust_samplingInterval(minimumSamplingInterval: number): number {
assert(isFinite(minimumSamplingInterval));
if (minimumSamplingInterval < 0) {
return -1; // only -1 is a valid negative value for samplingInterval and means "unspecified"
}
return minimumSamplingInterval;
}
function is_Variant(v: any): boolean {
return v instanceof Variant;
}
function is_StatusCode(v: any): boolean {
return (
v &&
v.constructor &&
(v instanceof StatusCode ||
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: IAddressSpace, 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: IAddressSpace,
dataTypeNodeId: NodeId,
variantDataType: DataType,
nodeId: NodeId,
allowNulls: boolean
): boolean {
if (variantDataType === DataType.ExtensionObject) {
return true;
}
if (variantDataType === DataType.Null && allowNulls) {
return true;
}
if (variantDataType === DataType.Null && !allowNulls) {
return false;
}
let builtInType: DataType;
let builtInUADataType: UADataType;
const destUADataType = addressSpace.findDataType(dataTypeNodeId)!;
assert(destUADataType instanceof UADataTypeImpl);
if (destUADataType.isAbstract || destUADataType.nodeId.namespace !== 0) {
builtInUADataType = destUADataType;
} else {
builtInType = addressSpace.findCorrespondingBasicDataType(destUADataType);
builtInUADataType = addressSpace.findDataType(builtInType)!;
}
assert(builtInUADataType instanceof UADataTypeImpl);
const enumerationUADataType = addressSpace.findDataType("Enumeration");
if (!enumerationUADataType) {
throw new Error("cannot find Enumeration DataType node in standard address space");
}
if (destUADataType.isSubtypeOf(enumerationUADataType)) {
// istanbul ignore next
if (doDebug) {
debugLog("destUADataType.", destUADataType.browseName.toString(), destUADataType.nodeId.toString());
debugLog(
"enumerationUADataType.",
enumerationUADataType.browseName.toString(),
enumerationUADataType.nodeId.toString()
);
}
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 UADataTypeImpl);
const dest_isSubTypeOf_variant = variantUADataType.isSubtypeOf(builtInUADataType);
/* istanbul ignore next */
if (doDebug) {
if (dest_isSubTypeOf_variant) {
/* istanbul ignore next*/
debugLog(chalk.green(" ---------- Type match !!! "), " on ", nodeId.toString());
} else {
/* istanbul ignore next*/
debugLog(chalk.red(" ---------- Type mismatch "), " on ", nodeId.toString());
}
debugLog(chalk.cyan(" Variable data Type is = "), destUADataType.browseName.toString());
debugLog(chalk.cyan(" which matches basic Type = "), builtInUADataType.browseName.toString());
debugLog(chalk.yellow(" Actual dataType = "), variantUADataType.browseName.toString());
}
return dest_isSubTypeOf_variant;
}
function default_func(this: UAVariable, dataValue1: DataValue, callback1: CallbackT<StatusCode>) {
return _default_writable_timestamped_set_func.call(this, dataValue1, callback1);
}
interface UAVariableOptions extends InternalBaseNodeOptions {
value?: any;
dataType: NodeId | string;
/**
* This attribute indicates whether the Value attribute of the Variableis 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.
* * All DataTypes are considered to be scalar, even if they have array-like semantics like ByteString and String.
*/
valueRank?: number;
arrayDimensions?: null | number[];
accessLevel?: any;
userAccessLevel?: any;
minimumSamplingInterval?: number; // default -1
historizing?: number;
}
/**
* A OPCUA Variable Node
*
* @class UAVariable
* @constructor
* @extends BaseNode
* 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 UAVariableImpl extends BaseNodeImpl implements UAVariable {
public readonly nodeClass = NodeClass.Variable;
public dataType: NodeId;
private _basicDataType?: DataType;
public $extensionObject?: any;
public $set_ExtensionObject?: (newValue: ExtensionObject, sourceTimestamp: PreciseClock, cache: Set<UAVariableImpl>) => void;
public $historicalDataConfiguration?: UAHistoricalDataConfiguration;
public varHistorian?: IVariableHistorian;
/**
* @internal @private
*/
public $dataValue: DataValue;
public accessLevel: number;
public userAccessLevel?: number;
public valueRank: number;
public minimumSamplingInterval: number;
public historizing: boolean;
public semantic_version: number;
public arrayDimensions: null | number[];
public _timestamped_get_func?: TimestampGetFunc | null;
public _timestamped_set_func?: VariableDataValueSetterWithCallback | null;
public _get_func: any;
public _set_func: any;
public refreshFunc?: (callback: CallbackT<DataValue>) => void;
public __waiting_callbacks?: any[];
get typeDefinitionObj(): UAVariableType {
// istanbul ignore next
if (super.typeDefinitionObj && super.typeDefinitionObj.nodeClass !== NodeClass.VariableType) {
console.log(super.typeDefinitionObj.toString());
throw new Error(
"Invalid type definition node class , expecting a VariableType got " + NodeClass[super.typeDefinitionObj.nodeClass]
);
}
return super.typeDefinitionObj as UAVariableType;
}
get typeDefinition(): NodeId {
return super.typeDefinition;
}
constructor(options: UAVariableOptions) {
super(options);
verifyRankAndDimensions(options);
this.valueRank = options.valueRank!;
this.arrayDimensions = options.arrayDimensions!;
this.dataType = this.resolveNodeId(options.dataType); // DataType (NodeId)
this.accessLevel = adjust_accessLevel(options.accessLevel);
this.userAccessLevel = adjust_userAccessLevel(options.userAccessLevel, this.accessLevel);
this.minimumSamplingInterval = adjust_samplingInterval(options.minimumSamplingInterval || 0);
this.historizing = !!options.historizing; // coerced to boolean"
this.$dataValue = new DataValue({ statusCode: StatusCodes.UncertainInitialValue, value: { dataType: DataType.Null } });
if (options.value) {
this.bindVariable(options.value);
}
this.setMaxListeners(5000);
this.semantic_version = 0;
}
private checkAccessLevelPrivate(_context: ISessionContext, accessLevel: AccessLevelFlag): boolean {
if (this.userAccessLevel === undefined) {
return true;
}
return (this.userAccessLevel & accessLevel) === accessLevel;
}
private checkPermissionPrivate(context: ISessionContext, permission: PermissionType): boolean {
if (!context) return true;
assert(context instanceof SessionContext);
if (context.checkPermission) {
if (!(context.checkPermission instanceof Function)) {
errorLog("context checkPermission is not a function");
return false;
}
if (!context.checkPermission(this, permission)) {
return false;
}
}
return true;
}
private checkPermissionAndAccessLevelPrivate(
context: ISessionContext,
permission: PermissionType,
accessLevel: AccessLevelFlag
): boolean {
if (!this.checkPermissionPrivate(context, permission)) {
return false;
}
return this.checkAccessLevelPrivate(context, accessLevel);
}
public isReadable(context: ISessionContext): boolean {
return (this.accessLevel & AccessLevelFlag.CurrentRead) === AccessLevelFlag.CurrentRead;
}
public isUserReadable(context: ISessionContext): boolean {
if (!this.isReadable(context)) {
return false;
}
if (!this.checkPermissionPrivate(context, PermissionType.Read)) {
return false;
}
return this.checkAccessLevelPrivate(context, AccessLevelFlag.CurrentRead);
}
public isWritable(context: ISessionContext): boolean {
return (this.accessLevel & AccessLevelFlag.CurrentWrite) === AccessLevelFlag.CurrentWrite;
}
public isUserWritable(context: ISessionContext): boolean {
if (!this.isWritable(context)) {
return false;
}
return this.checkPermissionAndAccessLevelPrivate(context, PermissionType.Write, AccessLevelFlag.CurrentWrite);
}
public canUserReadHistory(context: ISessionContext): boolean {
return this.checkPermissionAndAccessLevelPrivate(context, PermissionType.ReadHistory, AccessLevelFlag.HistoryRead);
}
public canUserWriteHistorizingAttribute(context: ISessionContext): boolean {
if (context && !context.checkPermission(this, PermissionType.WriteHistorizing)) {
return false;
}
return true;
}
public canUserInsertHistory(context: ISessionContext): boolean {
return this.checkPermissionAndAccessLevelPrivate(context, PermissionType.InsertHistory, AccessLevelFlag.HistoryWrite);
}
public canUserModifyHistory(context: ISessionContext): boolean {
return this.checkPermissionAndAccessLevelPrivate(context, PermissionType.ModifyHistory, AccessLevelFlag.HistoryWrite);
}
public canUserDeleteHistory(context: ISessionContext): boolean {
return this.checkPermissionAndAccessLevelPrivate(context, PermissionType.DeleteHistory, AccessLevelFlag.HistoryWrite);
}
/**
*
*
* 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?: ISessionContext | null,
indexRange?: NumericRange,
dataEncoding?: QualifiedNameLike | null
): DataValue {
if (!context) {
context = SessionContext.defaultContext;
}
if (context.isAccessRestricted(this)) {
return new DataValue({ statusCode: StatusCodes.BadSecurityModeInsufficient });
}
if (!this.isReadable(context)) {
return new DataValue({ statusCode: StatusCodes.BadNotReadable });
}
if (!this.checkPermissionPrivate(context, PermissionType.Read)) {
return new DataValue({ statusCode: StatusCodes.BadUserAccessDenied });
}
if (!this.isUserReadable(context)) {
return new DataValue({ statusCode: StatusCodes.BadNotReadable });
}
if (!isValidDataEncoding(dataEncoding)) {
return new DataValue({ statusCode: StatusCodes.BadDataEncodingInvalid });
}
if (this._timestamped_get_func) {
if (this._timestamped_get_func.length === 0) {
const dataValueOrPromise = (this._timestamped_get_func as VariableDataValueGetterSync)();
if (!Object.prototype.hasOwnProperty.call(dataValueOrPromise, "then")) {
if (dataValueOrPromise !== this.$dataValue) {
// TO DO : is this necessary ? this may interfere with current use of $dataValue
this.$dataValue = dataValueOrPromise as DataValue;
this.verifyVariantCompatibility(this.$dataValue.value);
}
} else {
errorLog("Unsupported: _timestamped_get_func returns a Promise !");
}
}
}
let dataValue = this.$dataValue;
if (dataValue.statusCode.isGoodish()) {
// 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 {
return this.addressSpacePrivate.isEnumeration(this.dataType);
}
/**
* return true if the DataType is of type Extension object
* this is not taking into account the valueRank of the variable
*/
public isExtensionObject(): boolean {
// DataType must be one of Structure
if (this.dataType.isEmpty()) return false;
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.isSubtypeOf(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 UADataTypeImpl;
return dataTypeNode._getEnumerationInfo();
}
public asyncRefresh(oldestDate: PreciseClock, callback: CallbackT<DataValue>): void;
public asyncRefresh(oldestDate: PreciseClock): Promise<DataValue>;
public asyncRefresh(...args: any[]): any {
if (this.$dataValue.statusCode.isGoodish()) {
this.verifyVariantCompatibility(this.$dataValue.value);
}
const oldestDate = args[0] as PreciseClock;
const callback = args[1] as CallbackT<DataValue>;
const lessOrEqual = (a: PreciseClock, b: PreciseClock) => {
return (
a.timestamp.getTime() < b.timestamp.getTime() ||
(a.timestamp.getTime() === b.timestamp.getTime() && a.picoseconds <= b.picoseconds)
);
};
if (!this.refreshFunc) {
// no refresh func
const dataValue = this.readValue();
dataValue.serverTimestamp = oldestDate.timestamp;
dataValue.serverPicoseconds = oldestDate.picoseconds;
const serverClock = coerceClock(dataValue.serverTimestamp, dataValue.serverPicoseconds);
if (lessOrEqual(oldestDate, serverClock)) {
return callback(null, dataValue);
} else {
// fake
return callback(null, dataValue);
}
}
const c1 = this.$dataValue.serverTimestamp
? coerceClock(this.$dataValue.serverTimestamp, this.$dataValue.serverPicoseconds)
: null;
if (this.$dataValue.serverTimestamp && lessOrEqual(oldestDate, c1!)) {
const dataValue = this.readValue().clone();
dataValue.serverTimestamp = oldestDate.timestamp;
dataValue.serverPicoseconds = oldestDate.picoseconds;
return callback(null, dataValue);
}
try {
this.refreshFunc.call(this, (err: Error | null, dataValue?: DataValueLike) => {
// istanbul ignore next
if (err || !dataValue) {
errorLog(
"-------------- refresh call failed",
this.browseName.toString(),
this.nodeId.toString(),
err?.message
);
dataValue = { statusCode: StatusCodes.BadNoDataAvailable };
}
if (dataValue && dataValue !== this.$dataValue) {
this._internal_set_dataValue(coerceDataValue(dataValue), null);
}
callback(err, this.$dataValue);
});
} catch (err) {
errorLog("-------------- refresh call failed 2", this.browseName.toString(), this.nodeId.toString());
errorLog(err);
const dataValue = new DataValue({ statusCode: StatusCodes.BadInternalError });
this._internal_set_dataValue(dataValue, null);
callback(err as Error, 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 (typeof value === "string") {
if (!Object.prototype.hasOwnProperty.call(enumInfo.nameIndex, 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: ISessionContext | null,
attributeId: AttributeIds,
indexRange?: NumericRange,
dataEncoding?: QualifiedNameLike | null
): DataValue {
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();
case AttributeIds.AccessLevelEx:
return this._readAccessLevelEx(context);
default:
return BaseNodeImpl.prototype.readAttribute.call(this, context, attributeId);
}
}
public getBasicDataType(): DataType {
if (this._basicDataType) {
return this._basicDataType;
}
if (this.dataType.namespace === 0 && this.dataType.value === 0) {
return DataType.Null;
}
const addressSpace = this.addressSpace;
if (!addressSpace) {
// may be node has been deleted already
return DataType.Null;
}
const dataTypeNode = addressSpace.findDataType(this.dataType)!;
const basicDataType =
dataTypeNode && dataTypeNode.nodeClass === NodeClass.DataType ? dataTypeNode.getBasicDataType() : DataType.Null;
// const basicDataType = addressSpace.findCorrespondingBasicDataType(this.dataType);
this._basicDataType = basicDataType;
return basicDataType;
}
public adjustVariant(variant: Variant): Variant {
return adjustVariant(variant, this.valueRank, this.getBasicDataType());
}
public verifyVariantCompatibility(variant: Variant): void {
try {
// istanbul ignore next
if (Object.prototype.hasOwnProperty.call(variant, "value")) {
if (variant.dataType === null || variant.dataType === undefined) {
throw new Error(
"Variant must provide a valid dataType : variant = " +
variant.toString() +
" this.dataType= " +
this.dataType.toString()
);
}
if (
variant.dataType === DataType.Boolean &&
(this.dataType.namespace !== 0 || this.dataType.value !== DataType.Boolean)
) {
throw new Error(
"Variant must provide a valid Boolean : variant = " +
variant.toString() +
" this.dataType= " +
this.dataType.toString()
);
}
if (
this.dataType.namespace === 0 &&
this.dataType.value === DataType.LocalizedText &&
variant.dataType !== DataType.LocalizedText &&
variant.dataType !== DataType.Null
) {
throw new Error(
"Variant must provide a valid LocalizedText : variant = " +
variant.toString() +
" this.dataType= " +
this.dataType.toString()
);
}
}
const basicType = this.getBasicDataType();
if (basicType === DataType.String && variant.dataType === DataType.ByteString) {
return; // this is allowed
}
if (basicType === DataType.ByteString && variant.dataType === DataType.String) {
return; // this is allowed
}
if (
basicType !== DataType.Null &&
basicType !== DataType.Variant &&
variant.dataType !== DataType.Null &&
variant.dataType !== basicType
) {
const message =
"UAVariable.setValueFromSource " +
this.browseName.toString() +
" nodeId:" +
this.nodeId.toString() +
" dataType:" +
this.dataType.toString() +
":\n" +
"the provided variant must have the expected dataType!\n" +
" - the expected dataType is " +
chalk.cyan(DataType[basicType]) +
"\n" +
" - the actual dataType is " +
chalk.magenta(DataType[variant.dataType]) +
"\n" +
" - " +
variant.toString();
throw new Error(message);
}
} catch (err) {
errorLog("UAVariable ", (err as Error)?.message, this.browseName.toString(), " nodeId=", this.nodeId.toString());
errorLog((err as Error).message);
errorLog((err as Error).stack);
throw err;
}
}
/**
* setValueFromSource is used to let the device sets the variable values
* this method also records the current time as sourceTimestamp and serverTimestamp.
. *
* The method will raise an exception if the value is not compatible with the dataType and expected dimension
*
* @method setValueFromSource
* @param variant {Variant}
* @param [statusCode {StatusCode} = StatusCodes.Good]
* @param [sourceTimestamp= Now]
*/
public setValueFromSource(variant: VariantLike, statusCode?: StatusCode, sourceTimestamp?: Date): void {
try {
statusCode = statusCode || StatusCodes.Good;
const variant1 = Variant.coerce(variant);
this.verifyVariantCompatibility(variant1);
const now = coerceClock(sourceTimestamp, 0);
const dataValue = new DataValue(null);
dataValue.serverPicoseconds = now.picoseconds;
dataValue.serverTimestamp = now.timestamp;
dataValue.sourcePicoseconds = now.picoseconds;
dataValue.sourceTimestamp = now.timestamp;
dataValue.statusCode = statusCode;
dataValue.value = variant1;
if (dataValue.value.dataType === DataType.ExtensionObject) {
const valueIsCorrect = this.checkExtensionObjectIsCorrect(dataValue.value.value);
if (!valueIsCorrect) {
errorLog("setValueFromSource Invalid value !");
errorLog(this.toString());
errorLog(dataValue.toString());
this.checkExtensionObjectIsCorrect(dataValue.value.value);
}
// ----------------------------------
if (this.$extensionObject || this.$$extensionObjectArray) {
// we have an extension object already bound to this node
// the client is asking us to replace the object entierly by a new one
// const ext = dataValue.value.value;
this._internal_set_dataValue(dataValue);
return;
} else {
this.$dataValue = dataValue;
}
} else {
this._internal_set_dataValue(dataValue);
}
} catch (err) {
errorLog("UAVariable#setValueFromString Error : ", this.browseName.toString(), this.nodeId.toString());
errorLog((err as Error).message);
errorLog(this.parent?.toString());
throw err;
}
}
public writeValue(
context: ISessionContext,
dataValue: DataValue,
indexRange: string | NumericRange | null,
callback: StatusCodeCallback
): void;
public writeValue(context: ISessionContext, dataValue: DataValue, callback: StatusCodeCallback): void;
public writeValue(
context: ISessionContext,
dataValue: DataValue,
indexRange?: string | NumericRange | null
): Promise<StatusCode>;
public writeValue(context: ISessionContext, dataValue: DataValue, ...args: any[]): any {
context = context || SessionContext.defaultContext;
assert(context instanceof SessionContext);
if (!dataValue.sourceTimestamp) {
// source timestamp was not specified by the caller
// we will set the timestamp ourself with the current clock
if (context.currentTime) {
dataValue.sourceTimestamp = context.currentTime.timestamp;
dataValue.sourcePicoseconds = context.currentTime.picoseconds;
} else {
const { timestamp, picoseconds } = getCurrentClock();
dataValue.sourceTimestamp = timestamp;
dataValue.sourcePicoseconds = picoseconds;
}
}
if (context.currentTime && !dataValue.serverTimestamp) {
dataValue.serverTimestamp = context.currentTime.timestamp;
dataValue.serverPicoseconds = context.currentTime.picoseconds;
}
// 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(typeof callback === "function");
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.checkPermissionPrivate(context, PermissionType.Write)) {
return new DataValue({ statusCode: StatusCodes.BadUserAccessDenied });
}
if (!this.isUserWritable(context)) {
return callback!(null, StatusCodes.BadWriteNotSupported);
}
// adjust special case
const variant = adjustVariant2.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 || default_func;
if (!write_func) {
warningLog(" warning " + this.nodeId.toString() + " " + this.browseName.toString() + " has no setter. \n");
warningLog("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, (err?: Error | null, statusCode1?: StatusCode) => {
if (!err) {
dataValue && this.verifyVariantCompatibility(dataValue.value);
if (indexRange && !indexRange.isEmpty()) {
if (!indexRange.isValid()) {
return callback!(null, StatusCodes.BadIndexRangeInvalid);
}
const newArrayOrMatrix = dataValue.value.value;
if (dataValue.value.arrayType === VariantArrayType.Array) {
if (this.$dataValue.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, newArrayOrMatrix);
if (result.statusCode.isNot(StatusCodes.Good)) {
return callback!(null, result.statusCode);
}
dataValue.value.value = result.array;
// scrap original array so we detect range
this.$dataValue.value.value = null;
} else if (dataValue.value.arrayType === VariantArrayType.Matrix) {
const dimensions = this.$dataValue.value.dimensions;
if (this.$dataValue.value.arrayType !== VariantArrayType.Matrix || !dimensions) {
// not a matrix !
return callback!(null, StatusCodes.BadTypeMismatch);
}
const matrix = this.$dataValue.value.value;
const result = indexRange.set_values_matrix(
{
matrix,
dimensions
},
newArrayOrMatrix
);
if (result.statusCode.isNot(StatusCodes.Good)) {
return callback!(null, result.statusCode);
}
dataValue.value.dimensions = this.$dataValue.value.dimensions;
dataValue.value.value = result.matrix;
// scrap original array so we detect range
this.$dataValue.value.value = null;
} else {
return callback!(null, StatusCodes.BadTypeMismatch);