node-opcua-client 2.73.1 → 2.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +3 -1
  2. package/README.md +54 -0
  3. package/dist/alarms_and_conditions/client_alarm.d.ts +49 -45
  4. package/dist/alarms_and_conditions/client_alarm.js +109 -101
  5. package/dist/alarms_and_conditions/client_alarm.js.map +1 -1
  6. package/dist/alarms_and_conditions/client_alarm_list.d.ts +25 -25
  7. package/dist/alarms_and_conditions/client_alarm_list.js +97 -97
  8. package/dist/alarms_and_conditions/client_alarm_list.js.map +1 -1
  9. package/dist/alarms_and_conditions/client_alarm_tools.d.ts +4 -4
  10. package/dist/alarms_and_conditions/client_alarm_tools.js +156 -152
  11. package/dist/alarms_and_conditions/client_alarm_tools.js.map +1 -1
  12. package/dist/alarms_and_conditions/client_alarm_tools_acknowledge_all_conditions.d.ts +18 -18
  13. package/dist/alarms_and_conditions/client_alarm_tools_acknowledge_all_conditions.js +192 -190
  14. package/dist/alarms_and_conditions/client_alarm_tools_acknowledge_all_conditions.js.map +1 -1
  15. package/dist/alarms_and_conditions/client_alarm_tools_dump_event.d.ts +9 -9
  16. package/dist/alarms_and_conditions/client_alarm_tools_dump_event.js +73 -73
  17. package/dist/alarms_and_conditions/client_alarm_tools_extractConditionFields.d.ts +3 -8
  18. package/dist/alarms_and_conditions/client_alarm_tools_extractConditionFields.js +118 -120
  19. package/dist/alarms_and_conditions/client_alarm_tools_extractConditionFields.js.map +1 -1
  20. package/dist/alarms_and_conditions/client_tools.d.ts +7 -7
  21. package/dist/alarms_and_conditions/client_tools.js +180 -180
  22. package/dist/client_base.d.ts +277 -277
  23. package/dist/client_base.js +14 -14
  24. package/dist/client_monitored_item.d.ts +21 -21
  25. package/dist/client_monitored_item.js +11 -11
  26. package/dist/client_monitored_item_base.d.ts +39 -39
  27. package/dist/client_monitored_item_base.js +2 -2
  28. package/dist/client_monitored_item_group.d.ts +18 -18
  29. package/dist/client_monitored_item_group.js +13 -13
  30. package/dist/client_monitored_item_toolbox.d.ts +15 -15
  31. package/dist/client_monitored_item_toolbox.js +117 -117
  32. package/dist/client_session.d.ts +484 -484
  33. package/dist/client_session.js +10 -10
  34. package/dist/client_session_keepalive_manager.d.ts +34 -34
  35. package/dist/client_session_keepalive_manager.js +150 -150
  36. package/dist/client_subscription.d.ts +241 -241
  37. package/dist/client_subscription.js +14 -14
  38. package/dist/client_utils.d.ts +22 -22
  39. package/dist/client_utils.js +88 -88
  40. package/dist/common.d.ts +17 -17
  41. package/dist/common.js +5 -5
  42. package/dist/index.d.ts +55 -55
  43. package/dist/index.js +93 -93
  44. package/dist/opcua_client.d.ts +132 -132
  45. package/dist/opcua_client.js +33 -33
  46. package/dist/private/client_base_impl.d.ts +157 -157
  47. package/dist/private/client_base_impl.js +1337 -1337
  48. package/dist/private/client_monitored_item_base_impl.d.ts +3 -3
  49. package/dist/private/client_monitored_item_base_impl.js +4 -4
  50. package/dist/private/client_monitored_item_group_impl.d.ts +53 -53
  51. package/dist/private/client_monitored_item_group_impl.js +159 -159
  52. package/dist/private/client_monitored_item_impl.d.ts +93 -93
  53. package/dist/private/client_monitored_item_impl.js +305 -304
  54. package/dist/private/client_monitored_item_impl.js.map +1 -1
  55. package/dist/private/client_publish_engine.d.ts +62 -62
  56. package/dist/private/client_publish_engine.js +408 -408
  57. package/dist/private/client_session_impl.d.ts +621 -621
  58. package/dist/private/client_session_impl.js +1302 -1301
  59. package/dist/private/client_session_impl.js.map +1 -1
  60. package/dist/private/client_subscription_impl.d.ts +93 -93
  61. package/dist/private/client_subscription_impl.js +748 -743
  62. package/dist/private/client_subscription_impl.js.map +1 -1
  63. package/dist/private/i_private_client.d.ts +18 -18
  64. package/dist/private/i_private_client.js +2 -2
  65. package/dist/private/opcua_client_impl.d.ts +169 -169
  66. package/dist/private/opcua_client_impl.js +981 -981
  67. package/dist/reconnection.d.ts +9 -9
  68. package/dist/reconnection.js +408 -408
  69. package/dist/tools/findservers.d.ts +20 -20
  70. package/dist/tools/findservers.js +61 -61
  71. package/dist/tools/read_history_server_capabilities.d.ts +6 -6
  72. package/dist/tools/read_history_server_capabilities.js +99 -99
  73. package/dist/verify.d.ts +5 -5
  74. package/dist/verify.js +134 -134
  75. package/package.json +48 -48
  76. package/source/alarms_and_conditions/client_alarm.ts +28 -17
  77. package/source/alarms_and_conditions/client_alarm_list.ts +1 -0
  78. package/source/alarms_and_conditions/client_alarm_tools.ts +33 -23
  79. package/source/alarms_and_conditions/client_alarm_tools_acknowledge_all_conditions.ts +10 -4
  80. package/source/alarms_and_conditions/client_alarm_tools_extractConditionFields.ts +11 -11
  81. package/source/private/client_monitored_item_impl.ts +4 -3
  82. package/source/private/client_session_impl.ts +10 -2
  83. package/source/private/client_subscription_impl.ts +6 -2
@@ -1,1302 +1,1303 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.ClientSessionImpl = void 0;
13
- /**
14
- * @module node-opcua-client-private
15
- */
16
- const events_1 = require("events");
17
- const chalk = require("chalk");
18
- const node_opcua_assert_1 = require("node-opcua-assert");
19
- const node_opcua_client_dynamic_extension_object_1 = require("node-opcua-client-dynamic-extension-object");
20
- const node_opcua_data_model_1 = require("node-opcua-data-model");
21
- const node_opcua_data_value_1 = require("node-opcua-data-value");
22
- const node_opcua_debug_1 = require("node-opcua-debug");
23
- const node_opcua_nodeid_1 = require("node-opcua-nodeid");
24
- const node_opcua_pseudo_session_1 = require("node-opcua-pseudo-session");
25
- const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
26
- const node_opcua_service_browse_1 = require("node-opcua-service-browse");
27
- const node_opcua_service_call_1 = require("node-opcua-service-call");
28
- const node_opcua_service_history_1 = require("node-opcua-service-history");
29
- const node_opcua_service_query_1 = require("node-opcua-service-query");
30
- const node_opcua_service_read_1 = require("node-opcua-service-read");
31
- const node_opcua_service_register_node_1 = require("node-opcua-service-register-node");
32
- const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
33
- const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
34
- const node_opcua_service_write_1 = require("node-opcua-service-write");
35
- const node_opcua_status_code_1 = require("node-opcua-status-code");
36
- const node_opcua_types_1 = require("node-opcua-types");
37
- const node_opcua_utils_1 = require("node-opcua-utils");
38
- const node_opcua_variant_1 = require("node-opcua-variant");
39
- const client_session_keepalive_manager_1 = require("../client_session_keepalive_manager");
40
- const reconnection_1 = require("../reconnection");
41
- const client_publish_engine_1 = require("./client_publish_engine");
42
- const client_subscription_impl_1 = require("./client_subscription_impl");
43
- const helpAPIChange = process.env.DEBUG && process.env.DEBUG.match(/API/);
44
- const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
45
- const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
46
- const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
47
- const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
48
- let pendingTransactionMessageDisplayed = false;
49
- function coerceBrowseDescription(data) {
50
- if (typeof data === "string" || data instanceof node_opcua_nodeid_1.NodeId) {
51
- return coerceBrowseDescription({
52
- browseDirection: node_opcua_data_model_1.BrowseDirection.Forward,
53
- includeSubtypes: true,
54
- nodeClassMask: 0,
55
- nodeId: data,
56
- referenceTypeId: "HierarchicalReferences",
57
- resultMask: 63
58
- });
59
- }
60
- else {
61
- data.nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(data.nodeId);
62
- data.referenceTypeId = data.referenceTypeId ? (0, node_opcua_nodeid_1.resolveNodeId)(data.referenceTypeId) : null;
63
- return new node_opcua_service_browse_1.BrowseDescription(data);
64
- }
65
- }
66
- function coerceReadValueId(node) {
67
- if (typeof node === "string" || node instanceof node_opcua_nodeid_1.NodeId) {
68
- return new node_opcua_service_read_1.ReadValueId({
69
- attributeId: node_opcua_service_read_1.AttributeIds.Value,
70
- dataEncoding: undefined,
71
- indexRange: undefined,
72
- nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(node)
73
- });
74
- }
75
- else {
76
- (0, node_opcua_assert_1.assert)(node instanceof Object);
77
- return new node_opcua_service_read_1.ReadValueId(node);
78
- }
79
- }
80
- const keys = Object.keys(node_opcua_service_read_1.AttributeIds).filter((k) => node_opcua_service_read_1.AttributeIds[k] !== node_opcua_service_read_1.AttributeIds.INVALID);
81
- const attributeNames = (() => {
82
- const r = [];
83
- for (let i = 1; i <= 22; i++) {
84
- r.push(node_opcua_data_model_1.attributeNameById[i].toString());
85
- }
86
- return r;
87
- })();
88
- function composeResult(nodes, nodesToRead, dataValues) {
89
- (0, node_opcua_assert_1.assert)(nodesToRead.length === dataValues.length);
90
- let c = 0;
91
- const results = [];
92
- let dataValue;
93
- let k;
94
- let nodeToRead;
95
- for (const node of nodes) {
96
- const data = {
97
- nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(node),
98
- statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown
99
- };
100
- let addedProperty = 0;
101
- for (const key of attributeNames) {
102
- dataValue = dataValues[c];
103
- nodeToRead = nodesToRead[c];
104
- c++;
105
- if (dataValue.statusCode.equals(node_opcua_status_code_1.StatusCodes.Good)) {
106
- k = (0, node_opcua_utils_1.lowerFirstLetter)(key);
107
- data[k] = dataValue.value ? dataValue.value.value : null;
108
- addedProperty += 1;
109
- }
110
- }
111
- /* istanbul ignore if */
112
- if (addedProperty > 0) {
113
- data.statusCode = node_opcua_status_code_1.StatusCodes.Good;
114
- }
115
- else {
116
- data.statusCode = node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown;
117
- }
118
- results.push(data);
119
- }
120
- return results;
121
- }
122
- const emptyUint32Array = new Uint32Array(0);
123
- /**
124
- * @class ClientSession
125
- * @param client {OPCUAClientImpl}
126
- * @constructor
127
- * @private
128
- */
129
- class ClientSessionImpl extends events_1.EventEmitter {
130
- constructor(client) {
131
- super();
132
- this.name = "";
133
- this.serverEndpoints = [];
134
- this.recursive_repair_detector = 0;
135
- this.processTransactionQueue = (request, callback) => {
136
- this._reconnecting.pendingTransactionsCount = this._reconnecting.pendingTransactionsCount || 0;
137
- this._reconnecting.pendingTransactionsCount++;
138
- this._performMessageTransaction(request, (err, response) => {
139
- this._reconnecting.pendingTransactionsCount--;
140
- if (err && err.message.match(/BadSessionIdInvalid/) && request.constructor.name !== "ActivateSessionRequest") {
141
- debugLog("Transaction on Invalid Session ", request.constructor.name);
142
- request.requestHeader.requestHandle = node_opcua_secure_channel_1.requestHandleNotSetValue;
143
- this.recreate_session_and_reperform_transaction(request, callback);
144
- return;
145
- }
146
- callback(err, response);
147
- const length = this._reconnecting.pendingTransactions.length; // record length before callback is called !
148
- if (length > 0) {
149
- debugLog("processTransactionQueue => ", this._reconnecting.pendingTransactions.length, " transaction(s) left in queue");
150
- // tslint:disable-next-line: no-shadowed-variable
151
- const { request, callback } = this._reconnecting.pendingTransactions.shift();
152
- this.processTransactionQueue(request, callback);
153
- }
154
- });
155
- };
156
- this.serverCertificate = Buffer.alloc(0);
157
- this.sessionId = new node_opcua_nodeid_1.NodeId();
158
- this._closeEventHasBeenEmitted = false;
159
- this._client = client;
160
- this._publishEngine = null;
161
- this._closed = false;
162
- this._reconnecting = {
163
- reconnecting: false,
164
- pendingCallbacks: [],
165
- pendingTransactions: [],
166
- pendingTransactionsCount: 0
167
- };
168
- this.requestedMaxReferencesPerNode = 10000;
169
- this.lastRequestSentTime = new Date(1, 1, 1970);
170
- this.lastResponseReceivedTime = new Date(1, 1, 1970);
171
- this.timeout = 0;
172
- }
173
- /**
174
- * the endpoint on which this session is operating
175
- * @property endpoint
176
- * @type {EndpointDescription}
177
- */
178
- get endpoint() {
179
- return this._client.endpoint;
180
- }
181
- get subscriptionCount() {
182
- return this._publishEngine ? this._publishEngine.subscriptionCount : 0;
183
- }
184
- get isReconnecting() {
185
- var _a;
186
- return this._client ? this._client.isReconnecting || ((_a = this._reconnecting) === null || _a === void 0 ? void 0 : _a.reconnecting) : false;
187
- }
188
- getPublishEngine() {
189
- if (!this._publishEngine) {
190
- this._publishEngine = new client_publish_engine_1.ClientSidePublishEngine(this);
191
- }
192
- return this._publishEngine;
193
- }
194
- /**
195
- * @internal
196
- * @param args
197
- */
198
- browse(...args) {
199
- const arg0 = args[0];
200
- const isArray = Array.isArray(arg0);
201
- const callback = args[1];
202
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
203
- (0, node_opcua_assert_1.assert)(isFinite(this.requestedMaxReferencesPerNode));
204
- const nodesToBrowse = (isArray ? arg0 : [arg0]).map(coerceBrowseDescription);
205
- const request = new node_opcua_service_browse_1.BrowseRequest({
206
- nodesToBrowse,
207
- requestedMaxReferencesPerNode: this.requestedMaxReferencesPerNode
208
- });
209
- this.performMessageTransaction(request, (err, response) => {
210
- if (err) {
211
- return callback(err);
212
- }
213
- /* istanbul ignore next */
214
- if (!response || !(response instanceof node_opcua_service_browse_1.BrowseResponse)) {
215
- return callback(new Error("Internal Error"));
216
- }
217
- const results = response.results ? response.results : [];
218
- if (this.requestedMaxReferencesPerNode > 0) {
219
- for (let i = 0; i < results.length; i++) {
220
- const r = results[i];
221
- /* istanbul ignore next */
222
- if (r.references && r.references.length > this.requestedMaxReferencesPerNode) {
223
- warningLog(chalk.yellow("warning") +
224
- " BrowseResponse : the server didn't take into" +
225
- " account our requestedMaxReferencesPerNode ");
226
- warningLog(" this.requestedMaxReferencesPerNode= " + this.requestedMaxReferencesPerNode);
227
- warningLog(" got " + r.references.length + "for " + nodesToBrowse[i].nodeId.toString());
228
- warningLog(" continuationPoint ", r.continuationPoint);
229
- }
230
- }
231
- }
232
- for (const r of results) {
233
- r.references = r.references || /* istanbul ignore next */ [];
234
- }
235
- (0, node_opcua_assert_1.assert)(results[0] instanceof node_opcua_service_browse_1.BrowseResult);
236
- return callback(null, isArray ? results : results[0]);
237
- });
238
- }
239
- browseNext(...args) {
240
- const arg0 = args[0];
241
- const isArray = Array.isArray(arg0);
242
- const releaseContinuationPoints = args[1];
243
- const callback = args[2];
244
- (0, node_opcua_assert_1.assert)(typeof callback === "function", "expecting a callback function here");
245
- const continuationPoints = isArray ? arg0 : [arg0];
246
- const request = new node_opcua_types_1.BrowseNextRequest({
247
- continuationPoints,
248
- releaseContinuationPoints
249
- });
250
- this.performMessageTransaction(request, (err, response) => {
251
- /* istanbul ignore next */
252
- if (err) {
253
- return callback(err);
254
- }
255
- /* istanbul ignore next */
256
- if (!response || !(response instanceof node_opcua_types_1.BrowseNextResponse)) {
257
- return callback(new Error("Internal Error"));
258
- }
259
- const results = response.results ? response.results : [];
260
- for (const r of results) {
261
- r.references = r.references || [];
262
- }
263
- (0, node_opcua_assert_1.assert)(results[0] instanceof node_opcua_service_browse_1.BrowseResult);
264
- return callback(null, isArray ? results : results[0]);
265
- });
266
- }
267
- /**
268
- * @internal
269
- * @param args
270
- */
271
- readVariableValue(...args) {
272
- const callback = args[1];
273
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
274
- const isArray = Array.isArray(args[0]);
275
- const nodes = isArray ? args[0] : [args[0]];
276
- const nodesToRead = nodes.map(coerceReadValueId);
277
- const request = new node_opcua_service_read_1.ReadRequest({
278
- nodesToRead,
279
- timestampsToReturn: node_opcua_service_read_1.TimestampsToReturn.Neither
280
- });
281
- this.performMessageTransaction(request, (err, response) => {
282
- /* istanbul ignore next */
283
- if (err) {
284
- return callback(err);
285
- }
286
- /* istanbul ignore next */
287
- if (!(response instanceof node_opcua_service_read_1.ReadResponse)) {
288
- return callback(new Error("Internal Error"));
289
- }
290
- /* istanbul ignore next */
291
- if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
292
- return callback(new Error(response.responseHeader.serviceResult.toString()));
293
- }
294
- /* istanbul ignore next */
295
- if (!response.results) {
296
- response.results = [];
297
- }
298
- (0, node_opcua_assert_1.assert)(nodes.length === response.results.length);
299
- callback(null, isArray ? response.results : response.results[0]);
300
- });
301
- }
302
- readHistoryValue(...args) {
303
- const startTime = args[1];
304
- const endTime = args[2];
305
- let options = {};
306
- let callback = args[3];
307
- if (typeof callback !== "function") {
308
- options = args[3];
309
- callback = args[4];
310
- }
311
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
312
- // adjust parameters
313
- options.numValuesPerNode = options.numValuesPerNode || 0;
314
- options.returnBounds = options.returnBounds || options.returnBounds === undefined ? true : false;
315
- options.isReadModified = options.isReadModified || false;
316
- options.timestampsToReturn = options.timestampsToReturn || node_opcua_service_read_1.TimestampsToReturn.Both;
317
- const arg0 = args[0];
318
- const isArray = Array.isArray(arg0);
319
- const nodes = isArray ? arg0 : [arg0];
320
- const nodesToRead = [];
321
- for (const node of nodes) {
322
- if (!node.nodeId) {
323
- nodesToRead.push({
324
- continuationPoint: undefined,
325
- dataEncoding: undefined,
326
- indexRange: undefined,
327
- nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(node)
328
- });
329
- }
330
- else {
331
- nodesToRead.push(node);
332
- }
333
- }
334
- const readRawModifiedDetails = new node_opcua_service_history_1.ReadRawModifiedDetails({
335
- endTime,
336
- isReadModified: false,
337
- numValuesPerNode: options.numValuesPerNode,
338
- returnBounds: options.returnBounds,
339
- startTime
340
- });
341
- const request = new node_opcua_service_history_1.HistoryReadRequest({
342
- historyReadDetails: readRawModifiedDetails,
343
- nodesToRead,
344
- releaseContinuationPoints: false,
345
- timestampsToReturn: options.timestampsToReturn
346
- });
347
- request.nodesToRead = request.nodesToRead || [];
348
- (0, node_opcua_assert_1.assert)(nodes.length === request.nodesToRead.length);
349
- this.historyRead(request, (err, response) => {
350
- /* istanbul ignore next */
351
- if (err) {
352
- return callback(err);
353
- }
354
- /* istanbul ignore next */
355
- if (!response || !(response instanceof node_opcua_service_history_1.HistoryReadResponse)) {
356
- return callback(new Error("Internal Error"));
357
- }
358
- response.results = response.results || [];
359
- (0, node_opcua_assert_1.assert)(nodes.length === response.results.length);
360
- callback(null, isArray ? response.results : response.results[0]);
361
- });
362
- }
363
- historyRead(request, callback) {
364
- /* istanbul ignore next */
365
- if (!callback) {
366
- throw new Error("expecting a callback");
367
- }
368
- this.performMessageTransaction(request, (err, response) => {
369
- /* istanbul ignore next */
370
- if (err) {
371
- return callback(err);
372
- }
373
- /* istanbul ignore next */
374
- if (!response || !(response instanceof node_opcua_service_history_1.HistoryReadResponse)) {
375
- return callback(new Error("Internal Error"));
376
- }
377
- if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
378
- return callback(new Error(response.responseHeader.serviceResult.toString()));
379
- }
380
- response.results = response.results || /* istanbul ignore next */ [];
381
- callback(null, response);
382
- });
383
- }
384
- readAggregateValue(arg0, startTime, endTime, aggregateFn, processingInterval, ...args) {
385
- const callback = args[0];
386
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
387
- const isArray = Array.isArray(arg0);
388
- const nodesToRead = isArray
389
- ? arg0
390
- : [arg0];
391
- const aggregateFns = Array.isArray(aggregateFn)
392
- ? aggregateFn
393
- : [aggregateFn];
394
- (0, node_opcua_assert_1.assert)(aggregateFns.length === nodesToRead.length);
395
- const readProcessedDetails = new node_opcua_service_history_1.ReadProcessedDetails({
396
- aggregateType: aggregateFns,
397
- endTime,
398
- processingInterval,
399
- startTime
400
- });
401
- const request = new node_opcua_service_history_1.HistoryReadRequest({
402
- historyReadDetails: readProcessedDetails,
403
- nodesToRead,
404
- releaseContinuationPoints: false,
405
- timestampsToReturn: node_opcua_service_read_1.TimestampsToReturn.Both
406
- });
407
- (0, node_opcua_assert_1.assert)(nodesToRead.length === request.nodesToRead.length);
408
- this.performMessageTransaction(request, (err, response) => {
409
- /* istanbul ignore next */
410
- if (err) {
411
- return callback(err);
412
- }
413
- /* istanbul ignore next */
414
- if (!response || !(response instanceof node_opcua_service_history_1.HistoryReadResponse)) {
415
- return callback(new Error("Internal Error"));
416
- }
417
- if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
418
- return callback(new Error(response.responseHeader.serviceResult.toString()));
419
- }
420
- response.results = response.results || /* istanbul ignore next */ [];
421
- (0, node_opcua_assert_1.assert)(nodesToRead.length === response.results.length);
422
- callback(null, isArray ? response.results : response.results[0]);
423
- });
424
- }
425
- /**
426
- * @internal
427
- * @param args
428
- */
429
- write(...args) {
430
- const arg0 = args[0];
431
- const isArray = Array.isArray(arg0);
432
- const nodesToWrite = isArray ? arg0 : [arg0];
433
- const callback = args[1];
434
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
435
- const request = new node_opcua_service_write_1.WriteRequest({ nodesToWrite });
436
- this.performMessageTransaction(request, (err, response) => {
437
- /* istanbul ignore next */
438
- if (err) {
439
- return callback(err, response);
440
- }
441
- /* istanbul ignore next */
442
- if (!response || !(response instanceof node_opcua_service_write_1.WriteResponse)) {
443
- return callback(new Error("Internal Error"));
444
- }
445
- /* istanbul ignore next */
446
- if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
447
- return callback(new Error(response.responseHeader.serviceResult.toString()));
448
- }
449
- response.results = response.results || /* istanbul ignore next */ [];
450
- (0, node_opcua_assert_1.assert)(nodesToWrite.length === response.results.length);
451
- callback(null, isArray ? response.results : response.results[0]);
452
- });
453
- }
454
- writeSingleNode(...args) {
455
- const nodeId = args[0];
456
- const value = args[1];
457
- const callback = args[2];
458
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
459
- const nodeToWrite = new node_opcua_service_write_1.WriteValue({
460
- attributeId: node_opcua_service_read_1.AttributeIds.Value,
461
- indexRange: undefined,
462
- nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(nodeId),
463
- value: new node_opcua_data_value_1.DataValue({ value })
464
- });
465
- this.write(nodeToWrite, (err, statusCode) => {
466
- /* istanbul ignore next */
467
- if (err) {
468
- return callback(err);
469
- }
470
- (0, node_opcua_assert_1.assert)(statusCode);
471
- callback(null, statusCode);
472
- });
473
- }
474
- readAllAttributes(...args) {
475
- const arg0 = args[0];
476
- const callback = args[1];
477
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
478
- const isArray = Array.isArray(arg0);
479
- const nodes = isArray ? arg0 : [arg0];
480
- const nodesToRead = [];
481
- for (const node of nodes) {
482
- const nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(node);
483
- /* istanbul ignore next */
484
- if (!nodeId) {
485
- throw new Error("cannot coerce " + node + " to a valid NodeId");
486
- }
487
- for (let attributeId = 1; attributeId <= 22; attributeId++) {
488
- nodesToRead.push({
489
- attributeId,
490
- dataEncoding: undefined,
491
- indexRange: undefined,
492
- nodeId
493
- });
494
- }
495
- }
496
- this.read(nodesToRead, (err, dataValues) => {
497
- /* istanbul ignore next */
498
- if (err) {
499
- return callback(err);
500
- }
501
- /* istanbul ignore next */
502
- if (!dataValues) {
503
- return callback(new Error("Internal Error"));
504
- }
505
- const results = composeResult(nodes, nodesToRead, dataValues);
506
- callback(err, isArray ? results : results[0]);
507
- });
508
- }
509
- /**
510
- * @internal
511
- * @param args
512
- */
513
- read(...args) {
514
- if (args.length === 2) {
515
- return this.read(args[0], 0, args[1]);
516
- }
517
- (0, node_opcua_assert_1.assert)(args.length === 3);
518
- const isArray = Array.isArray(args[0]);
519
- const nodesToRead = isArray ? args[0] : [args[0]];
520
- (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRead));
521
- const maxAge = args[1];
522
- const callback = args[2];
523
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
524
- /* istanbul ignore next */
525
- if (helpAPIChange) {
526
- // the read method deprecation detection and warning
527
- if (!((0, node_opcua_utils_1.getFunctionParameterNames)(callback)[1] === "dataValues" || (0, node_opcua_utils_1.getFunctionParameterNames)(callback)[1] === "dataValue")) {
528
- warningLog(chalk.red("[NODE-OPCUA-E04] the ClientSession#read API has changed !!, please fix the client code"));
529
- warningLog(chalk.red(" replace ..:"));
530
- warningLog(chalk.cyan(" session.read(nodesToRead,function(err,nodesToRead,results) {}"));
531
- warningLog(chalk.red(" with .... :"));
532
- warningLog(chalk.cyan(" session.read(nodesToRead,function(err,dataValues) {}"));
533
- warningLog("");
534
- warningLog(chalk.yellow("please make sure to refactor your code and check that " +
535
- "the second argument of your callback function is named"), chalk.cyan("dataValue" + (isArray ? "s" : "")));
536
- warningLog(chalk.cyan("to make this exception disappear"));
537
- throw new Error("ERROR ClientSession#read API has changed !!, please fix the client code");
538
- }
539
- }
540
- // coerce nodeIds
541
- for (const node of nodesToRead) {
542
- node.nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(node.nodeId);
543
- }
544
- const request = new node_opcua_service_read_1.ReadRequest({
545
- maxAge,
546
- nodesToRead,
547
- timestampsToReturn: node_opcua_service_read_1.TimestampsToReturn.Both
548
- });
549
- this.performMessageTransaction(request, (err, response) => {
550
- /* istanbul ignore next */
551
- if (err) {
552
- return callback(err, response);
553
- }
554
- /* istanbul ignore next */
555
- if (!response || !(response instanceof node_opcua_service_read_1.ReadResponse)) {
556
- return callback(new Error("Internal Error"));
557
- }
558
- // perform ExtensionObject resolution
559
- promoteOpaqueStructureWithCallback(this, response.results, () => {
560
- response.results = response.results || /* istanbul ignore next */ [];
561
- return callback(null, isArray ? response.results : response.results[0]);
562
- });
563
- });
564
- }
565
- emitCloseEvent(statusCode) {
566
- if (!this._closeEventHasBeenEmitted) {
567
- debugLog("ClientSession#emitCloseEvent");
568
- this._closeEventHasBeenEmitted = true;
569
- this.emit("session_closed", statusCode);
570
- }
571
- }
572
- createSubscription(options, callback) {
573
- this._defaultRequest(node_opcua_service_subscription_1.CreateSubscriptionRequest, node_opcua_service_subscription_1.CreateSubscriptionResponse, options, callback);
574
- }
575
- createSubscription2(...args) {
576
- const createSubscriptionRequest = args[0];
577
- let callback = args[1];
578
- const subscription = new client_subscription_impl_1.ClientSubscriptionImpl(this, createSubscriptionRequest);
579
- // tslint:disable-next-line:no-empty
580
- subscription.on("error", (err) => {
581
- if (callback) {
582
- callback(err);
583
- callback = null;
584
- }
585
- });
586
- subscription.on("started", () => {
587
- (0, node_opcua_assert_1.assert)(subscription.session === this, "expecting a session here");
588
- if (callback) {
589
- callback(null, subscription);
590
- callback = null;
591
- }
592
- });
593
- }
594
- deleteSubscriptions(options, callback) {
595
- this._defaultRequest(node_opcua_service_subscription_1.DeleteSubscriptionsRequest, node_opcua_service_subscription_1.DeleteSubscriptionsResponse, options, callback);
596
- }
597
- setTriggering(request, callback) {
598
- this._defaultRequest(node_opcua_service_subscription_1.SetTriggeringRequest, node_opcua_service_subscription_1.SetTriggeringResponse, request, callback);
599
- }
600
- /**
601
- * @method transferSubscriptions
602
- * @async
603
- */
604
- transferSubscriptions(options, callback) {
605
- this._defaultRequest(node_opcua_service_subscription_1.TransferSubscriptionsRequest, node_opcua_service_subscription_1.TransferSubscriptionsResponse, options, callback);
606
- }
607
- createMonitoredItems(options, callback) {
608
- this._defaultRequest(node_opcua_service_subscription_1.CreateMonitoredItemsRequest, node_opcua_service_subscription_1.CreateMonitoredItemsResponse, options, callback);
609
- }
610
- modifyMonitoredItems(options, callback) {
611
- this._defaultRequest(node_opcua_service_subscription_1.ModifyMonitoredItemsRequest, node_opcua_service_subscription_1.ModifyMonitoredItemsResponse, options, callback);
612
- }
613
- /**
614
- *
615
- * @method modifySubscription
616
- * @async
617
- * @param options {ModifySubscriptionRequest}
618
- * @param callback {Function}
619
- * @param callback.err {Error|null} - the Error if the async method has failed
620
- * @param callback.response {ModifySubscriptionResponse} - the response
621
- */
622
- modifySubscription(options, callback) {
623
- this._defaultRequest(node_opcua_service_subscription_1.ModifySubscriptionRequest, node_opcua_service_subscription_1.ModifySubscriptionResponse, options, callback);
624
- }
625
- setMonitoringMode(options, callback) {
626
- this._defaultRequest(node_opcua_service_subscription_1.SetMonitoringModeRequest, node_opcua_service_subscription_1.SetMonitoringModeResponse, options, callback);
627
- }
628
- /**
629
- *
630
- * @method publish
631
- * @async
632
- * @param options {PublishRequest}
633
- * @param callback {Function}
634
- * @param callback.err {Error|null} - the Error if the async method has failed
635
- * @param callback.response {PublishResponse} - the response
636
- */
637
- publish(options, callback) {
638
- this._defaultRequest(node_opcua_service_subscription_1.PublishRequest, node_opcua_service_subscription_1.PublishResponse, options, callback);
639
- }
640
- /**
641
- *
642
- * @method republish
643
- * @async
644
- * @param options {RepublishRequest}
645
- * @param callback the callback
646
- */
647
- republish(options, callback) {
648
- this._defaultRequest(node_opcua_service_subscription_1.RepublishRequest, node_opcua_service_subscription_1.RepublishResponse, options, callback);
649
- }
650
- /**
651
- *
652
- * @method deleteMonitoredItems
653
- * @async
654
- * @param options {DeleteMonitoredItemsRequest}
655
- * @param callback {Function}
656
- * @param callback.err {Error|null} - the Error if the async method has failed
657
- */
658
- deleteMonitoredItems(options, callback) {
659
- this._defaultRequest(node_opcua_service_subscription_1.DeleteMonitoredItemsRequest, node_opcua_service_subscription_1.DeleteMonitoredItemsResponse, options, callback);
660
- }
661
- /**
662
- * @internal
663
- */
664
- setPublishingMode(...args) {
665
- const publishingEnabled = args[0];
666
- const isArray = Array.isArray(args[1]);
667
- const subscriptionIds = isArray ? args[1] : [args[1]];
668
- const callback = args[2];
669
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
670
- (0, node_opcua_assert_1.assert)(publishingEnabled === true || publishingEnabled === false);
671
- const options = new node_opcua_service_subscription_1.SetPublishingModeRequest({
672
- publishingEnabled,
673
- subscriptionIds
674
- });
675
- this._defaultRequest(node_opcua_service_subscription_1.SetPublishingModeRequest, node_opcua_service_subscription_1.SetPublishingModeResponse, options, (err, response) => {
676
- /* istanbul ignore next */
677
- if (err) {
678
- return callback(err);
679
- }
680
- /* istanbul ignore next */
681
- if (!response) {
682
- return callback(new Error("Internal Error"));
683
- }
684
- response.results = response.results || /* istanbul ignore next */ [];
685
- callback(err, isArray ? response.results : response.results[0]);
686
- });
687
- }
688
- /**
689
- * @internal
690
- * @param args
691
- */
692
- translateBrowsePath(...args) {
693
- const isArray = Array.isArray(args[0]);
694
- const browsePaths = isArray ? args[0] : [args[0]];
695
- const callback = args[1];
696
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
697
- const request = new node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsRequest({ browsePaths });
698
- this.performMessageTransaction(request, (err, response) => {
699
- /* istanbul ignore next */
700
- if (err) {
701
- return callback(err, response);
702
- }
703
- /* istanbul ignore next */
704
- if (!response || !(response instanceof node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse)) {
705
- return callback(new Error("Internal Error"));
706
- }
707
- response.results = response.results || /* istanbul ignore next */ [];
708
- callback(null, isArray ? response.results : response.results[0]);
709
- });
710
- }
711
- channelId() {
712
- return this._client !== null && this._client._secureChannel !== null && this._client._secureChannel.isOpened()
713
- ? this._client._secureChannel.channelId
714
- : -1;
715
- }
716
- isChannelValid() {
717
- /* istanbul ignore next */
718
- if (!this._client) {
719
- debugLog(chalk.red("Warning SessionClient is null ?"));
720
- }
721
- return this._client !== null && this._client._secureChannel !== null && this._client._secureChannel.isOpened();
722
- }
723
- performMessageTransaction(request, callback) {
724
- if (!this._client) {
725
- // session may have been closed by user ... but is still in used !!
726
- return callback(new Error("Session has been closed and should not be used to perform a transaction anymore"));
727
- }
728
- if (!this.isChannelValid()) {
729
- // the secure channel is broken, may be the server has crashed or the network cable has been disconnected
730
- // for a long time
731
- // we may need to queue this transaction, as a secure token may be being reprocessed
732
- debugLog(chalk.bgWhite.red("!!! Performing transaction on invalid channel !!! ", request.constructor.name));
733
- return callback(new Error("Invalid Channel after performing transaction on " + request.constructor.name));
734
- }
735
- this._reconnecting.pendingTransactions = this._reconnecting.pendingTransactions || [];
736
- this._reconnecting.pendingTransactionsCount = this._reconnecting.pendingTransactionsCount || 0;
737
- const isPublishRequest = request instanceof node_opcua_service_subscription_1.PublishRequest;
738
- if (isPublishRequest) {
739
- return this._performMessageTransaction(request, callback);
740
- }
741
- if (this._reconnecting.pendingTransactionsCount > 0) {
742
- /* istanbul ignore next */
743
- if (this._reconnecting.pendingTransactions.length > 10) {
744
- if (!pendingTransactionMessageDisplayed) {
745
- pendingTransactionMessageDisplayed = true;
746
- warningLog("[NODE-OPCUA-W21]", "Pending transactions: ", this._reconnecting.pendingTransactions.map((a) => a.request.constructor.name).join(" "));
747
- warningLog("[NODE-OPCUA-W22]", chalk.yellow("Warning : your opcua client is sending multiple requests simultaneously to the server", request.constructor.name), "\n", chalk.yellow(" please fix your application code"));
748
- }
749
- }
750
- else if (this._reconnecting.pendingTransactions.length > 3) {
751
- debugLog(chalk.yellow("Warning : your client is sending multiple requests simultaneously to the server", request.constructor.name));
752
- }
753
- this._reconnecting.pendingTransactions.push({ request, callback });
754
- return;
755
- }
756
- this.processTransactionQueue(request, callback);
757
- }
758
- _performMessageTransaction(request, callback) {
759
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
760
- /* istanbul ignore next */
761
- if (!this._client) {
762
- // session may have been closed by user ... but is still in used !!
763
- return callback(new Error("Session has been closed and should not be used to perform a transaction anymore"));
764
- }
765
- if (!this.isChannelValid()) {
766
- // the secure channel is broken, may be the server has crashed or the network cable has been disconnected
767
- // for a long time
768
- // we may need to queue this transaction, as a secure token may be being reprocessed
769
- debugLog(chalk.bgWhite.red("!!! Performing transaction on invalid channel !!! ", request.constructor.name));
770
- return callback(new Error("Invalid Channel BadConnectionClosed"));
771
- }
772
- // is this stuff useful?
773
- if (request.requestHeader) {
774
- request.requestHeader.authenticationToken = this.authenticationToken;
775
- }
776
- this.lastRequestSentTime = new Date();
777
- this._client.performMessageTransaction(request, (err, response) => {
778
- this.lastResponseReceivedTime = new Date();
779
- /* istanbul ignore next */
780
- if (err) {
781
- if (response && response.responseHeader.serviceDiagnostics) {
782
- err.serviceDiagnostics = response.responseHeader.serviceDiagnostics;
783
- }
784
- if (response && response.diagnosticInfos) {
785
- err.diagnosticsInfo = response.diagnosticInfos;
786
- }
787
- return callback(err);
788
- }
789
- /* istanbul ignore next */
790
- if (!response) {
791
- return callback(new Error("internal Error"));
792
- }
793
- /* istanbul ignore next */
794
- if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
795
- err = new Error(" ServiceResult is " +
796
- response.responseHeader.serviceResult.toString() +
797
- " request was " +
798
- request.constructor.name);
799
- if (response && response.responseHeader.serviceDiagnostics) {
800
- err.serviceDiagnostics = response.responseHeader.serviceDiagnostics;
801
- }
802
- if (response && response.diagnosticInfos) {
803
- err.diagnosticsInfo = response.diagnosticInfos;
804
- }
805
- return callback(err, response);
806
- }
807
- return callback(null, response);
808
- });
809
- }
810
- /**
811
- * evaluate the remaining time for the session
812
- *
813
- *
814
- * evaluate the time in milliseconds that the session will live
815
- * on the server end from now.
816
- * The remaining live time is calculated based on when the last message was sent to the server
817
- * and the session timeout.
818
- *
819
- * * In normal operation , when server and client communicates on a regular
820
- * basis, evaluateRemainingLifetime will return a number slightly below
821
- * session.timeout
822
- *
823
- * * when the client and server cannot communicate due to a network issue
824
- * (or a server crash), evaluateRemainingLifetime returns the estimated number
825
- * of milliseconds before the server (if not crash) will keep the session alive
826
- * on its end to allow a automatic reconnection with session.
827
- *
828
- * * When evaluateRemainingLifetime returns zero , this mean that
829
- * the session has probably ended on the server side and will have to be recreated
830
- * from scratch in case of a reconnection.
831
- *
832
- * @return the number of milliseconds before session expires
833
- */
834
- evaluateRemainingLifetime() {
835
- const now = Date.now();
836
- const expiryTime = this.lastRequestSentTime.getTime() + this.timeout;
837
- return Math.max(0, expiryTime - now);
838
- }
839
- _terminatePublishEngine() {
840
- if (this._publishEngine) {
841
- this._publishEngine.terminate();
842
- this._publishEngine = null;
843
- }
844
- }
845
- /**
846
- * @internal
847
- * @param args
848
- */
849
- close(...args) {
850
- if (arguments.length === 1) {
851
- return this.close(true, args[0]);
852
- }
853
- const deleteSubscription = args[0];
854
- const callback = args[1];
855
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
856
- (0, node_opcua_assert_1.assert)(typeof deleteSubscription === "boolean");
857
- /* istanbul ignore next */
858
- if (!this._client) {
859
- debugLog("ClientSession#close : warning, client is already closed");
860
- return callback(); // already close ?
861
- }
862
- (0, node_opcua_assert_1.assert)(this._client);
863
- this._terminatePublishEngine();
864
- this._client.closeSession(this, deleteSubscription, (err) => {
865
- debugLog("session Close err ", err ? err.message : "null");
866
- callback();
867
- });
868
- }
869
- /**
870
- * @method hasBeenClosed
871
- * @return {Boolean}
872
- */
873
- hasBeenClosed() {
874
- return (0, node_opcua_utils_1.isNullOrUndefined)(this._client) || this._closed || this._closeEventHasBeenEmitted;
875
- }
876
- /**
877
- * @internal
878
- * @param args
879
- */
880
- call(...args) {
881
- const isArray = Array.isArray(args[0]);
882
- const methodsToCall = isArray ? args[0] : [args[0]];
883
- (0, node_opcua_assert_1.assert)(Array.isArray(methodsToCall));
884
- const callback = args[1];
885
- // Note : The client has no explicit address space and therefore will struggle to
886
- // access the method arguments signature.
887
- // There are two methods that can be considered:
888
- // - get the object definition by querying the server
889
- // - load a fake address space to have some thing to query on our end
890
- // const request = this._client.factory.constructObjectId("CallRequest",{ methodsToCall: methodsToCall});
891
- const request = new node_opcua_service_call_1.CallRequest({ methodsToCall });
892
- this.performMessageTransaction(request, (err, response) => {
893
- /* istanbul ignore next */
894
- if (err) {
895
- return callback(err);
896
- }
897
- /* istanbul ignore next */
898
- if (!response || !(response instanceof node_opcua_service_call_1.CallResponse)) {
899
- return callback(new Error("internal error"));
900
- }
901
- response.results = response.results || [];
902
- promoteOpaqueStructure3WithCallback(this, response.results, () => {
903
- callback(null, isArray ? response.results : response.results[0]);
904
- });
905
- });
906
- }
907
- getMonitoredItems(...args) {
908
- const subscriptionId = args[0];
909
- const callback = args[1];
910
- // <UAObject NodeId="i=2253" BrowseName="Server">
911
- // <UAMethod NodeId="i=11492" BrowseName="GetMonitoredItems"
912
- // ParentNodeId="i=2253" MethodDeclarationId="i=11489">
913
- // <UAMethod NodeId="i=11489" BrowseName="GetMonitoredItems" ParentNodeId="i=2004">
914
- const methodsToCall = new node_opcua_service_call_1.CallMethodRequest({
915
- inputArguments: [
916
- // BaseDataType
917
- { dataType: node_opcua_variant_1.DataType.UInt32, value: subscriptionId }
918
- ],
919
- methodId: (0, node_opcua_nodeid_1.coerceNodeId)("ns=0;i=11492"),
920
- objectId: (0, node_opcua_nodeid_1.coerceNodeId)("ns=0;i=2253") // ObjectId.Server
921
- });
922
- this.call(methodsToCall, (err, result) => {
923
- /* istanbul ignore next */
924
- if (err) {
925
- return callback(err);
926
- }
927
- /* istanbul ignore next */
928
- if (!result) {
929
- return callback(new Error("internal error"));
930
- }
931
- /* istanbul ignore next */
932
- if (result.statusCode.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
933
- callback(new Error(result.statusCode.toString()));
934
- }
935
- else {
936
- result.outputArguments = result.outputArguments || [];
937
- (0, node_opcua_assert_1.assert)(result.outputArguments.length === 2);
938
- const data = {
939
- clientHandles: result.outputArguments[1].value,
940
- serverHandles: result.outputArguments[0].value //
941
- };
942
- // Note some server might return null array
943
- // let make sure we have Uint32Array and not a null pointer
944
- data.serverHandles = data.serverHandles || /* istanbul ignore next */ emptyUint32Array;
945
- data.clientHandles = data.clientHandles || /* istanbul ignore next */ emptyUint32Array;
946
- (0, node_opcua_assert_1.assert)(data.serverHandles instanceof Uint32Array);
947
- (0, node_opcua_assert_1.assert)(data.clientHandles instanceof Uint32Array);
948
- callback(null, data);
949
- }
950
- });
951
- }
952
- /**
953
- * @internal
954
- */
955
- getArgumentDefinition(...args) {
956
- const methodId = args[0];
957
- const callback = args[1];
958
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
959
- return (0, node_opcua_pseudo_session_1.getArgumentDefinitionHelper)(this, methodId, callback);
960
- }
961
- registerNodes(...args) {
962
- const nodesToRegister = args[0];
963
- const callback = args[1];
964
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
965
- (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRegister));
966
- const request = new node_opcua_service_register_node_1.RegisterNodesRequest({
967
- nodesToRegister: nodesToRegister.map(node_opcua_nodeid_1.resolveNodeId)
968
- });
969
- this.performMessageTransaction(request, (err, response) => {
970
- /* istanbul ignore next */
971
- if (err) {
972
- return callback(err);
973
- }
974
- /* istanbul ignore next */
975
- if (!response || !(response instanceof node_opcua_service_register_node_1.RegisterNodesResponse)) {
976
- return callback(new Error("Internal Error"));
977
- }
978
- response.registeredNodeIds = response.registeredNodeIds || /* istanbul ignore next */ [];
979
- callback(null, response.registeredNodeIds);
980
- });
981
- }
982
- unregisterNodes(...args) {
983
- const nodesToUnregister = args[0];
984
- const callback = args[1];
985
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
986
- (0, node_opcua_assert_1.assert)(Array.isArray(nodesToUnregister));
987
- const request = new node_opcua_service_register_node_1.UnregisterNodesRequest({
988
- nodesToUnregister: nodesToUnregister.map(node_opcua_nodeid_1.resolveNodeId)
989
- });
990
- this.performMessageTransaction(request, (err, response) => {
991
- /* istanbul ignore next */
992
- if (err) {
993
- return callback(err);
994
- }
995
- /* istanbul ignore next */
996
- if (!response || !(response instanceof node_opcua_service_register_node_1.UnregisterNodesResponse)) {
997
- return callback(new Error("Internal Error"));
998
- }
999
- callback();
1000
- });
1001
- }
1002
- queryFirst(...args) {
1003
- const queryFirstRequest = args[0];
1004
- const callback = args[1];
1005
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
1006
- const request = new node_opcua_service_query_1.QueryFirstRequest(queryFirstRequest);
1007
- this.performMessageTransaction(request, (err, response) => {
1008
- /* istanbul ignore next */
1009
- if (err) {
1010
- return callback(err);
1011
- }
1012
- /* istanbul ignore next */
1013
- if (!response || !(response instanceof node_opcua_service_query_1.QueryFirstResponse)) {
1014
- return callback(new Error("internal error"));
1015
- }
1016
- callback(null, response);
1017
- });
1018
- }
1019
- startKeepAliveManager() {
1020
- if (this._keepAliveManager) {
1021
- // "keepAliveManger already started"
1022
- return;
1023
- }
1024
- this._keepAliveManager = new client_session_keepalive_manager_1.ClientSessionKeepAliveManager(this);
1025
- this._keepAliveManager.on("failure", () => {
1026
- /**
1027
- * raised when a keep-alive request has failed on the session, may be the session has timeout
1028
- * unexpectedly on the server side, may be the connection is broken.
1029
- * @event keepalive_failure
1030
- */
1031
- this.emit("keepalive_failure");
1032
- });
1033
- this._keepAliveManager.on("keepalive", (state, count) => {
1034
- /**
1035
- * @event keepalive
1036
- */
1037
- this.emit("keepalive", state, count);
1038
- });
1039
- this._keepAliveManager.start();
1040
- }
1041
- stopKeepAliveManager() {
1042
- if (this._keepAliveManager) {
1043
- this._keepAliveManager.stop();
1044
- this._keepAliveManager = undefined;
1045
- }
1046
- }
1047
- dispose() {
1048
- (0, node_opcua_assert_1.assert)(this._closeEventHasBeenEmitted);
1049
- this._terminatePublishEngine();
1050
- this.stopKeepAliveManager();
1051
- this.removeAllListeners();
1052
- //
1053
- const privateThis = this;
1054
- if (!(!privateThis.pendingTransactions || privateThis.pendingTransactions.length === 0)) {
1055
- // tslint:disable-next-line: no-console
1056
- console.log("dispose when pendingTransactions is not empty ");
1057
- }
1058
- }
1059
- toString() {
1060
- const now = Date.now();
1061
- const lap1 = now - this.lastRequestSentTime.getTime();
1062
- const lap2 = now - this.lastResponseReceivedTime.getTime();
1063
- const timeoutDelay = this.timeout - lap1;
1064
- const timeoutInfo = timeoutDelay < 0
1065
- ? chalk.red(" expired since " + -timeoutDelay / 1000 + " seconds")
1066
- : chalk.green(" timeout in " + timeoutDelay / 1000 + " seconds");
1067
- let str = "";
1068
- str += " name..................... " + this.name;
1069
- str += "\n sessionId................ " + this.sessionId.toString();
1070
- str += "\n authenticationToken...... " + (this.authenticationToken ? this.authenticationToken.toString() : "");
1071
- str += "\n timeout.................. " + this.timeout + "ms" + timeoutInfo;
1072
- str += "\n serverNonce.............. " + (this.serverNonce ? this.serverNonce.toString("hex") : "");
1073
- str += "\n serverCertificate........ " + (0, node_opcua_utils_1.buffer_ellipsis)(this.serverCertificate);
1074
- // xx console.log(" serverSignature.......... ", this.serverSignature);
1075
- str += "\n lastRequestSentTime...... " + new Date(this.lastRequestSentTime).toISOString() + " (" + lap1 + ")";
1076
- str += "\n lastResponseReceivedTime. " + new Date(this.lastResponseReceivedTime).toISOString() + " (" + lap2 + ")";
1077
- str += "\n isReconnecting........... " + this.isReconnecting;
1078
- str += "\n isValidChannel........... " + this.isChannelValid() + " has been closed " + this.hasBeenClosed();
1079
- str += "\n channelId................ " + this.channelId();
1080
- str += "\n remaining life time...... " + this.evaluateRemainingLifetime();
1081
- str += "\n subscription count....... " + this.subscriptionCount;
1082
- if (this._client && this._client._secureChannel) {
1083
- if (this._client._secureChannel.securityToken) {
1084
- str += "\n reviseTokenLifetime...... " + this._client._secureChannel.securityToken.revisedLifetime;
1085
- }
1086
- }
1087
- return str;
1088
- }
1089
- getBuiltInDataType(...args) {
1090
- const nodeId = args[0];
1091
- const callback = args[1];
1092
- return (0, node_opcua_pseudo_session_1.getBuiltInDataType)(this, nodeId, callback);
1093
- }
1094
- resumePublishEngine() {
1095
- (0, node_opcua_assert_1.assert)(this._publishEngine);
1096
- if (this._publishEngine && this._publishEngine.subscriptionCount > 0) {
1097
- this._publishEngine.replenish_publish_request_queue();
1098
- }
1099
- }
1100
- readNamespaceArray(...args) {
1101
- const callback = args[0];
1102
- this.read({
1103
- attributeId: node_opcua_service_read_1.AttributeIds.Value,
1104
- nodeId: (0, node_opcua_nodeid_1.resolveNodeId)("Server_NamespaceArray")
1105
- }, (err, dataValue) => {
1106
- /* istanbul ignore next */
1107
- if (err) {
1108
- return callback(err);
1109
- }
1110
- /* istanbul ignore next */
1111
- if (!dataValue) {
1112
- return callback(new Error("Internal Error"));
1113
- }
1114
- /* istanbul ignore next */
1115
- if (dataValue.statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1116
- return callback(new Error("readNamespaceArray : " + dataValue.statusCode.toString()));
1117
- }
1118
- (0, node_opcua_assert_1.assert)(dataValue.value.value instanceof Array);
1119
- this._namespaceArray = dataValue.value.value; // keep a cache
1120
- callback(null, this._namespaceArray);
1121
- });
1122
- }
1123
- getNamespaceIndex(namespaceUri) {
1124
- (0, node_opcua_assert_1.assert)(this._namespaceArray, "please make sure that readNamespaceArray has been called");
1125
- return this._namespaceArray.indexOf(namespaceUri);
1126
- }
1127
- // tslint:disable:no-empty
1128
- // ---------------------------------------- Alarm & condition stub
1129
- disableCondition() {
1130
- /** empty */
1131
- }
1132
- enableCondition() {
1133
- /** empty */
1134
- }
1135
- addCommentCondition(_conditionId, _eventId, _comment, _callback) {
1136
- /** empty */
1137
- }
1138
- confirmCondition(_conditionId, _eventId, _comment, _callback) {
1139
- /** empty */
1140
- }
1141
- acknowledgeCondition(_conditionId, _eventId, _comment, _callback) {
1142
- /** empty */
1143
- }
1144
- findMethodId(_nodeId, _methodName, _callback) {
1145
- /** empty */
1146
- }
1147
- _callMethodCondition(_methodName, _conditionId, _eventId, _comment, _callback) {
1148
- /** empty */
1149
- }
1150
- extractNamespaceDataType() {
1151
- return __awaiter(this, void 0, void 0, function* () {
1152
- return (0, node_opcua_client_dynamic_extension_object_1.getExtraDataTypeManager)(this);
1153
- });
1154
- }
1155
- getExtensionObjectConstructor(dataTypeNodeId) {
1156
- return __awaiter(this, void 0, void 0, function* () {
1157
- return (0, node_opcua_client_dynamic_extension_object_1.getExtensionObjectConstructor)(this, dataTypeNodeId);
1158
- });
1159
- }
1160
- /**
1161
- *
1162
- * @param dataType
1163
- * @param pojo
1164
- * @async
1165
- */
1166
- constructExtensionObject(dataType, pojo) {
1167
- return __awaiter(this, void 0, void 0, function* () {
1168
- const Constructor = yield this.getExtensionObjectConstructor(dataType);
1169
- return new Constructor(pojo);
1170
- });
1171
- }
1172
- _defaultRequest(requestClass, _responseClass, options, callback) {
1173
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
1174
- const request = options instanceof requestClass ? options : new requestClass(options);
1175
- /* istanbul ignore next */
1176
- if (doDebug) {
1177
- request.trace = new Error("").stack;
1178
- }
1179
- /* istanbul ignore next */
1180
- if (this._closeEventHasBeenEmitted) {
1181
- debugLog("ClientSession#_defaultRequest => session has been closed !!", request.toString());
1182
- setImmediate(() => {
1183
- callback(new Error("ClientSession is closed !"));
1184
- });
1185
- return;
1186
- }
1187
- this.performMessageTransaction(request, (err, response) => {
1188
- if (this._closeEventHasBeenEmitted) {
1189
- debugLog("ClientSession#_defaultRequest ... err =", err ? err.message : "null", response ? response.toString() : " null");
1190
- }
1191
- /* istanbul ignore next */
1192
- if (err) {
1193
- debugLog("Client session : performMessageTransaction error = ", err.message);
1194
- // let intercept interesting error message
1195
- if (err.message.match(/BadSessionClosed/)) {
1196
- // the session has been closed by Server
1197
- // probably due to timeout issue
1198
- // let's print some statistics
1199
- const now = Date.now();
1200
- /* istanbul ignore next */
1201
- if (doDebug) {
1202
- debugLog(chalk.bgWhite.red(" server send BadSessionClosed !"));
1203
- debugLog(chalk.bgWhite.red(" request was "), request.toString());
1204
- debugLog(" timeout.................. ", this.timeout);
1205
- debugLog(" lastRequestSentTime...... ", new Date(this.lastRequestSentTime).toISOString(), now - this.lastRequestSentTime.getTime());
1206
- debugLog(" lastResponseReceivedTime. ", new Date(this.lastResponseReceivedTime).toISOString(), now - this.lastResponseReceivedTime.getTime());
1207
- }
1208
- // DO NOT TERMINATE SESSION, as we will need a publishEngine when we
1209
- // reconnect this._terminatePublishEngine();
1210
- if (false) {
1211
- // ER 10.2019
1212
- /**
1213
- * send when the session has been closed by the server ( probably due to inactivity and timeout)
1214
- * @event session_closed
1215
- */
1216
- this.emitCloseEvent(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1217
- }
1218
- }
1219
- return callback(err, response);
1220
- }
1221
- callback(null, response);
1222
- });
1223
- }
1224
- recreate_session_and_reperform_transaction(request, callback) {
1225
- if (this.recursive_repair_detector >= 1) {
1226
- // tslint:disable-next-line: no-console
1227
- console.log("recreate_session_and_reperform_transaction => Already in Progress");
1228
- return callback(new Error("Cannot recreate session"));
1229
- }
1230
- this.recursive_repair_detector += 1;
1231
- debugLog(chalk.red("----------------> Repairing Client Session as Server believes it is invalid now "));
1232
- (0, reconnection_1.repair_client_session)(this._client, this, (err) => {
1233
- this.recursive_repair_detector -= 1;
1234
- if (err) {
1235
- debugLog(chalk.red("----------------> session Repaired has failed with error", err.message));
1236
- return callback(err);
1237
- }
1238
- debugLog(chalk.red("----------------> session Repaired, now redoing original transaction "));
1239
- this._performMessageTransaction(request, callback);
1240
- });
1241
- }
1242
- }
1243
- exports.ClientSessionImpl = ClientSessionImpl;
1244
- function promoteOpaqueStructure2(session, callMethodResult) {
1245
- return __awaiter(this, void 0, void 0, function* () {
1246
- if (!callMethodResult || !callMethodResult.outputArguments || callMethodResult.outputArguments.length === 0) {
1247
- return;
1248
- }
1249
- yield (0, node_opcua_client_dynamic_extension_object_1.promoteOpaqueStructure)(session, callMethodResult.outputArguments.map((a) => ({ value: a })));
1250
- });
1251
- }
1252
- function promoteOpaqueStructure3(session, callMethodResults) {
1253
- return __awaiter(this, void 0, void 0, function* () {
1254
- // construct dataTypeManager if not already present
1255
- const extraDataTypeManager = yield (0, node_opcua_client_dynamic_extension_object_1.getExtraDataTypeManager)(session);
1256
- const promises = callMethodResults.map((x) => __awaiter(this, void 0, void 0, function* () { return promoteOpaqueStructure2(session, x); }));
1257
- yield Promise.all(promises);
1258
- });
1259
- }
1260
- // tslint:disable:no-var-requires
1261
- // tslint:disable:max-line-length
1262
- const thenify = require("thenify");
1263
- const callbackify = require("callbackify");
1264
- const opts = { multiArgs: false };
1265
- const promoteOpaqueStructureWithCallback = callbackify(node_opcua_client_dynamic_extension_object_1.promoteOpaqueStructure);
1266
- const promoteOpaqueStructure3WithCallback = callbackify(promoteOpaqueStructure3);
1267
- ClientSessionImpl.prototype.browse = thenify.withCallback(ClientSessionImpl.prototype.browse, opts);
1268
- ClientSessionImpl.prototype.browseNext = thenify.withCallback(ClientSessionImpl.prototype.browseNext, opts);
1269
- ClientSessionImpl.prototype.readVariableValue = thenify.withCallback(ClientSessionImpl.prototype.readVariableValue, opts);
1270
- ClientSessionImpl.prototype.readHistoryValue = thenify.withCallback(ClientSessionImpl.prototype.readHistoryValue, opts);
1271
- ClientSessionImpl.prototype.readAggregateValue = thenify.withCallback(ClientSessionImpl.prototype.readAggregateValue, opts);
1272
- ClientSessionImpl.prototype.historyRead = thenify.withCallback(ClientSessionImpl.prototype.historyRead, opts);
1273
- ClientSessionImpl.prototype.write = thenify.withCallback(ClientSessionImpl.prototype.write, opts);
1274
- ClientSessionImpl.prototype.writeSingleNode = thenify.withCallback(ClientSessionImpl.prototype.writeSingleNode, opts);
1275
- ClientSessionImpl.prototype.readAllAttributes = thenify.withCallback(ClientSessionImpl.prototype.readAllAttributes, opts);
1276
- ClientSessionImpl.prototype.read = thenify.withCallback(ClientSessionImpl.prototype.read, opts);
1277
- ClientSessionImpl.prototype.createSubscription = thenify.withCallback(ClientSessionImpl.prototype.createSubscription, opts);
1278
- ClientSessionImpl.prototype.createSubscription2 = thenify.withCallback(ClientSessionImpl.prototype.createSubscription2, opts);
1279
- ClientSessionImpl.prototype.deleteSubscriptions = thenify.withCallback(ClientSessionImpl.prototype.deleteSubscriptions, opts);
1280
- ClientSessionImpl.prototype.transferSubscriptions = thenify.withCallback(ClientSessionImpl.prototype.transferSubscriptions, opts);
1281
- ClientSessionImpl.prototype.createMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.createMonitoredItems, opts);
1282
- ClientSessionImpl.prototype.modifyMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.modifyMonitoredItems, opts);
1283
- ClientSessionImpl.prototype.modifySubscription = thenify.withCallback(ClientSessionImpl.prototype.modifySubscription, opts);
1284
- ClientSessionImpl.prototype.setTriggering = thenify.withCallback(ClientSessionImpl.prototype.setTriggering, opts);
1285
- ClientSessionImpl.prototype.setMonitoringMode = thenify.withCallback(ClientSessionImpl.prototype.setMonitoringMode, opts);
1286
- ClientSessionImpl.prototype.publish = thenify.withCallback(ClientSessionImpl.prototype.publish, opts);
1287
- ClientSessionImpl.prototype.republish = thenify.withCallback(ClientSessionImpl.prototype.republish, opts);
1288
- ClientSessionImpl.prototype.deleteMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.deleteMonitoredItems, opts);
1289
- ClientSessionImpl.prototype.setPublishingMode = thenify.withCallback(ClientSessionImpl.prototype.setPublishingMode, opts);
1290
- ClientSessionImpl.prototype.translateBrowsePath = thenify.withCallback(ClientSessionImpl.prototype.translateBrowsePath, opts);
1291
- ClientSessionImpl.prototype.performMessageTransaction = thenify.withCallback(ClientSessionImpl.prototype.performMessageTransaction, opts);
1292
- ClientSessionImpl.prototype.close = thenify.withCallback(ClientSessionImpl.prototype.close, opts);
1293
- ClientSessionImpl.prototype.call = thenify.withCallback(ClientSessionImpl.prototype.call, opts);
1294
- ClientSessionImpl.prototype.getMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.getMonitoredItems, opts);
1295
- ClientSessionImpl.prototype.getArgumentDefinition = thenify.withCallback(ClientSessionImpl.prototype.getArgumentDefinition, opts);
1296
- ClientSessionImpl.prototype.queryFirst = thenify.withCallback(ClientSessionImpl.prototype.queryFirst, opts);
1297
- ClientSessionImpl.prototype.registerNodes = thenify.withCallback(ClientSessionImpl.prototype.registerNodes, opts);
1298
- ClientSessionImpl.prototype.unregisterNodes = thenify.withCallback(ClientSessionImpl.prototype.unregisterNodes, opts);
1299
- ClientSessionImpl.prototype.readNamespaceArray = thenify.withCallback(ClientSessionImpl.prototype.readNamespaceArray, opts);
1300
- ClientSessionImpl.prototype.getBuiltInDataType = thenify.withCallback(ClientSessionImpl.prototype.getBuiltInDataType, opts);
1301
- ClientSessionImpl.prototype.constructExtensionObject = callbackify(ClientSessionImpl.prototype.constructExtensionObject);
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ClientSessionImpl = void 0;
13
+ /**
14
+ * @module node-opcua-client-private
15
+ */
16
+ const events_1 = require("events");
17
+ const chalk = require("chalk");
18
+ const node_opcua_assert_1 = require("node-opcua-assert");
19
+ const node_opcua_client_dynamic_extension_object_1 = require("node-opcua-client-dynamic-extension-object");
20
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
21
+ const node_opcua_data_value_1 = require("node-opcua-data-value");
22
+ const node_opcua_debug_1 = require("node-opcua-debug");
23
+ const node_opcua_nodeid_1 = require("node-opcua-nodeid");
24
+ const node_opcua_pseudo_session_1 = require("node-opcua-pseudo-session");
25
+ const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
26
+ const node_opcua_service_browse_1 = require("node-opcua-service-browse");
27
+ const node_opcua_service_call_1 = require("node-opcua-service-call");
28
+ const node_opcua_service_history_1 = require("node-opcua-service-history");
29
+ const node_opcua_service_query_1 = require("node-opcua-service-query");
30
+ const node_opcua_service_read_1 = require("node-opcua-service-read");
31
+ const node_opcua_service_register_node_1 = require("node-opcua-service-register-node");
32
+ const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
33
+ const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
34
+ const node_opcua_service_write_1 = require("node-opcua-service-write");
35
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
36
+ const node_opcua_types_1 = require("node-opcua-types");
37
+ const node_opcua_utils_1 = require("node-opcua-utils");
38
+ const node_opcua_variant_1 = require("node-opcua-variant");
39
+ const client_session_keepalive_manager_1 = require("../client_session_keepalive_manager");
40
+ const reconnection_1 = require("../reconnection");
41
+ const client_publish_engine_1 = require("./client_publish_engine");
42
+ const client_subscription_impl_1 = require("./client_subscription_impl");
43
+ const helpAPIChange = process.env.DEBUG && process.env.DEBUG.match(/API/);
44
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
45
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
46
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
47
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
48
+ let pendingTransactionMessageDisplayed = false;
49
+ function coerceBrowseDescription(data) {
50
+ if (typeof data === "string" || data instanceof node_opcua_nodeid_1.NodeId) {
51
+ return coerceBrowseDescription({
52
+ browseDirection: node_opcua_data_model_1.BrowseDirection.Forward,
53
+ includeSubtypes: true,
54
+ nodeClassMask: 0,
55
+ nodeId: data,
56
+ referenceTypeId: "HierarchicalReferences",
57
+ resultMask: 63
58
+ });
59
+ }
60
+ else {
61
+ data.nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(data.nodeId);
62
+ data.referenceTypeId = data.referenceTypeId ? (0, node_opcua_nodeid_1.resolveNodeId)(data.referenceTypeId) : null;
63
+ return new node_opcua_service_browse_1.BrowseDescription(data);
64
+ }
65
+ }
66
+ function coerceReadValueId(node) {
67
+ if (typeof node === "string" || node instanceof node_opcua_nodeid_1.NodeId) {
68
+ return new node_opcua_service_read_1.ReadValueId({
69
+ attributeId: node_opcua_service_read_1.AttributeIds.Value,
70
+ dataEncoding: undefined,
71
+ indexRange: undefined,
72
+ nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(node)
73
+ });
74
+ }
75
+ else {
76
+ (0, node_opcua_assert_1.assert)(node instanceof Object);
77
+ return new node_opcua_service_read_1.ReadValueId(node);
78
+ }
79
+ }
80
+ const keys = Object.keys(node_opcua_service_read_1.AttributeIds).filter((k) => node_opcua_service_read_1.AttributeIds[k] !== node_opcua_service_read_1.AttributeIds.INVALID);
81
+ const attributeNames = (() => {
82
+ const r = [];
83
+ for (let i = 1; i <= 22; i++) {
84
+ r.push(node_opcua_data_model_1.attributeNameById[i].toString());
85
+ }
86
+ return r;
87
+ })();
88
+ function composeResult(nodes, nodesToRead, dataValues) {
89
+ (0, node_opcua_assert_1.assert)(nodesToRead.length === dataValues.length);
90
+ let c = 0;
91
+ const results = [];
92
+ let dataValue;
93
+ let k;
94
+ let nodeToRead;
95
+ for (const node of nodes) {
96
+ const data = {
97
+ nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(node),
98
+ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown
99
+ };
100
+ let addedProperty = 0;
101
+ for (const key of attributeNames) {
102
+ dataValue = dataValues[c];
103
+ nodeToRead = nodesToRead[c];
104
+ c++;
105
+ if (dataValue.statusCode.equals(node_opcua_status_code_1.StatusCodes.Good)) {
106
+ k = (0, node_opcua_utils_1.lowerFirstLetter)(key);
107
+ data[k] = dataValue.value ? dataValue.value.value : null;
108
+ addedProperty += 1;
109
+ }
110
+ }
111
+ /* istanbul ignore if */
112
+ if (addedProperty > 0) {
113
+ data.statusCode = node_opcua_status_code_1.StatusCodes.Good;
114
+ }
115
+ else {
116
+ data.statusCode = node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown;
117
+ }
118
+ results.push(data);
119
+ }
120
+ return results;
121
+ }
122
+ const emptyUint32Array = new Uint32Array(0);
123
+ /**
124
+ * @class ClientSession
125
+ * @param client {OPCUAClientImpl}
126
+ * @constructor
127
+ * @private
128
+ */
129
+ class ClientSessionImpl extends events_1.EventEmitter {
130
+ constructor(client) {
131
+ super();
132
+ this.name = "";
133
+ this.serverEndpoints = [];
134
+ this.recursive_repair_detector = 0;
135
+ this.processTransactionQueue = (request, callback) => {
136
+ this._reconnecting.pendingTransactionsCount = this._reconnecting.pendingTransactionsCount || 0;
137
+ this._reconnecting.pendingTransactionsCount++;
138
+ this._performMessageTransaction(request, (err, response) => {
139
+ this._reconnecting.pendingTransactionsCount--;
140
+ if (err && err.message.match(/BadSessionIdInvalid/) && request.constructor.name !== "ActivateSessionRequest") {
141
+ debugLog("Transaction on Invalid Session ", request.constructor.name);
142
+ request.requestHeader.requestHandle = node_opcua_secure_channel_1.requestHandleNotSetValue;
143
+ warningLog("client is now attempting to recreate a session");
144
+ this.recreate_session_and_reperform_transaction(request, callback);
145
+ return;
146
+ }
147
+ callback(err, response);
148
+ const length = this._reconnecting.pendingTransactions.length; // record length before callback is called !
149
+ if (length > 0) {
150
+ debugLog("processTransactionQueue => ", this._reconnecting.pendingTransactions.length, " transaction(s) left in queue");
151
+ // tslint:disable-next-line: no-shadowed-variable
152
+ const { request, callback } = this._reconnecting.pendingTransactions.shift();
153
+ this.processTransactionQueue(request, callback);
154
+ }
155
+ });
156
+ };
157
+ this.serverCertificate = Buffer.alloc(0);
158
+ this.sessionId = new node_opcua_nodeid_1.NodeId();
159
+ this._closeEventHasBeenEmitted = false;
160
+ this._client = client;
161
+ this._publishEngine = null;
162
+ this._closed = false;
163
+ this._reconnecting = {
164
+ reconnecting: false,
165
+ pendingCallbacks: [],
166
+ pendingTransactions: [],
167
+ pendingTransactionsCount: 0
168
+ };
169
+ this.requestedMaxReferencesPerNode = 10000;
170
+ this.lastRequestSentTime = new Date(1, 1, 1970);
171
+ this.lastResponseReceivedTime = new Date(1, 1, 1970);
172
+ this.timeout = 0;
173
+ }
174
+ /**
175
+ * the endpoint on which this session is operating
176
+ * @property endpoint
177
+ * @type {EndpointDescription}
178
+ */
179
+ get endpoint() {
180
+ return this._client.endpoint;
181
+ }
182
+ get subscriptionCount() {
183
+ return this._publishEngine ? this._publishEngine.subscriptionCount : 0;
184
+ }
185
+ get isReconnecting() {
186
+ var _a;
187
+ return this._client ? this._client.isReconnecting || ((_a = this._reconnecting) === null || _a === void 0 ? void 0 : _a.reconnecting) : false;
188
+ }
189
+ getPublishEngine() {
190
+ if (!this._publishEngine) {
191
+ this._publishEngine = new client_publish_engine_1.ClientSidePublishEngine(this);
192
+ }
193
+ return this._publishEngine;
194
+ }
195
+ /**
196
+ * @internal
197
+ * @param args
198
+ */
199
+ browse(...args) {
200
+ const arg0 = args[0];
201
+ const isArray = Array.isArray(arg0);
202
+ const callback = args[1];
203
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
204
+ (0, node_opcua_assert_1.assert)(isFinite(this.requestedMaxReferencesPerNode));
205
+ const nodesToBrowse = (isArray ? arg0 : [arg0]).map(coerceBrowseDescription);
206
+ const request = new node_opcua_service_browse_1.BrowseRequest({
207
+ nodesToBrowse,
208
+ requestedMaxReferencesPerNode: this.requestedMaxReferencesPerNode
209
+ });
210
+ this.performMessageTransaction(request, (err, response) => {
211
+ if (err) {
212
+ return callback(err);
213
+ }
214
+ /* istanbul ignore next */
215
+ if (!response || !(response instanceof node_opcua_service_browse_1.BrowseResponse)) {
216
+ return callback(new Error("Internal Error"));
217
+ }
218
+ const results = response.results ? response.results : [];
219
+ if (this.requestedMaxReferencesPerNode > 0) {
220
+ for (let i = 0; i < results.length; i++) {
221
+ const r = results[i];
222
+ /* istanbul ignore next */
223
+ if (r.references && r.references.length > this.requestedMaxReferencesPerNode) {
224
+ warningLog(chalk.yellow("warning") +
225
+ " BrowseResponse : the server didn't take into" +
226
+ " account our requestedMaxReferencesPerNode ");
227
+ warningLog(" this.requestedMaxReferencesPerNode= " + this.requestedMaxReferencesPerNode);
228
+ warningLog(" got " + r.references.length + "for " + nodesToBrowse[i].nodeId.toString());
229
+ warningLog(" continuationPoint ", r.continuationPoint);
230
+ }
231
+ }
232
+ }
233
+ for (const r of results) {
234
+ r.references = r.references || /* istanbul ignore next */ [];
235
+ }
236
+ (0, node_opcua_assert_1.assert)(results[0] instanceof node_opcua_service_browse_1.BrowseResult);
237
+ return callback(null, isArray ? results : results[0]);
238
+ });
239
+ }
240
+ browseNext(...args) {
241
+ const arg0 = args[0];
242
+ const isArray = Array.isArray(arg0);
243
+ const releaseContinuationPoints = args[1];
244
+ const callback = args[2];
245
+ (0, node_opcua_assert_1.assert)(typeof callback === "function", "expecting a callback function here");
246
+ const continuationPoints = isArray ? arg0 : [arg0];
247
+ const request = new node_opcua_types_1.BrowseNextRequest({
248
+ continuationPoints,
249
+ releaseContinuationPoints
250
+ });
251
+ this.performMessageTransaction(request, (err, response) => {
252
+ /* istanbul ignore next */
253
+ if (err) {
254
+ return callback(err);
255
+ }
256
+ /* istanbul ignore next */
257
+ if (!response || !(response instanceof node_opcua_types_1.BrowseNextResponse)) {
258
+ return callback(new Error("Internal Error"));
259
+ }
260
+ const results = response.results ? response.results : [];
261
+ for (const r of results) {
262
+ r.references = r.references || [];
263
+ }
264
+ (0, node_opcua_assert_1.assert)(results[0] instanceof node_opcua_service_browse_1.BrowseResult);
265
+ return callback(null, isArray ? results : results[0]);
266
+ });
267
+ }
268
+ /**
269
+ * @internal
270
+ * @param args
271
+ */
272
+ readVariableValue(...args) {
273
+ const callback = args[1];
274
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
275
+ const isArray = Array.isArray(args[0]);
276
+ const nodes = isArray ? args[0] : [args[0]];
277
+ const nodesToRead = nodes.map(coerceReadValueId);
278
+ const request = new node_opcua_service_read_1.ReadRequest({
279
+ nodesToRead,
280
+ timestampsToReturn: node_opcua_service_read_1.TimestampsToReturn.Neither
281
+ });
282
+ this.performMessageTransaction(request, (err, response) => {
283
+ /* istanbul ignore next */
284
+ if (err) {
285
+ return callback(err);
286
+ }
287
+ /* istanbul ignore next */
288
+ if (!(response instanceof node_opcua_service_read_1.ReadResponse)) {
289
+ return callback(new Error("Internal Error"));
290
+ }
291
+ /* istanbul ignore next */
292
+ if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
293
+ return callback(new Error(response.responseHeader.serviceResult.toString()));
294
+ }
295
+ /* istanbul ignore next */
296
+ if (!response.results) {
297
+ response.results = [];
298
+ }
299
+ (0, node_opcua_assert_1.assert)(nodes.length === response.results.length);
300
+ callback(null, isArray ? response.results : response.results[0]);
301
+ });
302
+ }
303
+ readHistoryValue(...args) {
304
+ const startTime = args[1];
305
+ const endTime = args[2];
306
+ let options = {};
307
+ let callback = args[3];
308
+ if (typeof callback !== "function") {
309
+ options = args[3];
310
+ callback = args[4];
311
+ }
312
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
313
+ // adjust parameters
314
+ options.numValuesPerNode = options.numValuesPerNode || 0;
315
+ options.returnBounds = options.returnBounds || options.returnBounds === undefined ? true : false;
316
+ options.isReadModified = options.isReadModified || false;
317
+ options.timestampsToReturn = options.timestampsToReturn || node_opcua_service_read_1.TimestampsToReturn.Both;
318
+ const arg0 = args[0];
319
+ const isArray = Array.isArray(arg0);
320
+ const nodes = isArray ? arg0 : [arg0];
321
+ const nodesToRead = [];
322
+ for (const node of nodes) {
323
+ if (!node.nodeId) {
324
+ nodesToRead.push({
325
+ continuationPoint: undefined,
326
+ dataEncoding: undefined,
327
+ indexRange: undefined,
328
+ nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(node)
329
+ });
330
+ }
331
+ else {
332
+ nodesToRead.push(node);
333
+ }
334
+ }
335
+ const readRawModifiedDetails = new node_opcua_service_history_1.ReadRawModifiedDetails({
336
+ endTime,
337
+ isReadModified: false,
338
+ numValuesPerNode: options.numValuesPerNode,
339
+ returnBounds: options.returnBounds,
340
+ startTime
341
+ });
342
+ const request = new node_opcua_service_history_1.HistoryReadRequest({
343
+ historyReadDetails: readRawModifiedDetails,
344
+ nodesToRead,
345
+ releaseContinuationPoints: false,
346
+ timestampsToReturn: options.timestampsToReturn
347
+ });
348
+ request.nodesToRead = request.nodesToRead || [];
349
+ (0, node_opcua_assert_1.assert)(nodes.length === request.nodesToRead.length);
350
+ this.historyRead(request, (err, response) => {
351
+ /* istanbul ignore next */
352
+ if (err) {
353
+ return callback(err);
354
+ }
355
+ /* istanbul ignore next */
356
+ if (!response || !(response instanceof node_opcua_service_history_1.HistoryReadResponse)) {
357
+ return callback(new Error("Internal Error"));
358
+ }
359
+ response.results = response.results || [];
360
+ (0, node_opcua_assert_1.assert)(nodes.length === response.results.length);
361
+ callback(null, isArray ? response.results : response.results[0]);
362
+ });
363
+ }
364
+ historyRead(request, callback) {
365
+ /* istanbul ignore next */
366
+ if (!callback) {
367
+ throw new Error("expecting a callback");
368
+ }
369
+ this.performMessageTransaction(request, (err, response) => {
370
+ /* istanbul ignore next */
371
+ if (err) {
372
+ return callback(err);
373
+ }
374
+ /* istanbul ignore next */
375
+ if (!response || !(response instanceof node_opcua_service_history_1.HistoryReadResponse)) {
376
+ return callback(new Error("Internal Error"));
377
+ }
378
+ if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
379
+ return callback(new Error(response.responseHeader.serviceResult.toString()));
380
+ }
381
+ response.results = response.results || /* istanbul ignore next */ [];
382
+ callback(null, response);
383
+ });
384
+ }
385
+ readAggregateValue(arg0, startTime, endTime, aggregateFn, processingInterval, ...args) {
386
+ const callback = args[0];
387
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
388
+ const isArray = Array.isArray(arg0);
389
+ const nodesToRead = isArray
390
+ ? arg0
391
+ : [arg0];
392
+ const aggregateFns = Array.isArray(aggregateFn)
393
+ ? aggregateFn
394
+ : [aggregateFn];
395
+ (0, node_opcua_assert_1.assert)(aggregateFns.length === nodesToRead.length);
396
+ const readProcessedDetails = new node_opcua_service_history_1.ReadProcessedDetails({
397
+ aggregateType: aggregateFns,
398
+ endTime,
399
+ processingInterval,
400
+ startTime
401
+ });
402
+ const request = new node_opcua_service_history_1.HistoryReadRequest({
403
+ historyReadDetails: readProcessedDetails,
404
+ nodesToRead,
405
+ releaseContinuationPoints: false,
406
+ timestampsToReturn: node_opcua_service_read_1.TimestampsToReturn.Both
407
+ });
408
+ (0, node_opcua_assert_1.assert)(nodesToRead.length === request.nodesToRead.length);
409
+ this.performMessageTransaction(request, (err, response) => {
410
+ /* istanbul ignore next */
411
+ if (err) {
412
+ return callback(err);
413
+ }
414
+ /* istanbul ignore next */
415
+ if (!response || !(response instanceof node_opcua_service_history_1.HistoryReadResponse)) {
416
+ return callback(new Error("Internal Error"));
417
+ }
418
+ if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
419
+ return callback(new Error(response.responseHeader.serviceResult.toString()));
420
+ }
421
+ response.results = response.results || /* istanbul ignore next */ [];
422
+ (0, node_opcua_assert_1.assert)(nodesToRead.length === response.results.length);
423
+ callback(null, isArray ? response.results : response.results[0]);
424
+ });
425
+ }
426
+ /**
427
+ * @internal
428
+ * @param args
429
+ */
430
+ write(...args) {
431
+ const arg0 = args[0];
432
+ const isArray = Array.isArray(arg0);
433
+ const nodesToWrite = isArray ? arg0 : [arg0];
434
+ const callback = args[1];
435
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
436
+ const request = new node_opcua_service_write_1.WriteRequest({ nodesToWrite });
437
+ this.performMessageTransaction(request, (err, response) => {
438
+ /* istanbul ignore next */
439
+ if (err) {
440
+ return callback(err, response);
441
+ }
442
+ /* istanbul ignore next */
443
+ if (!response || !(response instanceof node_opcua_service_write_1.WriteResponse)) {
444
+ return callback(new Error("Internal Error"));
445
+ }
446
+ /* istanbul ignore next */
447
+ if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
448
+ return callback(new Error(response.responseHeader.serviceResult.toString()));
449
+ }
450
+ response.results = response.results || /* istanbul ignore next */ [];
451
+ (0, node_opcua_assert_1.assert)(nodesToWrite.length === response.results.length);
452
+ callback(null, isArray ? response.results : response.results[0]);
453
+ });
454
+ }
455
+ writeSingleNode(...args) {
456
+ const nodeId = args[0];
457
+ const value = args[1];
458
+ const callback = args[2];
459
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
460
+ const nodeToWrite = new node_opcua_service_write_1.WriteValue({
461
+ attributeId: node_opcua_service_read_1.AttributeIds.Value,
462
+ indexRange: undefined,
463
+ nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(nodeId),
464
+ value: new node_opcua_data_value_1.DataValue({ value })
465
+ });
466
+ this.write(nodeToWrite, (err, statusCode) => {
467
+ /* istanbul ignore next */
468
+ if (err) {
469
+ return callback(err);
470
+ }
471
+ (0, node_opcua_assert_1.assert)(statusCode);
472
+ callback(null, statusCode);
473
+ });
474
+ }
475
+ readAllAttributes(...args) {
476
+ const arg0 = args[0];
477
+ const callback = args[1];
478
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
479
+ const isArray = Array.isArray(arg0);
480
+ const nodes = isArray ? arg0 : [arg0];
481
+ const nodesToRead = [];
482
+ for (const node of nodes) {
483
+ const nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(node);
484
+ /* istanbul ignore next */
485
+ if (!nodeId) {
486
+ throw new Error("cannot coerce " + node + " to a valid NodeId");
487
+ }
488
+ for (let attributeId = 1; attributeId <= 22; attributeId++) {
489
+ nodesToRead.push({
490
+ attributeId,
491
+ dataEncoding: undefined,
492
+ indexRange: undefined,
493
+ nodeId
494
+ });
495
+ }
496
+ }
497
+ this.read(nodesToRead, (err, dataValues) => {
498
+ /* istanbul ignore next */
499
+ if (err) {
500
+ return callback(err);
501
+ }
502
+ /* istanbul ignore next */
503
+ if (!dataValues) {
504
+ return callback(new Error("Internal Error"));
505
+ }
506
+ const results = composeResult(nodes, nodesToRead, dataValues);
507
+ callback(err, isArray ? results : results[0]);
508
+ });
509
+ }
510
+ /**
511
+ * @internal
512
+ * @param args
513
+ */
514
+ read(...args) {
515
+ if (args.length === 2) {
516
+ return this.read(args[0], 0, args[1]);
517
+ }
518
+ (0, node_opcua_assert_1.assert)(args.length === 3);
519
+ const isArray = Array.isArray(args[0]);
520
+ const nodesToRead = isArray ? args[0] : [args[0]];
521
+ (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRead));
522
+ const maxAge = args[1];
523
+ const callback = args[2];
524
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
525
+ /* istanbul ignore next */
526
+ if (helpAPIChange) {
527
+ // the read method deprecation detection and warning
528
+ if (!((0, node_opcua_utils_1.getFunctionParameterNames)(callback)[1] === "dataValues" || (0, node_opcua_utils_1.getFunctionParameterNames)(callback)[1] === "dataValue")) {
529
+ warningLog(chalk.red("[NODE-OPCUA-E04] the ClientSession#read API has changed !!, please fix the client code"));
530
+ warningLog(chalk.red(" replace ..:"));
531
+ warningLog(chalk.cyan(" session.read(nodesToRead,function(err,nodesToRead,results) {}"));
532
+ warningLog(chalk.red(" with .... :"));
533
+ warningLog(chalk.cyan(" session.read(nodesToRead,function(err,dataValues) {}"));
534
+ warningLog("");
535
+ warningLog(chalk.yellow("please make sure to refactor your code and check that " +
536
+ "the second argument of your callback function is named"), chalk.cyan("dataValue" + (isArray ? "s" : "")));
537
+ warningLog(chalk.cyan("to make this exception disappear"));
538
+ throw new Error("ERROR ClientSession#read API has changed !!, please fix the client code");
539
+ }
540
+ }
541
+ // coerce nodeIds
542
+ for (const node of nodesToRead) {
543
+ node.nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(node.nodeId);
544
+ }
545
+ const request = new node_opcua_service_read_1.ReadRequest({
546
+ maxAge,
547
+ nodesToRead,
548
+ timestampsToReturn: node_opcua_service_read_1.TimestampsToReturn.Both
549
+ });
550
+ this.performMessageTransaction(request, (err, response) => {
551
+ /* istanbul ignore next */
552
+ if (err) {
553
+ return callback(err, response);
554
+ }
555
+ /* istanbul ignore next */
556
+ if (!response || !(response instanceof node_opcua_service_read_1.ReadResponse)) {
557
+ return callback(new Error("Internal Error"));
558
+ }
559
+ // perform ExtensionObject resolution
560
+ promoteOpaqueStructureWithCallback(this, response.results, () => {
561
+ response.results = response.results || /* istanbul ignore next */ [];
562
+ return callback(null, isArray ? response.results : response.results[0]);
563
+ });
564
+ });
565
+ }
566
+ emitCloseEvent(statusCode) {
567
+ if (!this._closeEventHasBeenEmitted) {
568
+ debugLog("ClientSession#emitCloseEvent");
569
+ this._closeEventHasBeenEmitted = true;
570
+ this.emit("session_closed", statusCode);
571
+ }
572
+ }
573
+ createSubscription(options, callback) {
574
+ this._defaultRequest(node_opcua_service_subscription_1.CreateSubscriptionRequest, node_opcua_service_subscription_1.CreateSubscriptionResponse, options, callback);
575
+ }
576
+ createSubscription2(...args) {
577
+ const createSubscriptionRequest = args[0];
578
+ let callback = args[1];
579
+ const subscription = new client_subscription_impl_1.ClientSubscriptionImpl(this, createSubscriptionRequest);
580
+ // tslint:disable-next-line:no-empty
581
+ subscription.on("error", (err) => {
582
+ if (callback) {
583
+ callback(err);
584
+ callback = null;
585
+ }
586
+ });
587
+ subscription.on("started", () => {
588
+ (0, node_opcua_assert_1.assert)(subscription.session === this, "expecting a session here");
589
+ if (callback) {
590
+ callback(null, subscription);
591
+ callback = null;
592
+ }
593
+ });
594
+ }
595
+ deleteSubscriptions(options, callback) {
596
+ this._defaultRequest(node_opcua_service_subscription_1.DeleteSubscriptionsRequest, node_opcua_service_subscription_1.DeleteSubscriptionsResponse, options, callback);
597
+ }
598
+ setTriggering(request, callback) {
599
+ this._defaultRequest(node_opcua_service_subscription_1.SetTriggeringRequest, node_opcua_service_subscription_1.SetTriggeringResponse, request, callback);
600
+ }
601
+ /**
602
+ * @method transferSubscriptions
603
+ * @async
604
+ */
605
+ transferSubscriptions(options, callback) {
606
+ this._defaultRequest(node_opcua_service_subscription_1.TransferSubscriptionsRequest, node_opcua_service_subscription_1.TransferSubscriptionsResponse, options, callback);
607
+ }
608
+ createMonitoredItems(options, callback) {
609
+ this._defaultRequest(node_opcua_service_subscription_1.CreateMonitoredItemsRequest, node_opcua_service_subscription_1.CreateMonitoredItemsResponse, options, callback);
610
+ }
611
+ modifyMonitoredItems(options, callback) {
612
+ this._defaultRequest(node_opcua_service_subscription_1.ModifyMonitoredItemsRequest, node_opcua_service_subscription_1.ModifyMonitoredItemsResponse, options, callback);
613
+ }
614
+ /**
615
+ *
616
+ * @method modifySubscription
617
+ * @async
618
+ * @param options {ModifySubscriptionRequest}
619
+ * @param callback {Function}
620
+ * @param callback.err {Error|null} - the Error if the async method has failed
621
+ * @param callback.response {ModifySubscriptionResponse} - the response
622
+ */
623
+ modifySubscription(options, callback) {
624
+ this._defaultRequest(node_opcua_service_subscription_1.ModifySubscriptionRequest, node_opcua_service_subscription_1.ModifySubscriptionResponse, options, callback);
625
+ }
626
+ setMonitoringMode(options, callback) {
627
+ this._defaultRequest(node_opcua_service_subscription_1.SetMonitoringModeRequest, node_opcua_service_subscription_1.SetMonitoringModeResponse, options, callback);
628
+ }
629
+ /**
630
+ *
631
+ * @method publish
632
+ * @async
633
+ * @param options {PublishRequest}
634
+ * @param callback {Function}
635
+ * @param callback.err {Error|null} - the Error if the async method has failed
636
+ * @param callback.response {PublishResponse} - the response
637
+ */
638
+ publish(options, callback) {
639
+ this._defaultRequest(node_opcua_service_subscription_1.PublishRequest, node_opcua_service_subscription_1.PublishResponse, options, callback);
640
+ }
641
+ /**
642
+ *
643
+ * @method republish
644
+ * @async
645
+ * @param options {RepublishRequest}
646
+ * @param callback the callback
647
+ */
648
+ republish(options, callback) {
649
+ this._defaultRequest(node_opcua_service_subscription_1.RepublishRequest, node_opcua_service_subscription_1.RepublishResponse, options, callback);
650
+ }
651
+ /**
652
+ *
653
+ * @method deleteMonitoredItems
654
+ * @async
655
+ * @param options {DeleteMonitoredItemsRequest}
656
+ * @param callback {Function}
657
+ * @param callback.err {Error|null} - the Error if the async method has failed
658
+ */
659
+ deleteMonitoredItems(options, callback) {
660
+ this._defaultRequest(node_opcua_service_subscription_1.DeleteMonitoredItemsRequest, node_opcua_service_subscription_1.DeleteMonitoredItemsResponse, options, callback);
661
+ }
662
+ /**
663
+ * @internal
664
+ */
665
+ setPublishingMode(...args) {
666
+ const publishingEnabled = args[0];
667
+ const isArray = Array.isArray(args[1]);
668
+ const subscriptionIds = isArray ? args[1] : [args[1]];
669
+ const callback = args[2];
670
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
671
+ (0, node_opcua_assert_1.assert)(publishingEnabled === true || publishingEnabled === false);
672
+ const options = new node_opcua_service_subscription_1.SetPublishingModeRequest({
673
+ publishingEnabled,
674
+ subscriptionIds
675
+ });
676
+ this._defaultRequest(node_opcua_service_subscription_1.SetPublishingModeRequest, node_opcua_service_subscription_1.SetPublishingModeResponse, options, (err, response) => {
677
+ /* istanbul ignore next */
678
+ if (err) {
679
+ return callback(err);
680
+ }
681
+ /* istanbul ignore next */
682
+ if (!response) {
683
+ return callback(new Error("Internal Error"));
684
+ }
685
+ response.results = response.results || /* istanbul ignore next */ [];
686
+ callback(err, isArray ? response.results : response.results[0]);
687
+ });
688
+ }
689
+ /**
690
+ * @internal
691
+ * @param args
692
+ */
693
+ translateBrowsePath(...args) {
694
+ const isArray = Array.isArray(args[0]);
695
+ const browsePaths = isArray ? args[0] : [args[0]];
696
+ const callback = args[1];
697
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
698
+ const request = new node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsRequest({ browsePaths });
699
+ this.performMessageTransaction(request, (err, response) => {
700
+ /* istanbul ignore next */
701
+ if (err) {
702
+ return callback(err, response);
703
+ }
704
+ /* istanbul ignore next */
705
+ if (!response || !(response instanceof node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse)) {
706
+ return callback(new Error("Internal Error"));
707
+ }
708
+ response.results = response.results || /* istanbul ignore next */ [];
709
+ callback(null, isArray ? response.results : response.results[0]);
710
+ });
711
+ }
712
+ channelId() {
713
+ return this._client !== null && this._client._secureChannel !== null && this._client._secureChannel.isOpened()
714
+ ? this._client._secureChannel.channelId
715
+ : -1;
716
+ }
717
+ isChannelValid() {
718
+ /* istanbul ignore next */
719
+ if (!this._client) {
720
+ debugLog(chalk.red("Warning SessionClient is null ?"));
721
+ }
722
+ return this._client !== null && this._client._secureChannel !== null && this._client._secureChannel.isOpened();
723
+ }
724
+ performMessageTransaction(request, callback) {
725
+ if (!this._client) {
726
+ // session may have been closed by user ... but is still in used !!
727
+ return callback(new Error("Session has been closed and should not be used to perform a transaction anymore"));
728
+ }
729
+ if (!this.isChannelValid()) {
730
+ // the secure channel is broken, may be the server has crashed or the network cable has been disconnected
731
+ // for a long time
732
+ // we may need to queue this transaction, as a secure token may be being reprocessed
733
+ debugLog(chalk.bgWhite.red("!!! Performing transaction on invalid channel !!! ", request.constructor.name));
734
+ return callback(new Error("Invalid Channel after performing transaction on " + request.constructor.name));
735
+ }
736
+ this._reconnecting.pendingTransactions = this._reconnecting.pendingTransactions || [];
737
+ this._reconnecting.pendingTransactionsCount = this._reconnecting.pendingTransactionsCount || 0;
738
+ const isPublishRequest = request instanceof node_opcua_service_subscription_1.PublishRequest;
739
+ if (isPublishRequest) {
740
+ return this._performMessageTransaction(request, callback);
741
+ }
742
+ if (this._reconnecting.pendingTransactionsCount > 0) {
743
+ /* istanbul ignore next */
744
+ if (this._reconnecting.pendingTransactions.length > 10) {
745
+ if (!pendingTransactionMessageDisplayed) {
746
+ pendingTransactionMessageDisplayed = true;
747
+ warningLog("[NODE-OPCUA-W21]", "Pending transactions: ", this._reconnecting.pendingTransactions.map((a) => a.request.constructor.name).join(" "));
748
+ warningLog("[NODE-OPCUA-W22]", chalk.yellow("Warning : your opcua client is sending multiple requests simultaneously to the server", request.constructor.name), "\n", chalk.yellow(" please fix your application code"));
749
+ }
750
+ }
751
+ else if (this._reconnecting.pendingTransactions.length > 3) {
752
+ debugLog(chalk.yellow("Warning : your client is sending multiple requests simultaneously to the server", request.constructor.name));
753
+ }
754
+ this._reconnecting.pendingTransactions.push({ request, callback });
755
+ return;
756
+ }
757
+ this.processTransactionQueue(request, callback);
758
+ }
759
+ _performMessageTransaction(request, callback) {
760
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
761
+ /* istanbul ignore next */
762
+ if (!this._client) {
763
+ // session may have been closed by user ... but is still in used !!
764
+ return callback(new Error("Session has been closed and should not be used to perform a transaction anymore"));
765
+ }
766
+ if (!this.isChannelValid()) {
767
+ // the secure channel is broken, may be the server has crashed or the network cable has been disconnected
768
+ // for a long time
769
+ // we may need to queue this transaction, as a secure token may be being reprocessed
770
+ debugLog(chalk.bgWhite.red("!!! Performing transaction on invalid channel !!! ", request.constructor.name));
771
+ return callback(new Error("Invalid Channel BadConnectionClosed"));
772
+ }
773
+ // is this stuff useful?
774
+ if (request.requestHeader) {
775
+ request.requestHeader.authenticationToken = this.authenticationToken;
776
+ }
777
+ this.lastRequestSentTime = new Date();
778
+ this._client.performMessageTransaction(request, (err, response) => {
779
+ this.lastResponseReceivedTime = new Date();
780
+ /* istanbul ignore next */
781
+ if (err) {
782
+ if (response && response.responseHeader.serviceDiagnostics) {
783
+ err.serviceDiagnostics = response.responseHeader.serviceDiagnostics;
784
+ }
785
+ if (response && response.diagnosticInfos) {
786
+ err.diagnosticsInfo = response.diagnosticInfos;
787
+ }
788
+ return callback(err);
789
+ }
790
+ /* istanbul ignore next */
791
+ if (!response) {
792
+ return callback(new Error("internal Error"));
793
+ }
794
+ /* istanbul ignore next */
795
+ if (response.responseHeader.serviceResult.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
796
+ err = new Error(" ServiceResult is " +
797
+ response.responseHeader.serviceResult.toString() +
798
+ " request was " +
799
+ request.constructor.name);
800
+ if (response && response.responseHeader.serviceDiagnostics) {
801
+ err.serviceDiagnostics = response.responseHeader.serviceDiagnostics;
802
+ }
803
+ if (response && response.diagnosticInfos) {
804
+ err.diagnosticsInfo = response.diagnosticInfos;
805
+ }
806
+ return callback(err, response);
807
+ }
808
+ return callback(null, response);
809
+ });
810
+ }
811
+ /**
812
+ * evaluate the remaining time for the session
813
+ *
814
+ *
815
+ * evaluate the time in milliseconds that the session will live
816
+ * on the server end from now.
817
+ * The remaining live time is calculated based on when the last message was sent to the server
818
+ * and the session timeout.
819
+ *
820
+ * * In normal operation , when server and client communicates on a regular
821
+ * basis, evaluateRemainingLifetime will return a number slightly below
822
+ * session.timeout
823
+ *
824
+ * * when the client and server cannot communicate due to a network issue
825
+ * (or a server crash), evaluateRemainingLifetime returns the estimated number
826
+ * of milliseconds before the server (if not crash) will keep the session alive
827
+ * on its end to allow a automatic reconnection with session.
828
+ *
829
+ * * When evaluateRemainingLifetime returns zero , this mean that
830
+ * the session has probably ended on the server side and will have to be recreated
831
+ * from scratch in case of a reconnection.
832
+ *
833
+ * @return the number of milliseconds before session expires
834
+ */
835
+ evaluateRemainingLifetime() {
836
+ const now = Date.now();
837
+ const expiryTime = this.lastRequestSentTime.getTime() + this.timeout;
838
+ return Math.max(0, expiryTime - now);
839
+ }
840
+ _terminatePublishEngine() {
841
+ if (this._publishEngine) {
842
+ this._publishEngine.terminate();
843
+ this._publishEngine = null;
844
+ }
845
+ }
846
+ /**
847
+ * @internal
848
+ * @param args
849
+ */
850
+ close(...args) {
851
+ if (arguments.length === 1) {
852
+ return this.close(true, args[0]);
853
+ }
854
+ const deleteSubscription = args[0];
855
+ const callback = args[1];
856
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
857
+ (0, node_opcua_assert_1.assert)(typeof deleteSubscription === "boolean");
858
+ /* istanbul ignore next */
859
+ if (!this._client) {
860
+ debugLog("ClientSession#close : warning, client is already closed");
861
+ return callback(); // already close ?
862
+ }
863
+ (0, node_opcua_assert_1.assert)(this._client);
864
+ this._terminatePublishEngine();
865
+ this._client.closeSession(this, deleteSubscription, (err) => {
866
+ debugLog("session Close err ", err ? err.message : "null");
867
+ callback();
868
+ });
869
+ }
870
+ /**
871
+ * @method hasBeenClosed
872
+ * @return {Boolean}
873
+ */
874
+ hasBeenClosed() {
875
+ return (0, node_opcua_utils_1.isNullOrUndefined)(this._client) || this._closed || this._closeEventHasBeenEmitted;
876
+ }
877
+ /**
878
+ * @internal
879
+ * @param args
880
+ */
881
+ call(...args) {
882
+ const isArray = Array.isArray(args[0]);
883
+ const methodsToCall = isArray ? args[0] : [args[0]];
884
+ (0, node_opcua_assert_1.assert)(Array.isArray(methodsToCall));
885
+ const callback = args[1];
886
+ // Note : The client has no explicit address space and therefore will struggle to
887
+ // access the method arguments signature.
888
+ // There are two methods that can be considered:
889
+ // - get the object definition by querying the server
890
+ // - load a fake address space to have some thing to query on our end
891
+ // const request = this._client.factory.constructObjectId("CallRequest",{ methodsToCall: methodsToCall});
892
+ const request = new node_opcua_service_call_1.CallRequest({ methodsToCall });
893
+ this.performMessageTransaction(request, (err, response) => {
894
+ /* istanbul ignore next */
895
+ if (err) {
896
+ return callback(err);
897
+ }
898
+ /* istanbul ignore next */
899
+ if (!response || !(response instanceof node_opcua_service_call_1.CallResponse)) {
900
+ return callback(new Error("internal error"));
901
+ }
902
+ response.results = response.results || [];
903
+ promoteOpaqueStructure3WithCallback(this, response.results, () => {
904
+ callback(null, isArray ? response.results : response.results[0]);
905
+ });
906
+ });
907
+ }
908
+ getMonitoredItems(...args) {
909
+ const subscriptionId = args[0];
910
+ const callback = args[1];
911
+ // <UAObject NodeId="i=2253" BrowseName="Server">
912
+ // <UAMethod NodeId="i=11492" BrowseName="GetMonitoredItems"
913
+ // ParentNodeId="i=2253" MethodDeclarationId="i=11489">
914
+ // <UAMethod NodeId="i=11489" BrowseName="GetMonitoredItems" ParentNodeId="i=2004">
915
+ const methodsToCall = new node_opcua_service_call_1.CallMethodRequest({
916
+ inputArguments: [
917
+ // BaseDataType
918
+ { dataType: node_opcua_variant_1.DataType.UInt32, value: subscriptionId }
919
+ ],
920
+ methodId: (0, node_opcua_nodeid_1.coerceNodeId)("ns=0;i=11492"),
921
+ objectId: (0, node_opcua_nodeid_1.coerceNodeId)("ns=0;i=2253") // ObjectId.Server
922
+ });
923
+ this.call(methodsToCall, (err, result) => {
924
+ /* istanbul ignore next */
925
+ if (err) {
926
+ return callback(err);
927
+ }
928
+ /* istanbul ignore next */
929
+ if (!result) {
930
+ return callback(new Error("internal error"));
931
+ }
932
+ /* istanbul ignore next */
933
+ if (result.statusCode.isNot(node_opcua_status_code_1.StatusCodes.Good)) {
934
+ callback(new Error(result.statusCode.toString()));
935
+ }
936
+ else {
937
+ result.outputArguments = result.outputArguments || [];
938
+ (0, node_opcua_assert_1.assert)(result.outputArguments.length === 2);
939
+ const data = {
940
+ clientHandles: result.outputArguments[1].value,
941
+ serverHandles: result.outputArguments[0].value //
942
+ };
943
+ // Note some server might return null array
944
+ // let make sure we have Uint32Array and not a null pointer
945
+ data.serverHandles = data.serverHandles || /* istanbul ignore next */ emptyUint32Array;
946
+ data.clientHandles = data.clientHandles || /* istanbul ignore next */ emptyUint32Array;
947
+ (0, node_opcua_assert_1.assert)(data.serverHandles instanceof Uint32Array);
948
+ (0, node_opcua_assert_1.assert)(data.clientHandles instanceof Uint32Array);
949
+ callback(null, data);
950
+ }
951
+ });
952
+ }
953
+ /**
954
+ * @internal
955
+ */
956
+ getArgumentDefinition(...args) {
957
+ const methodId = args[0];
958
+ const callback = args[1];
959
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
960
+ return (0, node_opcua_pseudo_session_1.getArgumentDefinitionHelper)(this, methodId, callback);
961
+ }
962
+ registerNodes(...args) {
963
+ const nodesToRegister = args[0];
964
+ const callback = args[1];
965
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
966
+ (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRegister));
967
+ const request = new node_opcua_service_register_node_1.RegisterNodesRequest({
968
+ nodesToRegister: nodesToRegister.map(node_opcua_nodeid_1.resolveNodeId)
969
+ });
970
+ this.performMessageTransaction(request, (err, response) => {
971
+ /* istanbul ignore next */
972
+ if (err) {
973
+ return callback(err);
974
+ }
975
+ /* istanbul ignore next */
976
+ if (!response || !(response instanceof node_opcua_service_register_node_1.RegisterNodesResponse)) {
977
+ return callback(new Error("Internal Error"));
978
+ }
979
+ response.registeredNodeIds = response.registeredNodeIds || /* istanbul ignore next */ [];
980
+ callback(null, response.registeredNodeIds);
981
+ });
982
+ }
983
+ unregisterNodes(...args) {
984
+ const nodesToUnregister = args[0];
985
+ const callback = args[1];
986
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
987
+ (0, node_opcua_assert_1.assert)(Array.isArray(nodesToUnregister));
988
+ const request = new node_opcua_service_register_node_1.UnregisterNodesRequest({
989
+ nodesToUnregister: nodesToUnregister.map(node_opcua_nodeid_1.resolveNodeId)
990
+ });
991
+ this.performMessageTransaction(request, (err, response) => {
992
+ /* istanbul ignore next */
993
+ if (err) {
994
+ return callback(err);
995
+ }
996
+ /* istanbul ignore next */
997
+ if (!response || !(response instanceof node_opcua_service_register_node_1.UnregisterNodesResponse)) {
998
+ return callback(new Error("Internal Error"));
999
+ }
1000
+ callback();
1001
+ });
1002
+ }
1003
+ queryFirst(...args) {
1004
+ const queryFirstRequest = args[0];
1005
+ const callback = args[1];
1006
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
1007
+ const request = new node_opcua_service_query_1.QueryFirstRequest(queryFirstRequest);
1008
+ this.performMessageTransaction(request, (err, response) => {
1009
+ /* istanbul ignore next */
1010
+ if (err) {
1011
+ return callback(err);
1012
+ }
1013
+ /* istanbul ignore next */
1014
+ if (!response || !(response instanceof node_opcua_service_query_1.QueryFirstResponse)) {
1015
+ return callback(new Error("internal error"));
1016
+ }
1017
+ callback(null, response);
1018
+ });
1019
+ }
1020
+ startKeepAliveManager() {
1021
+ if (this._keepAliveManager) {
1022
+ // "keepAliveManger already started"
1023
+ return;
1024
+ }
1025
+ this._keepAliveManager = new client_session_keepalive_manager_1.ClientSessionKeepAliveManager(this);
1026
+ this._keepAliveManager.on("failure", () => {
1027
+ /**
1028
+ * raised when a keep-alive request has failed on the session, may be the session has timeout
1029
+ * unexpectedly on the server side, may be the connection is broken.
1030
+ * @event keepalive_failure
1031
+ */
1032
+ this.emit("keepalive_failure");
1033
+ });
1034
+ this._keepAliveManager.on("keepalive", (state, count) => {
1035
+ /**
1036
+ * @event keepalive
1037
+ */
1038
+ this.emit("keepalive", state, count);
1039
+ });
1040
+ this._keepAliveManager.start();
1041
+ }
1042
+ stopKeepAliveManager() {
1043
+ if (this._keepAliveManager) {
1044
+ this._keepAliveManager.stop();
1045
+ this._keepAliveManager = undefined;
1046
+ }
1047
+ }
1048
+ dispose() {
1049
+ (0, node_opcua_assert_1.assert)(this._closeEventHasBeenEmitted);
1050
+ this._terminatePublishEngine();
1051
+ this.stopKeepAliveManager();
1052
+ this.removeAllListeners();
1053
+ //
1054
+ const privateThis = this;
1055
+ if (!(!privateThis.pendingTransactions || privateThis.pendingTransactions.length === 0)) {
1056
+ // tslint:disable-next-line: no-console
1057
+ console.log("dispose when pendingTransactions is not empty ");
1058
+ }
1059
+ }
1060
+ toString() {
1061
+ const now = Date.now();
1062
+ const lap1 = now - this.lastRequestSentTime.getTime();
1063
+ const lap2 = now - this.lastResponseReceivedTime.getTime();
1064
+ const timeoutDelay = this.timeout - lap1;
1065
+ const timeoutInfo = timeoutDelay < 0
1066
+ ? chalk.red(" expired since " + -timeoutDelay / 1000 + " seconds")
1067
+ : chalk.green(" timeout in " + timeoutDelay / 1000 + " seconds");
1068
+ let str = "";
1069
+ str += " name..................... " + this.name;
1070
+ str += "\n sessionId................ " + this.sessionId.toString();
1071
+ str += "\n authenticationToken...... " + (this.authenticationToken ? this.authenticationToken.toString() : "");
1072
+ str += "\n timeout.................. " + this.timeout + "ms" + timeoutInfo;
1073
+ str += "\n serverNonce.............. " + (this.serverNonce ? this.serverNonce.toString("hex") : "");
1074
+ str += "\n serverCertificate........ " + (0, node_opcua_utils_1.buffer_ellipsis)(this.serverCertificate);
1075
+ // xx console.log(" serverSignature.......... ", this.serverSignature);
1076
+ str += "\n lastRequestSentTime...... " + new Date(this.lastRequestSentTime).toISOString() + " (" + lap1 + ")";
1077
+ str += "\n lastResponseReceivedTime. " + new Date(this.lastResponseReceivedTime).toISOString() + " (" + lap2 + ")";
1078
+ str += "\n isReconnecting........... " + this.isReconnecting;
1079
+ str += "\n isValidChannel........... " + this.isChannelValid() + " has been closed " + this.hasBeenClosed();
1080
+ str += "\n channelId................ " + this.channelId();
1081
+ str += "\n remaining life time...... " + this.evaluateRemainingLifetime();
1082
+ str += "\n subscription count....... " + this.subscriptionCount;
1083
+ if (this._client && this._client._secureChannel) {
1084
+ if (this._client._secureChannel.securityToken) {
1085
+ str += "\n reviseTokenLifetime...... " + this._client._secureChannel.securityToken.revisedLifetime;
1086
+ }
1087
+ }
1088
+ return str;
1089
+ }
1090
+ getBuiltInDataType(...args) {
1091
+ const nodeId = args[0];
1092
+ const callback = args[1];
1093
+ return (0, node_opcua_pseudo_session_1.getBuiltInDataType)(this, nodeId, callback);
1094
+ }
1095
+ resumePublishEngine() {
1096
+ (0, node_opcua_assert_1.assert)(this._publishEngine);
1097
+ if (this._publishEngine && this._publishEngine.subscriptionCount > 0) {
1098
+ this._publishEngine.replenish_publish_request_queue();
1099
+ }
1100
+ }
1101
+ readNamespaceArray(...args) {
1102
+ const callback = args[0];
1103
+ this.read({
1104
+ attributeId: node_opcua_service_read_1.AttributeIds.Value,
1105
+ nodeId: (0, node_opcua_nodeid_1.resolveNodeId)("Server_NamespaceArray")
1106
+ }, (err, dataValue) => {
1107
+ /* istanbul ignore next */
1108
+ if (err) {
1109
+ return callback(err);
1110
+ }
1111
+ /* istanbul ignore next */
1112
+ if (!dataValue) {
1113
+ return callback(new Error("Internal Error"));
1114
+ }
1115
+ /* istanbul ignore next */
1116
+ if (dataValue.statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1117
+ return callback(new Error("readNamespaceArray : " + dataValue.statusCode.toString()));
1118
+ }
1119
+ (0, node_opcua_assert_1.assert)(dataValue.value.value instanceof Array);
1120
+ this._namespaceArray = dataValue.value.value; // keep a cache
1121
+ callback(null, this._namespaceArray);
1122
+ });
1123
+ }
1124
+ getNamespaceIndex(namespaceUri) {
1125
+ (0, node_opcua_assert_1.assert)(this._namespaceArray, "please make sure that readNamespaceArray has been called");
1126
+ return this._namespaceArray.indexOf(namespaceUri);
1127
+ }
1128
+ // tslint:disable:no-empty
1129
+ // ---------------------------------------- Alarm & condition stub
1130
+ disableCondition() {
1131
+ /** empty */
1132
+ }
1133
+ enableCondition() {
1134
+ /** empty */
1135
+ }
1136
+ addCommentCondition(_conditionId, _eventId, _comment, _callback) {
1137
+ /** empty */
1138
+ }
1139
+ confirmCondition(_conditionId, _eventId, _comment, _callback) {
1140
+ /** empty */
1141
+ }
1142
+ acknowledgeCondition(_conditionId, _eventId, _comment, _callback) {
1143
+ /** empty */
1144
+ }
1145
+ findMethodId(_nodeId, _methodName, _callback) {
1146
+ /** empty */
1147
+ }
1148
+ _callMethodCondition(_methodName, _conditionId, _eventId, _comment, _callback) {
1149
+ /** empty */
1150
+ }
1151
+ extractNamespaceDataType() {
1152
+ return __awaiter(this, void 0, void 0, function* () {
1153
+ return (0, node_opcua_client_dynamic_extension_object_1.getExtraDataTypeManager)(this);
1154
+ });
1155
+ }
1156
+ getExtensionObjectConstructor(dataTypeNodeId) {
1157
+ return __awaiter(this, void 0, void 0, function* () {
1158
+ return (0, node_opcua_client_dynamic_extension_object_1.getExtensionObjectConstructor)(this, dataTypeNodeId);
1159
+ });
1160
+ }
1161
+ /**
1162
+ *
1163
+ * @param dataType
1164
+ * @param pojo
1165
+ * @async
1166
+ */
1167
+ constructExtensionObject(dataType, pojo) {
1168
+ return __awaiter(this, void 0, void 0, function* () {
1169
+ const Constructor = yield this.getExtensionObjectConstructor(dataType);
1170
+ return new Constructor(pojo);
1171
+ });
1172
+ }
1173
+ _defaultRequest(requestClass, _responseClass, options, callback) {
1174
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
1175
+ const request = options instanceof requestClass ? options : new requestClass(options);
1176
+ /* istanbul ignore next */
1177
+ if (doDebug) {
1178
+ request.trace = new Error("").stack;
1179
+ }
1180
+ /* istanbul ignore next */
1181
+ if (this._closeEventHasBeenEmitted) {
1182
+ debugLog("ClientSession#_defaultRequest => session has been closed !!", request.toString());
1183
+ setImmediate(() => {
1184
+ callback(new Error("ClientSession is closed !"));
1185
+ });
1186
+ return;
1187
+ }
1188
+ this.performMessageTransaction(request, (err, response) => {
1189
+ if (this._closeEventHasBeenEmitted) {
1190
+ debugLog("ClientSession#_defaultRequest ... err =", err ? err.message : "null", response ? response.toString() : " null");
1191
+ }
1192
+ /* istanbul ignore next */
1193
+ if (err) {
1194
+ debugLog("Client session : performMessageTransaction error = ", err.message);
1195
+ // let intercept interesting error message
1196
+ if (err.message.match(/BadSessionClosed/)) {
1197
+ // the session has been closed by Server
1198
+ // probably due to timeout issue
1199
+ // let's print some statistics
1200
+ const now = Date.now();
1201
+ /* istanbul ignore next */
1202
+ if (doDebug) {
1203
+ debugLog(chalk.bgWhite.red(" server send BadSessionClosed !"));
1204
+ debugLog(chalk.bgWhite.red(" request was "), request.toString());
1205
+ debugLog(" timeout.................. ", this.timeout);
1206
+ debugLog(" lastRequestSentTime...... ", new Date(this.lastRequestSentTime).toISOString(), now - this.lastRequestSentTime.getTime());
1207
+ debugLog(" lastResponseReceivedTime. ", new Date(this.lastResponseReceivedTime).toISOString(), now - this.lastResponseReceivedTime.getTime());
1208
+ }
1209
+ // DO NOT TERMINATE SESSION, as we will need a publishEngine when we
1210
+ // reconnect this._terminatePublishEngine();
1211
+ if (false) {
1212
+ // ER 10.2019
1213
+ /**
1214
+ * send when the session has been closed by the server ( probably due to inactivity and timeout)
1215
+ * @event session_closed
1216
+ */
1217
+ this.emitCloseEvent(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1218
+ }
1219
+ }
1220
+ return callback(err, response);
1221
+ }
1222
+ callback(null, response);
1223
+ });
1224
+ }
1225
+ recreate_session_and_reperform_transaction(request, callback) {
1226
+ if (this.recursive_repair_detector >= 1) {
1227
+ // tslint:disable-next-line: no-console
1228
+ console.log("recreate_session_and_reperform_transaction => Already in Progress");
1229
+ return callback(new Error("Cannot recreate session"));
1230
+ }
1231
+ this.recursive_repair_detector += 1;
1232
+ debugLog(chalk.red("----------------> Repairing Client Session as Server believes it is invalid now "));
1233
+ (0, reconnection_1.repair_client_session)(this._client, this, (err) => {
1234
+ this.recursive_repair_detector -= 1;
1235
+ if (err) {
1236
+ debugLog(chalk.red("----------------> session Repaired has failed with error", err.message));
1237
+ return callback(err);
1238
+ }
1239
+ debugLog(chalk.red("----------------> session Repaired, now redoing original transaction "));
1240
+ this._performMessageTransaction(request, callback);
1241
+ });
1242
+ }
1243
+ }
1244
+ exports.ClientSessionImpl = ClientSessionImpl;
1245
+ function promoteOpaqueStructure2(session, callMethodResult) {
1246
+ return __awaiter(this, void 0, void 0, function* () {
1247
+ if (!callMethodResult || !callMethodResult.outputArguments || callMethodResult.outputArguments.length === 0) {
1248
+ return;
1249
+ }
1250
+ yield (0, node_opcua_client_dynamic_extension_object_1.promoteOpaqueStructure)(session, callMethodResult.outputArguments.map((a) => ({ value: a })));
1251
+ });
1252
+ }
1253
+ function promoteOpaqueStructure3(session, callMethodResults) {
1254
+ return __awaiter(this, void 0, void 0, function* () {
1255
+ // construct dataTypeManager if not already present
1256
+ const extraDataTypeManager = yield (0, node_opcua_client_dynamic_extension_object_1.getExtraDataTypeManager)(session);
1257
+ const promises = callMethodResults.map((x) => __awaiter(this, void 0, void 0, function* () { return promoteOpaqueStructure2(session, x); }));
1258
+ yield Promise.all(promises);
1259
+ });
1260
+ }
1261
+ // tslint:disable:no-var-requires
1262
+ // tslint:disable:max-line-length
1263
+ const thenify = require("thenify");
1264
+ const callbackify = require("callbackify");
1265
+ const opts = { multiArgs: false };
1266
+ const promoteOpaqueStructureWithCallback = callbackify(node_opcua_client_dynamic_extension_object_1.promoteOpaqueStructure);
1267
+ const promoteOpaqueStructure3WithCallback = callbackify(promoteOpaqueStructure3);
1268
+ ClientSessionImpl.prototype.browse = thenify.withCallback(ClientSessionImpl.prototype.browse, opts);
1269
+ ClientSessionImpl.prototype.browseNext = thenify.withCallback(ClientSessionImpl.prototype.browseNext, opts);
1270
+ ClientSessionImpl.prototype.readVariableValue = thenify.withCallback(ClientSessionImpl.prototype.readVariableValue, opts);
1271
+ ClientSessionImpl.prototype.readHistoryValue = thenify.withCallback(ClientSessionImpl.prototype.readHistoryValue, opts);
1272
+ ClientSessionImpl.prototype.readAggregateValue = thenify.withCallback(ClientSessionImpl.prototype.readAggregateValue, opts);
1273
+ ClientSessionImpl.prototype.historyRead = thenify.withCallback(ClientSessionImpl.prototype.historyRead, opts);
1274
+ ClientSessionImpl.prototype.write = thenify.withCallback(ClientSessionImpl.prototype.write, opts);
1275
+ ClientSessionImpl.prototype.writeSingleNode = thenify.withCallback(ClientSessionImpl.prototype.writeSingleNode, opts);
1276
+ ClientSessionImpl.prototype.readAllAttributes = thenify.withCallback(ClientSessionImpl.prototype.readAllAttributes, opts);
1277
+ ClientSessionImpl.prototype.read = thenify.withCallback(ClientSessionImpl.prototype.read, opts);
1278
+ ClientSessionImpl.prototype.createSubscription = thenify.withCallback(ClientSessionImpl.prototype.createSubscription, opts);
1279
+ ClientSessionImpl.prototype.createSubscription2 = thenify.withCallback(ClientSessionImpl.prototype.createSubscription2, opts);
1280
+ ClientSessionImpl.prototype.deleteSubscriptions = thenify.withCallback(ClientSessionImpl.prototype.deleteSubscriptions, opts);
1281
+ ClientSessionImpl.prototype.transferSubscriptions = thenify.withCallback(ClientSessionImpl.prototype.transferSubscriptions, opts);
1282
+ ClientSessionImpl.prototype.createMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.createMonitoredItems, opts);
1283
+ ClientSessionImpl.prototype.modifyMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.modifyMonitoredItems, opts);
1284
+ ClientSessionImpl.prototype.modifySubscription = thenify.withCallback(ClientSessionImpl.prototype.modifySubscription, opts);
1285
+ ClientSessionImpl.prototype.setTriggering = thenify.withCallback(ClientSessionImpl.prototype.setTriggering, opts);
1286
+ ClientSessionImpl.prototype.setMonitoringMode = thenify.withCallback(ClientSessionImpl.prototype.setMonitoringMode, opts);
1287
+ ClientSessionImpl.prototype.publish = thenify.withCallback(ClientSessionImpl.prototype.publish, opts);
1288
+ ClientSessionImpl.prototype.republish = thenify.withCallback(ClientSessionImpl.prototype.republish, opts);
1289
+ ClientSessionImpl.prototype.deleteMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.deleteMonitoredItems, opts);
1290
+ ClientSessionImpl.prototype.setPublishingMode = thenify.withCallback(ClientSessionImpl.prototype.setPublishingMode, opts);
1291
+ ClientSessionImpl.prototype.translateBrowsePath = thenify.withCallback(ClientSessionImpl.prototype.translateBrowsePath, opts);
1292
+ ClientSessionImpl.prototype.performMessageTransaction = thenify.withCallback(ClientSessionImpl.prototype.performMessageTransaction, opts);
1293
+ ClientSessionImpl.prototype.close = thenify.withCallback(ClientSessionImpl.prototype.close, opts);
1294
+ ClientSessionImpl.prototype.call = thenify.withCallback(ClientSessionImpl.prototype.call, opts);
1295
+ ClientSessionImpl.prototype.getMonitoredItems = thenify.withCallback(ClientSessionImpl.prototype.getMonitoredItems, opts);
1296
+ ClientSessionImpl.prototype.getArgumentDefinition = thenify.withCallback(ClientSessionImpl.prototype.getArgumentDefinition, opts);
1297
+ ClientSessionImpl.prototype.queryFirst = thenify.withCallback(ClientSessionImpl.prototype.queryFirst, opts);
1298
+ ClientSessionImpl.prototype.registerNodes = thenify.withCallback(ClientSessionImpl.prototype.registerNodes, opts);
1299
+ ClientSessionImpl.prototype.unregisterNodes = thenify.withCallback(ClientSessionImpl.prototype.unregisterNodes, opts);
1300
+ ClientSessionImpl.prototype.readNamespaceArray = thenify.withCallback(ClientSessionImpl.prototype.readNamespaceArray, opts);
1301
+ ClientSessionImpl.prototype.getBuiltInDataType = thenify.withCallback(ClientSessionImpl.prototype.getBuiltInDataType, opts);
1302
+ ClientSessionImpl.prototype.constructExtensionObject = callbackify(ClientSessionImpl.prototype.constructExtensionObject);
1302
1303
  //# sourceMappingURL=client_session_impl.js.map