node-opcua-server 2.71.0 → 2.72.2

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 (65) hide show
  1. package/dist/base_server.d.ts +110 -110
  2. package/dist/base_server.js +473 -473
  3. package/dist/factory.d.ts +12 -12
  4. package/dist/factory.js +23 -23
  5. package/dist/history_server_capabilities.d.ts +35 -35
  6. package/dist/history_server_capabilities.js +43 -43
  7. package/dist/i_channel_data.d.ts +13 -13
  8. package/dist/i_channel_data.js +2 -2
  9. package/dist/i_register_server_manager.d.ts +16 -16
  10. package/dist/i_register_server_manager.js +2 -2
  11. package/dist/i_server_side_publish_engine.d.ts +36 -36
  12. package/dist/i_server_side_publish_engine.js +49 -49
  13. package/dist/i_socket_data.d.ts +11 -11
  14. package/dist/i_socket_data.js +2 -2
  15. package/dist/index.d.ts +15 -15
  16. package/dist/index.js +31 -31
  17. package/dist/monitored_item.d.ts +177 -177
  18. package/dist/monitored_item.js +998 -998
  19. package/dist/node_sampler.d.ts +3 -3
  20. package/dist/node_sampler.js +75 -75
  21. package/dist/opcua_server.d.ts +650 -647
  22. package/dist/opcua_server.js +2392 -2385
  23. package/dist/opcua_server.js.map +1 -1
  24. package/dist/queue.d.ts +11 -11
  25. package/dist/queue.js +71 -71
  26. package/dist/register_server_manager.d.ts +96 -96
  27. package/dist/register_server_manager.js +584 -584
  28. package/dist/register_server_manager_hidden.d.ts +17 -17
  29. package/dist/register_server_manager_hidden.js +27 -27
  30. package/dist/register_server_manager_mdns_only.d.ts +22 -22
  31. package/dist/register_server_manager_mdns_only.js +55 -55
  32. package/dist/server_capabilities.d.ts +148 -61
  33. package/dist/server_capabilities.js +91 -108
  34. package/dist/server_capabilities.js.map +1 -1
  35. package/dist/server_end_point.d.ts +183 -183
  36. package/dist/server_end_point.js +817 -816
  37. package/dist/server_end_point.js.map +1 -1
  38. package/dist/server_engine.d.ts +317 -316
  39. package/dist/server_engine.js +1716 -1688
  40. package/dist/server_engine.js.map +1 -1
  41. package/dist/server_publish_engine.d.ts +112 -112
  42. package/dist/server_publish_engine.js +530 -530
  43. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -16
  44. package/dist/server_publish_engine_for_orphan_subscriptions.js +49 -49
  45. package/dist/server_session.d.ts +181 -181
  46. package/dist/server_session.js +738 -738
  47. package/dist/server_session.js.map +1 -1
  48. package/dist/server_subscription.d.ts +415 -395
  49. package/dist/server_subscription.js +1334 -1316
  50. package/dist/server_subscription.js.map +1 -1
  51. package/dist/sessions_compatible_for_transfer.d.ts +2 -2
  52. package/dist/sessions_compatible_for_transfer.js +36 -36
  53. package/dist/user_manager.d.ts +32 -32
  54. package/dist/user_manager.js +74 -74
  55. package/dist/user_manager_ua.d.ts +3 -3
  56. package/dist/user_manager_ua.js +39 -39
  57. package/dist/validate_filter.d.ts +5 -5
  58. package/dist/validate_filter.js +60 -60
  59. package/package.json +34 -34
  60. package/source/opcua_server.ts +27 -16
  61. package/source/server_capabilities.ts +178 -91
  62. package/source/server_end_point.ts +9 -8
  63. package/source/server_engine.ts +30 -1
  64. package/source/server_session.ts +1 -0
  65. package/source/server_subscription.ts +46 -5
@@ -1,1689 +1,1717 @@
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.ServerEngine = void 0;
13
- /**
14
- * @module node-opcua-server
15
- */
16
- const events_1 = require("events");
17
- const async = require("async");
18
- const chalk = require("chalk");
19
- const node_opcua_assert_1 = require("node-opcua-assert");
20
- const node_opcua_address_space_1 = require("node-opcua-address-space");
21
- const nodeJS_1 = require("node-opcua-address-space/nodeJS");
22
- const node_opcua_data_value_1 = require("node-opcua-data-value");
23
- const node_opcua_common_1 = require("node-opcua-common");
24
- const node_opcua_data_model_1 = require("node-opcua-data-model");
25
- const node_opcua_nodeid_1 = require("node-opcua-nodeid");
26
- const node_opcua_service_read_1 = require("node-opcua-service-read");
27
- const node_opcua_constants_1 = require("node-opcua-constants");
28
- const node_opcua_date_time_1 = require("node-opcua-date-time");
29
- const node_opcua_debug_1 = require("node-opcua-debug");
30
- const node_opcua_nodesets_1 = require("node-opcua-nodesets");
31
- const node_opcua_object_registry_1 = require("node-opcua-object-registry");
32
- const node_opcua_service_call_1 = require("node-opcua-service-call");
33
- const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
34
- const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
35
- const node_opcua_service_history_1 = require("node-opcua-service-history");
36
- const node_opcua_status_code_1 = require("node-opcua-status-code");
37
- const node_opcua_types_1 = require("node-opcua-types");
38
- const node_opcua_variant_1 = require("node-opcua-variant");
39
- const history_server_capabilities_1 = require("./history_server_capabilities");
40
- const monitored_item_1 = require("./monitored_item");
41
- const server_capabilities_1 = require("./server_capabilities");
42
- const server_publish_engine_1 = require("./server_publish_engine");
43
- const server_publish_engine_for_orphan_subscriptions_1 = require("./server_publish_engine_for_orphan_subscriptions");
44
- const server_session_1 = require("./server_session");
45
- const server_subscription_1 = require("./server_subscription");
46
- const sessions_compatible_for_transfer_1 = require("./sessions_compatible_for_transfer");
47
- const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
48
- const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
49
- const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
50
- const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
51
- function upperCaseFirst(str) {
52
- return str.slice(0, 1).toUpperCase() + str.slice(1);
53
- }
54
- function shutdownAndDisposeAddressSpace() {
55
- return __awaiter(this, void 0, void 0, function* () {
56
- if (this.addressSpace) {
57
- yield this.addressSpace.shutdown();
58
- this.addressSpace.dispose();
59
- delete this.addressSpace;
60
- }
61
- });
62
- }
63
- function setSubscriptionDurable(inputArguments, context, callback) {
64
- // see https://reference.opcfoundation.org/v104/Core/docs/Part5/9.3/
65
- // https://reference.opcfoundation.org/v104/Core/docs/Part4/6.8/
66
- (0, node_opcua_assert_1.assert)(Array.isArray(inputArguments));
67
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
68
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(context, "session"), " expecting a session id in the context object");
69
- const session = context.session;
70
- if (!session) {
71
- return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
72
- }
73
- const subscriptionId = inputArguments[0].value;
74
- const lifetimeInHours = inputArguments[1].value;
75
- const subscription = session.getSubscription(subscriptionId);
76
- if (!subscription) {
77
- // subscription may belongs to a different session that ours
78
- if (this.findSubscription(subscriptionId)) {
79
- // if yes, then access to Subscription data should be denied
80
- return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied });
81
- }
82
- return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
83
- }
84
- if (subscription.monitoredItemCount > 0) {
85
- // This is returned when a Subscription already contains MonitoredItems.
86
- return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadInvalidState });
87
- }
88
- /**
89
- * MonitoredItems are used to monitor Variable Values for data changes and event notifier
90
- * Objects for new Events. Subscriptions are used to combine data changes and events of
91
- * the assigned MonitoredItems to an optimized stream of network messages. A reliable
92
- * delivery is ensured as long as the lifetime of the Subscription and the queues in the
93
- * MonitoredItems are long enough for a network interruption between OPC UA Client and
94
- * Server. All queues that ensure reliable delivery are normally kept in memory and a
95
- * Server restart would delete them.
96
- * There are use cases where OPC UA Clients have no permanent network connection to the
97
- * OPC UA Server or where reliable delivery of data changes and events is necessary
98
- * even if the OPC UA Server is restarted or the network connection is interrupted
99
- * for a longer time.
100
- * To ensure this reliable delivery, the OPC UA Server must store collected data and
101
- * events in non-volatile memory until the OPC UA Client has confirmed reception.
102
- * It is possible that there will be data lost if the Server is not shut down gracefully
103
- * or in case of power failure. But the OPC UA Server should store the queues frequently
104
- * even if the Server is not shut down.
105
- * The Method SetSubscriptionDurable defined in OPC 10000-5 is used to set a Subscription
106
- * into this durable mode and to allow much longer lifetimes and queue sizes than for normal
107
- * Subscriptions. The Method shall be called before the MonitoredItems are created in the
108
- * durable Subscription. The Server shall verify that the Method is called within the
109
- * Session context of the Session that owns the Subscription.
110
- *
111
- * A value of 0 for the parameter lifetimeInHours requests the highest lifetime supported by the Server.
112
- */
113
- const highestLifetimeInHours = 24 * 100;
114
- const revisedLifetimeInHours = lifetimeInHours === 0 ? highestLifetimeInHours : Math.max(1, Math.min(lifetimeInHours, highestLifetimeInHours));
115
- // also adjust subscription life time
116
- const currentLifeTimeInHours = (subscription.lifeTimeCount * subscription.publishingInterval) / (1000 * 60 * 60);
117
- if (currentLifeTimeInHours < revisedLifetimeInHours) {
118
- const requestedLifetimeCount = Math.ceil((revisedLifetimeInHours * (1000 * 60 * 60)) / subscription.publishingInterval);
119
- subscription.modify({
120
- requestedMaxKeepAliveCount: subscription.maxKeepAliveCount,
121
- requestedPublishingInterval: subscription.publishingInterval,
122
- maxNotificationsPerPublish: subscription.maxNotificationsPerPublish,
123
- priority: subscription.priority,
124
- requestedLifetimeCount
125
- });
126
- }
127
- const callMethodResult = new node_opcua_service_call_1.CallMethodResult({
128
- statusCode: node_opcua_status_code_1.StatusCodes.Good,
129
- outputArguments: [{ dataType: node_opcua_variant_1.DataType.UInt32, arrayType: node_opcua_variant_1.VariantArrayType.Scalar, value: revisedLifetimeInHours }]
130
- });
131
- callback(null, callMethodResult);
132
- }
133
- // binding methods
134
- function getMonitoredItemsId(inputArguments, context, callback) {
135
- (0, node_opcua_assert_1.assert)(Array.isArray(inputArguments));
136
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
137
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(context, "session"), " expecting a session id in the context object");
138
- const session = context.session;
139
- if (!session) {
140
- return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
141
- }
142
- const subscriptionId = inputArguments[0].value;
143
- const subscription = session.getSubscription(subscriptionId);
144
- if (!subscription) {
145
- // subscription may belongs to a different session that ours
146
- if (this.findSubscription(subscriptionId)) {
147
- // if yes, then access to Subscription data should be denied
148
- return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied });
149
- }
150
- return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
151
- }
152
- const result = subscription.getMonitoredItems();
153
- (0, node_opcua_assert_1.assert)(result.statusCode);
154
- (0, node_opcua_assert_1.assert)(result.serverHandles.length === result.clientHandles.length);
155
- const callMethodResult = new node_opcua_service_call_1.CallMethodResult({
156
- statusCode: result.statusCode,
157
- outputArguments: [
158
- { dataType: node_opcua_variant_1.DataType.UInt32, arrayType: node_opcua_variant_1.VariantArrayType.Array, value: result.serverHandles },
159
- { dataType: node_opcua_variant_1.DataType.UInt32, arrayType: node_opcua_variant_1.VariantArrayType.Array, value: result.clientHandles }
160
- ]
161
- });
162
- callback(null, callMethodResult);
163
- }
164
- function __bindVariable(self, nodeId, options) {
165
- options = options || {};
166
- const variable = self.addressSpace.findNode(nodeId);
167
- if (variable && variable.bindVariable) {
168
- variable.bindVariable(options, true);
169
- (0, node_opcua_assert_1.assert)(typeof variable.asyncRefresh === "function");
170
- (0, node_opcua_assert_1.assert)(typeof variable.refreshFunc === "function");
171
- }
172
- else {
173
- warningLog("Warning: cannot bind object with id ", nodeId.toString(), " please check your nodeset.xml file or add this node programmatically");
174
- }
175
- }
176
- // note OPCUA 1.03 part 4 page 76
177
- // The Server-assigned identifier for the Subscription (see 7.14 for IntegerId definition). This identifier shall
178
- // be unique for the entire Server, not just for the Session, in order to allow the Subscription to be transferred
179
- // to another Session using the TransferSubscriptions service.
180
- // After Server start-up the generation of subscriptionIds should start from a random IntegerId or continue from
181
- // the point before the restart.
182
- let next_subscriptionId = Math.ceil(Math.random() * 1000000);
183
- function _get_next_subscriptionId() {
184
- debugLog(" next_subscriptionId = ", next_subscriptionId);
185
- return next_subscriptionId++;
186
- }
187
- /**
188
- *
189
- */
190
- class ServerEngine extends events_1.EventEmitter {
191
- constructor(options) {
192
- super();
193
- options = options || { applicationUri: "" };
194
- options.buildInfo = options.buildInfo || {};
195
- ServerEngine.registry.register(this);
196
- this._sessions = {};
197
- this._closedSessions = {};
198
- this._orphanPublishEngine = undefined; // will be constructed on demand
199
- this.isAuditing = typeof options.isAuditing === "boolean" ? options.isAuditing : false;
200
- options.buildInfo.buildDate = options.buildInfo.buildDate || new Date();
201
- // ---------------------------------------------------- ServerStatusDataType
202
- this._serverStatus = new node_opcua_common_1.ServerStatusDataType({
203
- buildInfo: options.buildInfo,
204
- currentTime: new Date(),
205
- secondsTillShutdown: 0,
206
- shutdownReason: { text: "" },
207
- startTime: new Date(),
208
- state: node_opcua_common_1.ServerState.NoConfiguration
209
- });
210
- // --------------------------------------------------- ServerCapabilities
211
- options.serverCapabilities = options.serverCapabilities || {};
212
- // https://profiles.opcfoundation.org/profile
213
- options.serverCapabilities.serverProfileArray = options.serverCapabilities.serverProfileArray || [
214
- "http://opcfoundation.org/UA-Profile/Server/Standard",
215
- "http://opcfoundation.org/UA-Profile/Server/DataAccess",
216
- "http://opcfoundation.org/UA-Profile/Server/Events",
217
- "http://opcfoundation.org/UA-Profile/Client/HistoricalAccess",
218
- "http://opcfoundation.org/UA-Profile/Server/Methods",
219
- "http://opcfoundation.org/UA-Profile/Server/StandardEventSubscription",
220
- "http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary",
221
- "http://opcfoundation.org/UA-Profile/Server/FileAccess",
222
- "http://opcfoundation.org/UA-Profile/Server/StateMachine"
223
- // "http://opcfoundation.org/UA-Profile/Transport/wss-uajson",
224
- // "http://opcfoundation.org/UA-Profile/Transport/wss-uasc-uabinary"
225
- // "http://opcfoundation.org/UA-Profile/Server/DurableSubscription"
226
- // "http://opcfoundation.org/UA-Profile/Server/ReverseConnect",
227
- // "http://opcfoundation.org/UAProfile/Server/NodeManagement",
228
- // "Embedded UA Server Profile",
229
- // "Micro Embedded Device Server Profile",
230
- // "Nano Embedded Device Server Profile"
231
- ];
232
- options.serverCapabilities.localeIdArray = options.serverCapabilities.localeIdArray || ["en-EN", "fr-FR"];
233
- this.serverCapabilities = new server_capabilities_1.ServerCapabilities(options.serverCapabilities);
234
- // to do when spec is clear about what goes here!
235
- // spec 1.04 says (in Part 4 7.33 SignedSoftwareCertificate
236
- // Note: Details on SoftwareCertificates need to be defined in a future version.
237
- this.serverCapabilities.softwareCertificates = [
238
- // new SignedSoftwareCertificate({})
239
- ];
240
- // make sure minSupportedSampleRate matches MonitoredItem.minimumSamplingInterval
241
- this.serverCapabilities.__defineGetter__("minSupportedSampleRate", () => {
242
- return monitored_item_1.MonitoredItem.minimumSamplingInterval;
243
- });
244
- this.historyServerCapabilities = new history_server_capabilities_1.HistoryServerCapabilities(options.historyServerCapabilities);
245
- // --------------------------------------------------- serverDiagnosticsSummary extension Object
246
- this.serverDiagnosticsSummary = new node_opcua_common_1.ServerDiagnosticsSummaryDataType();
247
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(this.serverDiagnosticsSummary, "currentSessionCount"));
248
- // note spelling is different for serverDiagnosticsSummary.currentSubscriptionCount
249
- // and sessionDiagnostics.currentSubscriptionsCount ( with an s)
250
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(this.serverDiagnosticsSummary, "currentSubscriptionCount"));
251
- this.serverDiagnosticsSummary.__defineGetter__("currentSubscriptionCount", () => {
252
- // currentSubscriptionCount returns the total number of subscriptions
253
- // that are currently active on all sessions
254
- let counter = 0;
255
- Object.values(this._sessions).forEach((session) => {
256
- counter += session.currentSubscriptionCount;
257
- });
258
- return counter;
259
- });
260
- this._internalState = "creating";
261
- this.setServerState(node_opcua_common_1.ServerState.NoConfiguration);
262
- this.addressSpace = null;
263
- this._shutdownTasks = [];
264
- this._applicationUri = "";
265
- if (typeof options.applicationUri === "function") {
266
- this.__defineGetter__("_applicationUri", options.applicationUri);
267
- }
268
- else {
269
- this._applicationUri = options.applicationUri || "<unset _applicationUri>";
270
- }
271
- options.serverDiagnosticsEnabled = Object.prototype.hasOwnProperty.call(options, "serverDiagnosticsEnable")
272
- ? options.serverDiagnosticsEnabled
273
- : true;
274
- this.serverDiagnosticsEnabled = options.serverDiagnosticsEnabled;
275
- }
276
- isStarted() {
277
- return !!this._serverStatus;
278
- }
279
- dispose() {
280
- this.addressSpace = null;
281
- (0, node_opcua_assert_1.assert)(Object.keys(this._sessions).length === 0, "ServerEngine#_sessions not empty");
282
- this._sessions = {};
283
- // todo fix me
284
- this._closedSessions = {};
285
- (0, node_opcua_assert_1.assert)(Object.keys(this._closedSessions).length === 0, "ServerEngine#_closedSessions not empty");
286
- this._closedSessions = {};
287
- if (this._orphanPublishEngine) {
288
- this._orphanPublishEngine.dispose();
289
- this._orphanPublishEngine = undefined;
290
- }
291
- this._shutdownTasks = [];
292
- this._serverStatus = null;
293
- this._internalState = "disposed";
294
- this.removeAllListeners();
295
- ServerEngine.registry.unregister(this);
296
- }
297
- get startTime() {
298
- return this._serverStatus.startTime;
299
- }
300
- get currentTime() {
301
- return this._serverStatus.currentTime;
302
- }
303
- get buildInfo() {
304
- return this._serverStatus.buildInfo;
305
- }
306
- /**
307
- * register a function that will be called when the server will perform its shut down.
308
- * @method registerShutdownTask
309
- */
310
- registerShutdownTask(task) {
311
- (0, node_opcua_assert_1.assert)(typeof task === "function");
312
- this._shutdownTasks.push(task);
313
- }
314
- /**
315
- * @method shutdown
316
- */
317
- shutdown() {
318
- return __awaiter(this, void 0, void 0, function* () {
319
- debugLog("ServerEngine#shutdown");
320
- this._internalState = "shutdown";
321
- this.setServerState(node_opcua_common_1.ServerState.Shutdown);
322
- // delete any existing sessions
323
- const tokens = Object.keys(this._sessions).map((key) => {
324
- const session = this._sessions[key];
325
- return session.authenticationToken;
326
- });
327
- // delete and close any orphan subscriptions
328
- if (this._orphanPublishEngine) {
329
- this._orphanPublishEngine.shutdown();
330
- }
331
- for (const token of tokens) {
332
- this.closeSession(token, true, "Terminated");
333
- }
334
- // all sessions must have been terminated
335
- (0, node_opcua_assert_1.assert)(this.currentSessionCount === 0);
336
- // all subscriptions must have been terminated
337
- (0, node_opcua_assert_1.assert)(this.currentSubscriptionCount === 0, "all subscriptions must have been terminated");
338
- this._shutdownTasks.push(shutdownAndDisposeAddressSpace);
339
- // perform registerShutdownTask
340
- for (const task of this._shutdownTasks) {
341
- yield task.call(this);
342
- }
343
- this.dispose();
344
- });
345
- }
346
- /**
347
- * the number of active sessions
348
- */
349
- get currentSessionCount() {
350
- return this.serverDiagnosticsSummary.currentSessionCount;
351
- }
352
- /**
353
- * the cumulated number of sessions that have been opened since this object exists
354
- */
355
- get cumulatedSessionCount() {
356
- return this.serverDiagnosticsSummary.cumulatedSessionCount;
357
- }
358
- /**
359
- * the number of active subscriptions.
360
- */
361
- get currentSubscriptionCount() {
362
- return this.serverDiagnosticsSummary.currentSubscriptionCount;
363
- }
364
- /**
365
- * the cumulated number of subscriptions that have been created since this object exists
366
- */
367
- get cumulatedSubscriptionCount() {
368
- return this.serverDiagnosticsSummary.cumulatedSubscriptionCount;
369
- }
370
- get rejectedSessionCount() {
371
- return this.serverDiagnosticsSummary.rejectedSessionCount;
372
- }
373
- get rejectedRequestsCount() {
374
- return this.serverDiagnosticsSummary.rejectedRequestsCount;
375
- }
376
- get sessionAbortCount() {
377
- return this.serverDiagnosticsSummary.sessionAbortCount;
378
- }
379
- get sessionTimeoutCount() {
380
- return this.serverDiagnosticsSummary.sessionTimeoutCount;
381
- }
382
- get publishingIntervalCount() {
383
- return this.serverDiagnosticsSummary.publishingIntervalCount;
384
- }
385
- incrementSessionTimeoutCount() {
386
- if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
387
- // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
388
- this.serverDiagnosticsSummary.sessionTimeoutCount += 1;
389
- }
390
- }
391
- incrementSessionAbortCount() {
392
- if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
393
- // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
394
- this.serverDiagnosticsSummary.sessionAbortCount += 1;
395
- }
396
- }
397
- incrementRejectedRequestsCount() {
398
- if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
399
- // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
400
- this.serverDiagnosticsSummary.rejectedRequestsCount += 1;
401
- }
402
- }
403
- /**
404
- * increment rejected session count (also increment rejected requests count)
405
- */
406
- incrementRejectedSessionCount() {
407
- if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
408
- // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
409
- this.serverDiagnosticsSummary.rejectedSessionCount += 1;
410
- }
411
- this.incrementRejectedRequestsCount();
412
- }
413
- incrementSecurityRejectedRequestsCount() {
414
- if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
415
- // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
416
- this.serverDiagnosticsSummary.securityRejectedRequestsCount += 1;
417
- }
418
- this.incrementRejectedRequestsCount();
419
- }
420
- /**
421
- * increment rejected session count (also increment rejected requests count)
422
- */
423
- incrementSecurityRejectedSessionCount() {
424
- if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
425
- // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
426
- this.serverDiagnosticsSummary.securityRejectedSessionCount += 1;
427
- }
428
- this.incrementSecurityRejectedRequestsCount();
429
- }
430
- setShutdownTime(date) {
431
- this._expectedShutdownTime = date;
432
- }
433
- setShutdownReason(reason) {
434
- var _a;
435
- (_a = this.addressSpace) === null || _a === void 0 ? void 0 : _a.rootFolder.objects.server.serverStatus.shutdownReason.setValueFromSource({
436
- dataType: node_opcua_variant_1.DataType.LocalizedText,
437
- value: (0, node_opcua_data_model_1.coerceLocalizedText)(reason)
438
- });
439
- }
440
- /**
441
- * @method secondsTillShutdown
442
- * @return the approximate number of seconds until the server will be shut down. The
443
- * value is only relevant once the state changes into SHUTDOWN.
444
- */
445
- secondsTillShutdown() {
446
- if (!this._expectedShutdownTime) {
447
- return 0;
448
- }
449
- // ToDo: implement a correct solution here
450
- const now = Date.now();
451
- return Math.max(0, Math.ceil((this._expectedShutdownTime.getTime() - now) / 1000));
452
- }
453
- /**
454
- * the name of the server
455
- */
456
- get serverName() {
457
- return this._serverStatus.buildInfo.productName;
458
- }
459
- /**
460
- * the server urn
461
- */
462
- get serverNameUrn() {
463
- return this._applicationUri;
464
- }
465
- /**
466
- * the urn of the server namespace
467
- */
468
- get serverNamespaceUrn() {
469
- return this._applicationUri; // "urn:" + engine.serverName;
470
- }
471
- get serverStatus() {
472
- return this._serverStatus;
473
- }
474
- setServerState(serverState) {
475
- var _a, _b, _c, _d, _e, _f;
476
- (0, node_opcua_assert_1.assert)(serverState !== null && serverState !== undefined);
477
- (_f = (_e = (_d = (_c = (_b = (_a = this.addressSpace) === null || _a === void 0 ? void 0 : _a.rootFolder) === null || _b === void 0 ? void 0 : _b.objects) === null || _c === void 0 ? void 0 : _c.server) === null || _d === void 0 ? void 0 : _d.serverStatus) === null || _e === void 0 ? void 0 : _e.state) === null || _f === void 0 ? void 0 : _f.setValueFromSource({
478
- dataType: node_opcua_variant_1.DataType.Int32,
479
- value: serverState
480
- });
481
- }
482
- getServerDiagnosticsEnabledFlag() {
483
- const server = this.addressSpace.rootFolder.objects.server;
484
- const serverDiagnostics = server.getComponentByName("ServerDiagnostics");
485
- if (!serverDiagnostics) {
486
- return false;
487
- }
488
- return serverDiagnostics.readValue().value.value;
489
- }
490
- /**
491
- * @method initialize
492
- * @async
493
- *
494
- * @param options {Object}
495
- * @param options.nodeset_filename {String} - [option](default : 'mini.Node.Set2.xml' )
496
- * @param callback
497
- */
498
- initialize(options, callback) {
499
- (0, node_opcua_assert_1.assert)(!this.addressSpace); // check that 'initialize' has not been already called
500
- this._internalState = "initializing";
501
- options = options || {};
502
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
503
- options.nodeset_filename = options.nodeset_filename || node_opcua_nodesets_1.nodesets.standard;
504
- const startTime = new Date();
505
- debugLog("Loading ", options.nodeset_filename, "...");
506
- this.addressSpace = node_opcua_address_space_1.AddressSpace.create();
507
- // register namespace 1 (our namespace);
508
- const serverNamespace = this.addressSpace.registerNamespace(this.serverNamespaceUrn);
509
- (0, node_opcua_assert_1.assert)(serverNamespace.index === 1);
510
- // eslint-disable-next-line max-statements
511
- (0, nodeJS_1.generateAddressSpace)(this.addressSpace, options.nodeset_filename, () => {
512
- /* istanbul ignore next */
513
- if (!this.addressSpace) {
514
- throw new Error("Internal error");
515
- }
516
- const addressSpace = this.addressSpace;
517
- const endTime = new Date();
518
- debugLog("Loading ", options.nodeset_filename, " done : ", endTime.getTime() - startTime.getTime(), " ms");
519
- const bindVariableIfPresent = (nodeId, opts) => {
520
- (0, node_opcua_assert_1.assert)(nodeId instanceof node_opcua_nodeid_1.NodeId);
521
- (0, node_opcua_assert_1.assert)(!nodeId.isEmpty());
522
- const obj = addressSpace.findNode(nodeId);
523
- if (obj) {
524
- __bindVariable(this, nodeId, opts);
525
- }
526
- return obj;
527
- };
528
- // -------------------------------------------- install default get/put handler
529
- const server_NamespaceArray_Id = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_NamespaceArray); // ns=0;i=2255
530
- bindVariableIfPresent(server_NamespaceArray_Id, {
531
- get() {
532
- return new node_opcua_variant_1.Variant({
533
- arrayType: node_opcua_variant_1.VariantArrayType.Array,
534
- dataType: node_opcua_variant_1.DataType.String,
535
- value: addressSpace.getNamespaceArray().map((x) => x.namespaceUri)
536
- });
537
- },
538
- set: null // read only
539
- });
540
- const server_NameUrn_var = new node_opcua_variant_1.Variant({
541
- arrayType: node_opcua_variant_1.VariantArrayType.Array,
542
- dataType: node_opcua_variant_1.DataType.String,
543
- value: [
544
- this.serverNameUrn // this is us !
545
- ]
546
- });
547
- const server_ServerArray_Id = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerArray); // ns=0;i=2254
548
- bindVariableIfPresent(server_ServerArray_Id, {
549
- get() {
550
- return server_NameUrn_var;
551
- },
552
- set: null // read only
553
- });
554
- // fix DefaultUserRolePermissions and DefaultUserRolePermissions
555
- // of namespaces
556
- const namespaces = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.ObjectIds.Server_Namespaces);
557
- const namespacesNode = addressSpace.findNode(namespaces);
558
- if (namespacesNode) {
559
- for (const ns of namespacesNode.getComponents()) {
560
- const defaultUserRolePermissions = ns.getChildByName("DefaultUserRolePermissions");
561
- if (defaultUserRolePermissions) {
562
- defaultUserRolePermissions.setValueFromSource({ dataType: node_opcua_variant_1.DataType.Null });
563
- }
564
- const defaultRolePermissions = ns.getChildByName("DefaultRolePermissions");
565
- if (defaultRolePermissions) {
566
- defaultRolePermissions.setValueFromSource({ dataType: node_opcua_variant_1.DataType.Null });
567
- }
568
- }
569
- }
570
- const bindStandardScalar = (id, dataType, func, setter_func) => {
571
- (0, node_opcua_assert_1.assert)(typeof id === "number", "expecting id to be a number");
572
- (0, node_opcua_assert_1.assert)(typeof func === "function");
573
- (0, node_opcua_assert_1.assert)(typeof setter_func === "function" || !setter_func);
574
- (0, node_opcua_assert_1.assert)(dataType !== null); // check invalid dataType
575
- let setter_func2 = null;
576
- if (setter_func) {
577
- setter_func2 = (variant) => {
578
- const variable2 = !!variant.value;
579
- setter_func(variable2);
580
- return node_opcua_status_code_1.StatusCodes.Good;
581
- };
582
- }
583
- const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(id);
584
- // make sur the provided function returns a valid value for the variant type
585
- // This test may not be exhaustive but it will detect obvious mistakes.
586
- /* istanbul ignore next */
587
- if (!(0, node_opcua_variant_1.isValidVariant)(node_opcua_variant_1.VariantArrayType.Scalar, dataType, func())) {
588
- errorLog("func", func());
589
- throw new Error("bindStandardScalar : func doesn't provide an value of type " + node_opcua_variant_1.DataType[dataType]);
590
- }
591
- return bindVariableIfPresent(nodeId, {
592
- get() {
593
- return new node_opcua_variant_1.Variant({
594
- arrayType: node_opcua_variant_1.VariantArrayType.Scalar,
595
- dataType,
596
- value: func()
597
- });
598
- },
599
- set: setter_func2
600
- });
601
- };
602
- const bindStandardArray = (id, variantDataType, dataType, func) => {
603
- (0, node_opcua_assert_1.assert)(typeof func === "function");
604
- (0, node_opcua_assert_1.assert)(variantDataType !== null); // check invalid dataType
605
- const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(id);
606
- // make sur the provided function returns a valid value for the variant type
607
- // This test may not be exhaustive but it will detect obvious mistakes.
608
- (0, node_opcua_assert_1.assert)((0, node_opcua_variant_1.isValidVariant)(node_opcua_variant_1.VariantArrayType.Array, variantDataType, func()));
609
- bindVariableIfPresent(nodeId, {
610
- get() {
611
- const value = func();
612
- (0, node_opcua_assert_1.assert)(Array.isArray(value));
613
- return new node_opcua_variant_1.Variant({
614
- arrayType: node_opcua_variant_1.VariantArrayType.Array,
615
- dataType: variantDataType,
616
- value
617
- });
618
- },
619
- set: null // read only
620
- });
621
- };
622
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_EstimatedReturnTime, node_opcua_variant_1.DataType.DateTime, () => node_opcua_date_time_1.minOPCUADate);
623
- // TimeZoneDataType
624
- const timeZoneDataType = addressSpace.findDataType((0, node_opcua_nodeid_1.resolveNodeId)(node_opcua_constants_1.DataTypeIds.TimeZoneDataType));
625
- const timeZone = new node_opcua_types_1.TimeZoneDataType({
626
- daylightSavingInOffset: /* boolean*/ false,
627
- offset: /* int16 */ 0
628
- });
629
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_LocalTime, node_opcua_variant_1.DataType.ExtensionObject, () => {
630
- return timeZone;
631
- });
632
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServiceLevel, node_opcua_variant_1.DataType.Byte, () => {
633
- return 255;
634
- });
635
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_Auditing, node_opcua_variant_1.DataType.Boolean, () => {
636
- return this.isAuditing;
637
- });
638
- // eslint-disable-next-line @typescript-eslint/no-this-alias
639
- const engine = this;
640
- const makeNotReadableIfEnabledFlagIsFalse = (variable) => {
641
- const originalIsReadable = variable.isReadable;
642
- variable.isUserReadable = checkReadableFlag;
643
- function checkReadableFlag(context) {
644
- const isEnabled = engine.serverDiagnosticsEnabled;
645
- return originalIsReadable.call(this, context) && isEnabled;
646
- }
647
- for (const c of variable.getAggregates()) {
648
- if (c.nodeClass === node_opcua_data_model_1.NodeClass.Variable) {
649
- makeNotReadableIfEnabledFlagIsFalse(c);
650
- }
651
- }
652
- };
653
- const bindServerDiagnostics = () => {
654
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerDiagnostics_EnabledFlag, node_opcua_variant_1.DataType.Boolean, () => {
655
- return this.serverDiagnosticsEnabled;
656
- }, (newFlag) => {
657
- this.serverDiagnosticsEnabled = newFlag;
658
- });
659
- const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerDiagnostics_ServerDiagnosticsSummary);
660
- const serverDiagnosticsSummaryNode = addressSpace.findNode(nodeId);
661
- if (serverDiagnosticsSummaryNode) {
662
- serverDiagnosticsSummaryNode.bindExtensionObject(this.serverDiagnosticsSummary);
663
- this.serverDiagnosticsSummary = serverDiagnosticsSummaryNode.$extensionObject;
664
- makeNotReadableIfEnabledFlagIsFalse(serverDiagnosticsSummaryNode);
665
- }
666
- };
667
- const bindServerStatus = () => {
668
- const serverStatusNode = addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerStatus));
669
- if (!serverStatusNode) {
670
- return;
671
- }
672
- if (serverStatusNode) {
673
- serverStatusNode.bindExtensionObject(this._serverStatus);
674
- serverStatusNode.minimumSamplingInterval = 1000;
675
- }
676
- const currentTimeNode = addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerStatus_CurrentTime));
677
- if (currentTimeNode) {
678
- currentTimeNode.minimumSamplingInterval = 1000;
679
- }
680
- const secondsTillShutdown = addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerStatus_SecondsTillShutdown));
681
- if (secondsTillShutdown) {
682
- secondsTillShutdown.minimumSamplingInterval = 1000;
683
- }
684
- (0, node_opcua_assert_1.assert)(serverStatusNode.$extensionObject);
685
- serverStatusNode.$extensionObject = new Proxy(serverStatusNode.$extensionObject, {
686
- get(target, prop) {
687
- if (prop === "currentTime") {
688
- serverStatusNode.currentTime.touchValue();
689
- return new Date();
690
- }
691
- else if (prop === "secondsTillShutdown") {
692
- serverStatusNode.secondsTillShutdown.touchValue();
693
- return engine.secondsTillShutdown();
694
- }
695
- return target[prop];
696
- }
697
- });
698
- this._serverStatus = serverStatusNode.$extensionObject;
699
- };
700
- const bindServerCapabilities = () => {
701
- bindStandardArray(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_ServerProfileArray, node_opcua_variant_1.DataType.String, node_opcua_variant_1.DataType.String, () => {
702
- return this.serverCapabilities.serverProfileArray;
703
- });
704
- bindStandardArray(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_LocaleIdArray, node_opcua_variant_1.DataType.String, "LocaleId", () => {
705
- return this.serverCapabilities.localeIdArray;
706
- });
707
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MinSupportedSampleRate, node_opcua_variant_1.DataType.Double, () => {
708
- return this.serverCapabilities.minSupportedSampleRate;
709
- });
710
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxBrowseContinuationPoints, node_opcua_variant_1.DataType.UInt16, () => {
711
- return this.serverCapabilities.maxBrowseContinuationPoints;
712
- });
713
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxQueryContinuationPoints, node_opcua_variant_1.DataType.UInt16, () => {
714
- return this.serverCapabilities.maxQueryContinuationPoints;
715
- });
716
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxHistoryContinuationPoints, node_opcua_variant_1.DataType.UInt16, () => {
717
- return this.serverCapabilities.maxHistoryContinuationPoints;
718
- });
719
- // added by DI : Server-specific period of time in milliseconds until the Server will revoke a lock.
720
- // TODO bindStandardScalar(VariableIds.Server_ServerCapabilities_MaxInactiveLockTime,
721
- // TODO DataType.UInt16, function () {
722
- // TODO return self.serverCapabilities.maxInactiveLockTime;
723
- // TODO });
724
- bindStandardArray(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_SoftwareCertificates, node_opcua_variant_1.DataType.ExtensionObject, "SoftwareCertificates", () => {
725
- return this.serverCapabilities.softwareCertificates;
726
- });
727
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxArrayLength, node_opcua_variant_1.DataType.UInt32, () => {
728
- return this.serverCapabilities.maxArrayLength;
729
- });
730
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxStringLength, node_opcua_variant_1.DataType.UInt32, () => {
731
- return this.serverCapabilities.maxStringLength;
732
- });
733
- bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxByteStringLength, node_opcua_variant_1.DataType.UInt32, () => {
734
- return this.serverCapabilities.maxByteStringLength;
735
- });
736
- const bindOperationLimits = (operationLimits) => {
737
- (0, node_opcua_assert_1.assert)(operationLimits !== null && typeof operationLimits === "object");
738
- const keys = Object.keys(operationLimits);
739
- keys.forEach((key) => {
740
- const uid = "Server_ServerCapabilities_OperationLimits_" + upperCaseFirst(key);
741
- const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds[uid]);
742
- (0, node_opcua_assert_1.assert)(!nodeId.isEmpty());
743
- bindStandardScalar(node_opcua_constants_1.VariableIds[uid], node_opcua_variant_1.DataType.UInt32, () => {
744
- return operationLimits[key];
745
- });
746
- });
747
- };
748
- bindOperationLimits(this.serverCapabilities.operationLimits);
749
- // i=2399 [ProgramStateMachineType_ProgramDiagnostics];
750
- function fix_ProgramStateMachineType_ProgramDiagnostics() {
751
- const nodeId = (0, node_opcua_nodeid_1.coerceNodeId)("i=2399"); // ProgramStateMachineType_ProgramDiagnostics
752
- const variable = addressSpace.findNode(nodeId);
753
- if (variable) {
754
- variable.$extensionObject = new node_opcua_types_1.ProgramDiagnosticDataType({});
755
- // variable.setValueFromSource({
756
- // dataType: DataType.ExtensionObject,
757
- // // value: new ProgramDiagnostic2DataType()
758
- // value: new ProgramDiagnosticDataType({})
759
- // });
760
- }
761
- }
762
- fix_ProgramStateMachineType_ProgramDiagnostics();
763
- };
764
- const bindHistoryServerCapabilities = () => {
765
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_MaxReturnDataValues, node_opcua_variant_1.DataType.UInt32, () => {
766
- return this.historyServerCapabilities.maxReturnDataValues;
767
- });
768
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_MaxReturnEventValues, node_opcua_variant_1.DataType.UInt32, () => {
769
- return this.historyServerCapabilities.maxReturnEventValues;
770
- });
771
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_AccessHistoryDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
772
- return this.historyServerCapabilities.accessHistoryDataCapability;
773
- });
774
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_AccessHistoryEventsCapability, node_opcua_variant_1.DataType.Boolean, () => {
775
- return this.historyServerCapabilities.accessHistoryEventsCapability;
776
- });
777
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_InsertDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
778
- return this.historyServerCapabilities.insertDataCapability;
779
- });
780
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_ReplaceDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
781
- return this.historyServerCapabilities.replaceDataCapability;
782
- });
783
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_UpdateDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
784
- return this.historyServerCapabilities.updateDataCapability;
785
- });
786
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_InsertEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
787
- return this.historyServerCapabilities.insertEventCapability;
788
- });
789
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_ReplaceEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
790
- return this.historyServerCapabilities.replaceEventCapability;
791
- });
792
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_UpdateEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
793
- return this.historyServerCapabilities.updateEventCapability;
794
- });
795
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_DeleteEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
796
- return this.historyServerCapabilities.deleteEventCapability;
797
- });
798
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_DeleteRawCapability, node_opcua_variant_1.DataType.Boolean, () => {
799
- return this.historyServerCapabilities.deleteRawCapability;
800
- });
801
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_DeleteAtTimeCapability, node_opcua_variant_1.DataType.Boolean, () => {
802
- return this.historyServerCapabilities.deleteAtTimeCapability;
803
- });
804
- bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_InsertAnnotationCapability, node_opcua_variant_1.DataType.Boolean, () => {
805
- return this.historyServerCapabilities.insertAnnotationCapability;
806
- });
807
- };
808
- bindServerDiagnostics();
809
- bindServerStatus();
810
- bindServerCapabilities();
811
- bindHistoryServerCapabilities();
812
- const bindExtraStuff = () => {
813
- // mainly for compliance
814
- /*
815
- // The version number for the data type description. i=104
816
- bindStandardScalar(VariableIds.DataTypeDescriptionType_DataTypeVersion, DataType.String, () => {
817
- return "0";
818
- });
819
-
820
- const namingRuleDataTypeNode = addressSpace.findDataType(resolveNodeId(DataTypeIds.NamingRuleType))! as UADataType;
821
-
822
- if (namingRuleDataTypeNode) {
823
- const namingRuleType = (namingRuleDataTypeNode as any)._getEnumerationInfo().nameIndex; // getEnumeration("NamingRuleType");
824
- if (!namingRuleType) {
825
- throw new Error("Cannot find Enumeration definition for NamingRuleType");
826
- }
827
- // i=111
828
- bindStandardScalar(VariableIds.ModellingRuleType_NamingRule, DataType.Int32, () => {
829
- return 0;
830
- });
831
-
832
- // i=112
833
- bindStandardScalar(VariableIds.ModellingRule_Mandatory_NamingRule, DataType.Int32, () => {
834
- return namingRuleType.Mandatory ? namingRuleType.Mandatory.value : 0;
835
- });
836
-
837
- // i=113
838
- bindStandardScalar(VariableIds.ModellingRule_Optional_NamingRule, DataType.Int32, () => {
839
- return namingRuleType.Optional ? namingRuleType.Optional.value : 0;
840
- });
841
- // i=114
842
- bindStandardScalar(VariableIds.ModellingRule_ExposesItsArray_NamingRule, DataType.Int32, () => {
843
- return namingRuleType.ExposesItsArray ? namingRuleType.ExposesItsArray.value : 0;
844
- });
845
- bindStandardScalar(VariableIds.ModellingRule_MandatoryPlaceholder_NamingRule, DataType.Int32, () => {
846
- return namingRuleType.MandatoryPlaceholder ? namingRuleType.MandatoryPlaceholder.value : 0;
847
- });
848
- }
849
- */
850
- };
851
- bindExtraStuff();
852
- this.__internal_bindMethod((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.MethodIds.Server_GetMonitoredItems), getMonitoredItemsId.bind(this));
853
- this.__internal_bindMethod((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.MethodIds.Server_SetSubscriptionDurable), setSubscriptionDurable.bind(this));
854
- // fix getMonitoredItems.outputArguments arrayDimensions
855
- const fixGetMonitoredItemArgs = () => {
856
- var _a;
857
- const objects = (_a = this.addressSpace.rootFolder) === null || _a === void 0 ? void 0 : _a.objects;
858
- if (!objects || !objects.server || !objects.server.getMonitoredItems) {
859
- return;
860
- }
861
- const outputArguments = objects.server.getMonitoredItems.outputArguments;
862
- const dataValue = outputArguments.readValue();
863
- (0, node_opcua_assert_1.assert)(dataValue.value.value[0].arrayDimensions.length === 1 && dataValue.value.value[0].arrayDimensions[0] === 0);
864
- (0, node_opcua_assert_1.assert)(dataValue.value.value[1].arrayDimensions.length === 1 && dataValue.value.value[1].arrayDimensions[0] === 0);
865
- };
866
- fixGetMonitoredItemArgs();
867
- const prepareServerDiagnostics = () => {
868
- const addressSpace1 = this.addressSpace;
869
- if (!addressSpace1.rootFolder.objects) {
870
- return;
871
- }
872
- const server = addressSpace1.rootFolder.objects.server;
873
- if (!server) {
874
- return;
875
- }
876
- // create SessionsDiagnosticsSummary
877
- const serverDiagnosticsNode = server.getComponentByName("ServerDiagnostics");
878
- if (!serverDiagnosticsNode) {
879
- return;
880
- }
881
- if (true) {
882
- // set serverDiagnosticsNode enabledFlag writeable for admin user only
883
- // TO DO ...
884
- serverDiagnosticsNode.enabledFlag.userAccessLevel = (0, node_opcua_data_model_1.makeAccessLevelFlag)("CurrentRead");
885
- serverDiagnosticsNode.enabledFlag.accessLevel = (0, node_opcua_data_model_1.makeAccessLevelFlag)("CurrentRead");
886
- }
887
- // A Server may not expose the SamplingIntervalDiagnosticsArray if it does not use fixed sampling rates.
888
- // because we are not using fixed sampling rate, we need to remove the optional SamplingIntervalDiagnosticsArray
889
- // component
890
- const samplingIntervalDiagnosticsArray = serverDiagnosticsNode.getComponentByName("SamplingIntervalDiagnosticsArray");
891
- if (samplingIntervalDiagnosticsArray) {
892
- addressSpace.deleteNode(samplingIntervalDiagnosticsArray);
893
- const s = serverDiagnosticsNode.getComponents();
894
- }
895
- const subscriptionDiagnosticsArrayNode = serverDiagnosticsNode.getComponentByName("SubscriptionDiagnosticsArray");
896
- (0, node_opcua_assert_1.assert)(subscriptionDiagnosticsArrayNode.nodeClass === node_opcua_data_model_1.NodeClass.Variable);
897
- (0, node_opcua_address_space_1.bindExtObjArrayNode)(subscriptionDiagnosticsArrayNode, "SubscriptionDiagnosticsType", "subscriptionId");
898
- makeNotReadableIfEnabledFlagIsFalse(subscriptionDiagnosticsArrayNode);
899
- const sessionsDiagnosticsSummary = serverDiagnosticsNode.getComponentByName("SessionsDiagnosticsSummary");
900
- const sessionDiagnosticsArray = sessionsDiagnosticsSummary.getComponentByName("SessionDiagnosticsArray");
901
- (0, node_opcua_assert_1.assert)(sessionDiagnosticsArray.nodeClass === node_opcua_data_model_1.NodeClass.Variable);
902
- (0, node_opcua_address_space_1.bindExtObjArrayNode)(sessionDiagnosticsArray, "SessionDiagnosticsVariableType", "sessionId");
903
- const varType = addressSpace.findVariableType("SessionSecurityDiagnosticsType");
904
- if (!varType) {
905
- debugLog("Warning cannot find SessionSecurityDiagnosticsType variable Type");
906
- }
907
- else {
908
- const sessionSecurityDiagnosticsArray = sessionsDiagnosticsSummary.getComponentByName("SessionSecurityDiagnosticsArray");
909
- (0, node_opcua_assert_1.assert)(sessionSecurityDiagnosticsArray.nodeClass === node_opcua_data_model_1.NodeClass.Variable);
910
- (0, node_opcua_address_space_1.bindExtObjArrayNode)(sessionSecurityDiagnosticsArray, "SessionSecurityDiagnosticsType", "sessionId");
911
- (0, node_opcua_address_space_1.ensureObjectIsSecure)(sessionSecurityDiagnosticsArray);
912
- }
913
- };
914
- prepareServerDiagnostics();
915
- this._internalState = "initialized";
916
- this.setServerState(node_opcua_common_1.ServerState.Running);
917
- setImmediate(() => callback());
918
- });
919
- }
920
- /**
921
- *
922
- * @method browseSingleNode
923
- * @param nodeId {NodeId|String} : the nodeid of the element to browse
924
- * @param browseDescription
925
- * @param browseDescription.browseDirection {BrowseDirection} :
926
- * @param browseDescription.referenceTypeId {String|NodeId}
927
- * @param [context]
928
- * @return the browse result
929
- */
930
- browseSingleNode(nodeId, browseDescription, context) {
931
- const addressSpace = this.addressSpace;
932
- return addressSpace.browseSingleNode(nodeId, browseDescription, context);
933
- }
934
- browseWithAutomaticExpansion(nodesToBrowse, context) {
935
- return __awaiter(this, void 0, void 0, function* () {
936
- // do expansion first
937
- for (const browseDescription of nodesToBrowse) {
938
- const nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(browseDescription.nodeId);
939
- const node = this.addressSpace.findNode(nodeId);
940
- if (node) {
941
- if (node.onFirstBrowseAction) {
942
- try {
943
- yield node.onFirstBrowseAction();
944
- node.onFirstBrowseAction = undefined;
945
- }
946
- catch (err) {
947
- if (err instanceof Error) {
948
- errorLog("onFirstBrowseAction method has failed", err.message);
949
- }
950
- errorLog(err);
951
- }
952
- (0, node_opcua_assert_1.assert)(node.onFirstBrowseAction === undefined, "expansion can only be made once");
953
- }
954
- }
955
- }
956
- return this.browse(nodesToBrowse, context);
957
- });
958
- }
959
- /**
960
- *
961
- */
962
- browse(nodesToBrowse, context) {
963
- const results = [];
964
- for (const browseDescription of nodesToBrowse) {
965
- const nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(browseDescription.nodeId);
966
- const r = this.browseSingleNode(nodeId, browseDescription, context);
967
- results.push(r);
968
- }
969
- return results;
970
- }
971
- /**
972
- *
973
- * @method readSingleNode
974
- * @param context
975
- * @param nodeId
976
- * @param attributeId
977
- * @param [timestampsToReturn=TimestampsToReturn.Neither]
978
- * @return DataValue
979
- */
980
- readSingleNode(context, nodeId, attributeId, timestampsToReturn) {
981
- context.currentTime = (0, node_opcua_date_time_1.getCurrentClock)();
982
- return this._readSingleNode(context, new node_opcua_types_1.ReadValueId({
983
- attributeId,
984
- nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(nodeId)
985
- }), timestampsToReturn);
986
- }
987
- /**
988
- *
989
- *
990
- * Maximum age of the value to be read in milliseconds. The age of the value is based on the difference between
991
- * the ServerTimestamp and the time when the Server starts processing the request. For example if the Client
992
- * specifies a maxAge of 500 milliseconds and it takes 100 milliseconds until the Server starts processing
993
- * the request, the age of the returned value could be 600 milliseconds prior to the time it was requested.
994
- * If the Server has one or more values of an Attribute that are within the maximum age, it can return any one
995
- * of the values or it can read a new value from the data source. The number of values of an Attribute that
996
- * a Server has depends on the number of MonitoredItems that are defined for the Attribute. In any case,
997
- * the Client can make no assumption about which copy of the data will be returned.
998
- * If the Server does not have a value that is within the maximum age, it shall attempt to read a new value
999
- * from the data source.
1000
- * If the Server cannot meet the requested maxAge, it returns its 'best effort' value rather than rejecting the
1001
- * request.
1002
- * This may occur when the time it takes the Server to process and return the new data value after it has been
1003
- * accessed is greater than the specified maximum age.
1004
- * If maxAge is set to 0, the Server shall attempt to read a new value from the data source.
1005
- * If maxAge is set to the max Int32 value or greater, the Server shall attempt to get a cached value.
1006
- * Negative values are invalid for maxAge.
1007
- *
1008
- * @return an array of DataValue
1009
- */
1010
- read(context, readRequest) {
1011
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1012
- (0, node_opcua_assert_1.assert)(readRequest instanceof node_opcua_service_read_1.ReadRequest);
1013
- (0, node_opcua_assert_1.assert)(readRequest.maxAge >= 0);
1014
- const timestampsToReturn = readRequest.timestampsToReturn;
1015
- const nodesToRead = readRequest.nodesToRead || [];
1016
- (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRead));
1017
- context.currentTime = (0, node_opcua_date_time_1.getCurrentClock)();
1018
- const dataValues = [];
1019
- for (const readValueId of nodesToRead) {
1020
- const dataValue = this._readSingleNode(context, readValueId, timestampsToReturn);
1021
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Server) {
1022
- dataValue.sourceTimestamp = null;
1023
- dataValue.sourcePicoseconds = 0;
1024
- }
1025
- if ((timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Both || timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Server) &&
1026
- (!dataValue.serverTimestamp || dataValue.serverTimestamp.getTime() === node_opcua_date_time_1.minOPCUADate.getTime())) {
1027
- dataValue.serverTimestamp = context.currentTime.timestamp;
1028
- dataValue.sourcePicoseconds = 0; // context.currentTime.picosecond // do we really need picosecond here ? this would inflate binary data
1029
- }
1030
- dataValues.push(dataValue);
1031
- }
1032
- return dataValues;
1033
- }
1034
- /**
1035
- *
1036
- * @method writeSingleNode
1037
- * @param context
1038
- * @param writeValue
1039
- * @param callback
1040
- * @param callback.err
1041
- * @param callback.statusCode
1042
- * @async
1043
- */
1044
- writeSingleNode(context, writeValue, callback) {
1045
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1046
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
1047
- (0, node_opcua_assert_1.assert)(writeValue.schema.name === "WriteValue");
1048
- (0, node_opcua_assert_1.assert)(writeValue.value instanceof node_opcua_data_value_1.DataValue);
1049
- if (writeValue.value.value === null) {
1050
- return callback(null, node_opcua_status_code_1.StatusCodes.BadTypeMismatch);
1051
- }
1052
- (0, node_opcua_assert_1.assert)(writeValue.value.value instanceof node_opcua_variant_1.Variant);
1053
- const nodeId = writeValue.nodeId;
1054
- const obj = this.__findNode(nodeId);
1055
- if (!obj) {
1056
- return callback(null, node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown);
1057
- }
1058
- else {
1059
- obj.writeAttribute(context, writeValue, callback);
1060
- }
1061
- }
1062
- /**
1063
- * write a collection of nodes
1064
- * @method write
1065
- * @param context
1066
- * @param nodesToWrite
1067
- * @param callback
1068
- * @param callback.err
1069
- * @param callback.results
1070
- * @async
1071
- */
1072
- write(context, nodesToWrite, callback) {
1073
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1074
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
1075
- context.currentTime = (0, node_opcua_date_time_1.getCurrentClock)();
1076
- (0, node_opcua_address_space_1.ensureDatatypeExtractedWithCallback)(this.addressSpace, (err2, extraDataTypeManager) => {
1077
- if (err2) {
1078
- return callback(err2);
1079
- }
1080
- const performWrite = (writeValue, inner_callback) => {
1081
- (0, node_opcua_address_space_1.resolveOpaqueOnAddressSpace)(this.addressSpace, writeValue.value.value)
1082
- .then(() => {
1083
- this.writeSingleNode(context, writeValue, inner_callback);
1084
- })
1085
- .catch(inner_callback);
1086
- };
1087
- // tslint:disable:array-type
1088
- async.map(nodesToWrite, performWrite, (err, statusCodes) => {
1089
- (0, node_opcua_assert_1.assert)(Array.isArray(statusCodes));
1090
- callback(err, statusCodes);
1091
- });
1092
- });
1093
- }
1094
- /**
1095
- *
1096
- */
1097
- historyReadSingleNode(context, nodeId, attributeId, historyReadDetails, timestampsToReturn, continuationData, callback) {
1098
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1099
- callback(null, new node_opcua_service_history_1.HistoryReadResult({
1100
- statusCode: node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid
1101
- }));
1102
- return;
1103
- }
1104
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1105
- this._historyReadSingleNode(context, new node_opcua_service_history_1.HistoryReadValueId({
1106
- nodeId
1107
- }), historyReadDetails, timestampsToReturn, continuationData, callback);
1108
- }
1109
- /**
1110
- *
1111
- * @method historyRead
1112
- * @param context {SessionContext}
1113
- * @param historyReadRequest {HistoryReadRequest}
1114
- * @param historyReadRequest.requestHeader {RequestHeader}
1115
- * @param historyReadRequest.historyReadDetails {HistoryReadDetails}
1116
- * @param historyReadRequest.timestampsToReturn {TimestampsToReturn}
1117
- * @param historyReadRequest.releaseContinuationPoints {Boolean}
1118
- * @param historyReadRequest.nodesToRead {HistoryReadValueId[]}
1119
- * @param callback
1120
- * @param callback.err
1121
- * @param callback.results {HistoryReadResult[]}
1122
- */
1123
- historyRead(context, historyReadRequest, callback) {
1124
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1125
- (0, node_opcua_assert_1.assert)(historyReadRequest instanceof node_opcua_service_history_1.HistoryReadRequest);
1126
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
1127
- const timestampsToReturn = historyReadRequest.timestampsToReturn;
1128
- const historyReadDetails = historyReadRequest.historyReadDetails;
1129
- const releaseContinuationPoints = historyReadRequest.releaseContinuationPoints;
1130
- (0, node_opcua_assert_1.assert)(historyReadDetails instanceof node_opcua_service_history_1.HistoryReadDetails);
1131
- // ReadAnnotationDataDetails | ReadAtTimeDetails | ReadEventDetails | ReadProcessedDetails | ReadRawModifiedDetails;
1132
- const nodesToRead = historyReadRequest.nodesToRead || [];
1133
- (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRead));
1134
- const _q = (m) => __awaiter(this, void 0, void 0, function* () {
1135
- return new Promise((resolve) => {
1136
- const continuationPoint = m.nodeToRead.continuationPoint;
1137
- this._historyReadSingleNode(context, m.nodeToRead, m.processDetail, timestampsToReturn, { continuationPoint, releaseContinuationPoints /**, index = ??? */ }, (err, result) => {
1138
- if (err && !result) {
1139
- errorLog("Internal error", err.message);
1140
- result = new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
1141
- }
1142
- resolve(result);
1143
- });
1144
- });
1145
- });
1146
- if (historyReadDetails instanceof node_opcua_types_1.ReadProcessedDetails) {
1147
- //
1148
- if (!historyReadDetails.aggregateType || historyReadDetails.aggregateType.length !== nodesToRead.length) {
1149
- return callback(null, [new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInvalidArgument })]);
1150
- }
1151
- const promises = [];
1152
- let index = 0;
1153
- for (const nodeToRead of nodesToRead) {
1154
- const aggregateType = historyReadDetails.aggregateType[index];
1155
- const processDetail = new node_opcua_types_1.ReadProcessedDetails(Object.assign(Object.assign({}, historyReadDetails), { aggregateType: [aggregateType] }));
1156
- promises.push(_q({ nodeToRead, processDetail, index }));
1157
- index++;
1158
- }
1159
- Promise.all(promises).then((results) => {
1160
- callback(null, results);
1161
- });
1162
- return;
1163
- }
1164
- const _r = (nodeToRead, index) => __awaiter(this, void 0, void 0, function* () {
1165
- const continuationPoint = nodeToRead.continuationPoint;
1166
- return new Promise((resolve, reject) => {
1167
- this._historyReadSingleNode(context, nodeToRead, historyReadDetails, timestampsToReturn, { continuationPoint, releaseContinuationPoints, index }, (err, result) => {
1168
- if (err && !result) {
1169
- result = new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
1170
- }
1171
- resolve(result);
1172
- // it's not guaranteed that the historical read process is really asynchronous
1173
- });
1174
- });
1175
- });
1176
- const promises = [];
1177
- let index = 0;
1178
- for (const nodeToRead of nodesToRead) {
1179
- promises.push(_r(nodeToRead, index));
1180
- index++;
1181
- }
1182
- Promise.all(promises).then((results) => {
1183
- callback(null, results);
1184
- });
1185
- }
1186
- getOldestUnactivatedSession() {
1187
- const tmp = Object.values(this._sessions).filter((session1) => {
1188
- return session1.status === "new";
1189
- });
1190
- if (tmp.length === 0) {
1191
- return null;
1192
- }
1193
- let session = tmp[0];
1194
- for (let i = 1; i < tmp.length; i++) {
1195
- const c = tmp[i];
1196
- if (session.creationDate.getTime() < c.creationDate.getTime()) {
1197
- session = c;
1198
- }
1199
- }
1200
- return session;
1201
- }
1202
- /**
1203
- * create a new server session object.
1204
- * @class ServerEngine
1205
- * @method createSession
1206
- * @param [options] {Object}
1207
- * @param [options.sessionTimeout = 1000] {Number} sessionTimeout
1208
- * @param [options.clientDescription] {ApplicationDescription}
1209
- * @return {ServerSession}
1210
- */
1211
- createSession(options) {
1212
- options = options || {};
1213
- debugLog("createSession : increasing serverDiagnosticsSummary cumulatedSessionCount/currentSessionCount ");
1214
- this.serverDiagnosticsSummary.cumulatedSessionCount += 1;
1215
- this.serverDiagnosticsSummary.currentSessionCount += 1;
1216
- this.clientDescription = options.clientDescription || new node_opcua_service_endpoints_1.ApplicationDescription({});
1217
- const sessionTimeout = options.sessionTimeout || 1000;
1218
- (0, node_opcua_assert_1.assert)(typeof sessionTimeout === "number");
1219
- const session = new server_session_1.ServerSession(this, sessionTimeout);
1220
- debugLog("createSession :sessionTimeout = ", session.sessionTimeout);
1221
- const key = session.authenticationToken.toString();
1222
- this._sessions[key] = session;
1223
- // see spec OPC Unified Architecture, Part 2 page 26 Release 1.02
1224
- // TODO : When a Session is created, the Server adds an entry for the Client
1225
- // in its SessionDiagnosticsArray Variable
1226
- session.on("new_subscription", (subscription) => {
1227
- this.serverDiagnosticsSummary.cumulatedSubscriptionCount += 1;
1228
- // add the subscription diagnostics in our subscriptions diagnostics array
1229
- // note currentSubscriptionCount is handled directly with a special getter
1230
- });
1231
- session.on("subscription_terminated", (subscription) => {
1232
- // remove the subscription diagnostics in our subscriptions diagnostics array
1233
- // note currentSubscriptionCount is handled directly with a special getter
1234
- });
1235
- // OPC Unified Architecture, Part 4 23 Release 1.03
1236
- // Sessions are terminated by the Server automatically if the Client fails to issue a Service request on the
1237
- // Session within the timeout period negotiated by the Server in the CreateSession Service response.
1238
- // This protects the Server against Client failures and against situations where a failed underlying
1239
- // connection cannot be re-established. Clients shall be prepared to submit requests in a timely manner
1240
- // prevent the Session from closing automatically. Clients may explicitly terminate sessions using the
1241
- // CloseSession Service.
1242
- session.on("timeout", () => {
1243
- // the session hasn't been active for a while , probably because the client has disconnected abruptly
1244
- // it is now time to close the session completely
1245
- this.serverDiagnosticsSummary.sessionTimeoutCount += 1;
1246
- session.sessionName = session.sessionName || "";
1247
- const channel = session.channel;
1248
- errorLog(chalk.cyan("Server: closing SESSION "), session.status, chalk.yellow(session.sessionName), chalk.yellow(session.nodeId.toString()), chalk.cyan(" because of timeout = "), session.sessionTimeout, chalk.cyan(" has expired without a keep alive"), chalk.bgCyan("channel = "), channel === null || channel === void 0 ? void 0 : channel.remoteAddress, " port = ", channel === null || channel === void 0 ? void 0 : channel.remotePort);
1249
- // If a Server terminates a Session for any other reason, Subscriptions associated with the Session,
1250
- // are not deleted. => deleteSubscription= false
1251
- this.closeSession(session.authenticationToken, /*deleteSubscription=*/ false, /* reason =*/ "Timeout");
1252
- this.incrementSessionTimeoutCount();
1253
- });
1254
- return session;
1255
- }
1256
- /**
1257
- * @method closeSession
1258
- * @param authenticationToken
1259
- * @param deleteSubscriptions {Boolean} : true if session's subscription shall be deleted
1260
- * @param {String} [reason = "CloseSession"] the reason for closing the session (
1261
- * shall be "Timeout", "Terminated" or "CloseSession")
1262
- *
1263
- *
1264
- * what the specs say:
1265
- * -------------------
1266
- *
1267
- * If a Client invokes the CloseSession Service then all Subscriptions associated with the Session are also deleted
1268
- * if the deleteSubscriptions flag is set to TRUE. If a Server terminates a Session for any other reason,
1269
- * Subscriptions associated with the Session, are not deleted. Each Subscription has its own lifetime to protect
1270
- * against data loss in the case of a Session termination. In these cases, the Subscription can be reassigned to
1271
- * another Client before its lifetime expires.
1272
- */
1273
- closeSession(authenticationToken, deleteSubscriptions, reason) {
1274
- reason = reason || "CloseSession";
1275
- (0, node_opcua_assert_1.assert)(typeof reason === "string");
1276
- (0, node_opcua_assert_1.assert)(reason === "Timeout" || reason === "Terminated" || reason === "CloseSession" || reason === "Forcing");
1277
- debugLog("ServerEngine.closeSession ", authenticationToken.toString(), deleteSubscriptions);
1278
- const session = this.getSession(authenticationToken);
1279
- // istanbul ignore next
1280
- if (!session) {
1281
- throw new Error("cannot find session with this authenticationToken " + authenticationToken.toString());
1282
- }
1283
- if (!deleteSubscriptions) {
1284
- // Live Subscriptions will not be deleted, but transferred to the orphanPublishEngine
1285
- // until they time out or until a other session transfer them back to it.
1286
- if (!this._orphanPublishEngine) {
1287
- this._orphanPublishEngine = new server_publish_engine_for_orphan_subscriptions_1.ServerSidePublishEngineForOrphanSubscription({ maxPublishRequestInQueue: 0 });
1288
- }
1289
- debugLog("transferring remaining live subscription to orphanPublishEngine !");
1290
- server_publish_engine_1.ServerSidePublishEngine.transferSubscriptionsToOrphan(session.publishEngine, this._orphanPublishEngine);
1291
- }
1292
- session.close(deleteSubscriptions, reason);
1293
- (0, node_opcua_assert_1.assert)(session.status === "closed");
1294
- debugLog(" engine.serverDiagnosticsSummary.currentSessionCount -= 1;");
1295
- this.serverDiagnosticsSummary.currentSessionCount -= 1;
1296
- // xx //TODO make sure _closedSessions gets cleaned at some point
1297
- // xx self._closedSessions[key] = session;
1298
- // remove sessionDiagnostics from server.ServerDiagnostics.SessionsDiagnosticsSummary.SessionDiagnosticsSummary
1299
- delete this._sessions[authenticationToken.toString()];
1300
- session.dispose();
1301
- }
1302
- findSubscription(subscriptionId) {
1303
- const subscriptions = [];
1304
- Object.values(this._sessions).map((session) => {
1305
- if (subscriptions.length) {
1306
- return;
1307
- }
1308
- const subscription = session.publishEngine.getSubscriptionById(subscriptionId);
1309
- if (subscription) {
1310
- subscriptions.push(subscription);
1311
- }
1312
- });
1313
- if (subscriptions.length) {
1314
- (0, node_opcua_assert_1.assert)(subscriptions.length === 1);
1315
- return subscriptions[0];
1316
- }
1317
- return this.findOrphanSubscription(subscriptionId);
1318
- }
1319
- findOrphanSubscription(subscriptionId) {
1320
- if (!this._orphanPublishEngine) {
1321
- return null;
1322
- }
1323
- return this._orphanPublishEngine.getSubscriptionById(subscriptionId);
1324
- }
1325
- deleteOrphanSubscription(subscription) {
1326
- if (!this._orphanPublishEngine) {
1327
- return node_opcua_status_code_1.StatusCodes.BadInternalError;
1328
- }
1329
- (0, node_opcua_assert_1.assert)(this.findSubscription(subscription.id));
1330
- const c = this._orphanPublishEngine.subscriptionCount;
1331
- subscription.terminate();
1332
- subscription.dispose();
1333
- (0, node_opcua_assert_1.assert)(this._orphanPublishEngine.subscriptionCount === c - 1);
1334
- return node_opcua_status_code_1.StatusCodes.Good;
1335
- }
1336
- /**
1337
- * @method transferSubscription
1338
- * @param session {ServerSession} - the new session that will own the subscription
1339
- * @param subscriptionId {IntegerId} - the subscription Id to transfer
1340
- * @param sendInitialValues {Boolean} - true if initial values will be resent.
1341
- * @return {TransferResult}
1342
- */
1343
- transferSubscription(session, subscriptionId, sendInitialValues) {
1344
- return __awaiter(this, void 0, void 0, function* () {
1345
- if (subscriptionId <= 0) {
1346
- return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
1347
- }
1348
- const subscription = this.findSubscription(subscriptionId);
1349
- if (!subscription) {
1350
- return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
1351
- }
1352
- // istanbul ignore next
1353
- if (!subscription.$session) {
1354
- return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
1355
- }
1356
- // check that session have same userIdentity
1357
- if (!(0, sessions_compatible_for_transfer_1.sessionsCompatibleForTransfer)(subscription.$session, session)) {
1358
- return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied });
1359
- }
1360
- // update diagnostics
1361
- subscription.subscriptionDiagnostics.transferRequestCount++;
1362
- // now check that new session has sufficient right
1363
- // if (session.authenticationToken.toString() !== subscription.authenticationToken.toString()) {
1364
- // console.log("ServerEngine#transferSubscription => BadUserAccessDenied");
1365
- // return new TransferResult({ statusCode: StatusCodes.BadUserAccessDenied });
1366
- // }
1367
- if (session.publishEngine === subscription.publishEngine) {
1368
- // subscription is already in this session !!
1369
- return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNothingToDo });
1370
- }
1371
- if (session === subscription.$session) {
1372
- // subscription is already in this session !!
1373
- return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNothingToDo });
1374
- }
1375
- // The number of times the subscription has been transferred to an alternate client.
1376
- subscription.subscriptionDiagnostics.transferredToAltClientCount++;
1377
- // The number of times the subscription has been transferred to an alternate session for the same client.
1378
- subscription.subscriptionDiagnostics.transferredToSameClientCount++;
1379
- const nbSubscriptionBefore = session.publishEngine.subscriptionCount;
1380
- subscription.$session._unexposeSubscriptionDiagnostics(subscription);
1381
- yield server_publish_engine_1.ServerSidePublishEngine.transferSubscription(subscription, session.publishEngine, sendInitialValues);
1382
- subscription.$session = session;
1383
- session._exposeSubscriptionDiagnostics(subscription);
1384
- (0, node_opcua_assert_1.assert)(subscription.publishEngine === session.publishEngine);
1385
- // assert(session.publishEngine.subscriptionCount === nbSubscriptionBefore + 1);
1386
- const result = new node_opcua_service_subscription_1.TransferResult({
1387
- availableSequenceNumbers: subscription.getAvailableSequenceNumbers(),
1388
- statusCode: node_opcua_status_code_1.StatusCodes.Good
1389
- });
1390
- // istanbul ignore next
1391
- if (doDebug) {
1392
- debugLog("TransferResult", result.toString());
1393
- }
1394
- return result;
1395
- });
1396
- }
1397
- /**
1398
- * retrieve a session by its authenticationToken.
1399
- *
1400
- * @method getSession
1401
- * @param authenticationToken
1402
- * @param activeOnly
1403
- * @return {ServerSession}
1404
- */
1405
- getSession(authenticationToken, activeOnly) {
1406
- if (!authenticationToken ||
1407
- (authenticationToken.identifierType && authenticationToken.identifierType !== node_opcua_nodeid_1.NodeIdType.BYTESTRING)) {
1408
- return null; // wrong type !
1409
- }
1410
- const key = authenticationToken.toString();
1411
- let session = this._sessions[key];
1412
- if (!activeOnly && !session) {
1413
- session = this._closedSessions[key];
1414
- }
1415
- return session;
1416
- }
1417
- /**
1418
- */
1419
- browsePath(browsePath) {
1420
- return this.addressSpace.browsePath(browsePath);
1421
- }
1422
- /**
1423
- *
1424
- * performs a call to ```asyncRefresh``` on all variable nodes that provide an async refresh func.
1425
- *
1426
- * @method refreshValues
1427
- * @param nodesToRefresh {Array<Object>} an array containing the node to consider
1428
- * Each element of the array shall be of the form { nodeId: <xxx>, attributeIds: <value> }.
1429
- * @param callback
1430
- * @param callback.err
1431
- * @param callback.data an array containing value read
1432
- * The array length matches the number of nodeIds that are candidate for an async refresh (i.e: nodes that
1433
- * are of type Variable with asyncRefresh func }
1434
- *
1435
- * @async
1436
- */
1437
- refreshValues(nodesToRefresh, maxAge, callback) {
1438
- const referenceTime = new Date(Date.now() - maxAge);
1439
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
1440
- const objectMap = {};
1441
- for (const nodeToRefresh of nodesToRefresh) {
1442
- // only consider node for which the caller wants to read the Value attribute
1443
- // assuming that Value is requested if attributeId is missing,
1444
- if (nodeToRefresh instanceof node_opcua_types_1.ReadValueId && nodeToRefresh.attributeId !== node_opcua_data_model_1.AttributeIds.Value) {
1445
- continue;
1446
- }
1447
- // ... and that are valid object and instances of Variables ...
1448
- const obj = this.addressSpace.findNode(nodeToRefresh.nodeId);
1449
- if (!obj || !(obj.nodeClass === node_opcua_data_model_1.NodeClass.Variable)) {
1450
- continue;
1451
- }
1452
- // ... and that have been declared as asynchronously updating
1453
- if (typeof obj.refreshFunc !== "function") {
1454
- continue;
1455
- }
1456
- const key = obj.nodeId.toString();
1457
- if (objectMap[key]) {
1458
- continue;
1459
- }
1460
- objectMap[key] = obj;
1461
- }
1462
- const objectArray = Object.values(objectMap);
1463
- if (objectArray.length === 0) {
1464
- // nothing to do
1465
- return callback(null, []);
1466
- }
1467
- // perform all asyncRefresh in parallel
1468
- async.map(objectArray, (obj, inner_callback) => {
1469
- if (obj.nodeClass !== node_opcua_data_model_1.NodeClass.Variable) {
1470
- inner_callback(null, new node_opcua_data_value_1.DataValue({
1471
- statusCode: node_opcua_status_code_1.StatusCodes.BadNodeClassInvalid
1472
- }));
1473
- return;
1474
- }
1475
- try {
1476
- obj.asyncRefresh(referenceTime, (err, dataValue) => {
1477
- inner_callback(err, dataValue);
1478
- });
1479
- }
1480
- catch (err) {
1481
- // istanbul ignore next
1482
- if (!(err instanceof Error)) {
1483
- throw new Error("internal error");
1484
- }
1485
- errorLog("asyncRefresh internal error", err);
1486
- inner_callback(err);
1487
- }
1488
- }, (err, arrResult) => {
1489
- callback(err || null, arrResult);
1490
- });
1491
- }
1492
- _exposeSubscriptionDiagnostics(subscription) {
1493
- debugLog("ServerEngine#_exposeSubscriptionDiagnostics");
1494
- const subscriptionDiagnosticsArray = this._getServerSubscriptionDiagnosticsArrayNode();
1495
- const subscriptionDiagnostics = subscription.subscriptionDiagnostics;
1496
- (0, node_opcua_assert_1.assert)(subscriptionDiagnostics.$subscription === subscription);
1497
- (0, node_opcua_assert_1.assert)(subscriptionDiagnostics instanceof node_opcua_common_1.SubscriptionDiagnosticsDataType);
1498
- if (subscriptionDiagnostics && subscriptionDiagnosticsArray) {
1499
- (0, node_opcua_address_space_1.addElement)(subscriptionDiagnostics, subscriptionDiagnosticsArray);
1500
- }
1501
- }
1502
- _unexposeSubscriptionDiagnostics(subscription) {
1503
- const subscriptionDiagnosticsArray = this._getServerSubscriptionDiagnosticsArrayNode();
1504
- const subscriptionDiagnostics = subscription.subscriptionDiagnostics;
1505
- (0, node_opcua_assert_1.assert)(subscriptionDiagnostics instanceof node_opcua_common_1.SubscriptionDiagnosticsDataType);
1506
- if (subscriptionDiagnostics && subscriptionDiagnosticsArray) {
1507
- const node = subscriptionDiagnosticsArray[subscription.id];
1508
- (0, node_opcua_address_space_1.removeElement)(subscriptionDiagnosticsArray, subscriptionDiagnostics);
1509
- /*assert(
1510
- !(subscriptionDiagnosticsArray as any)[subscription.id],
1511
- " subscription node must have been removed from subscriptionDiagnosticsArray"
1512
- );
1513
- */
1514
- }
1515
- debugLog("ServerEngine#_unexposeSubscriptionDiagnostics");
1516
- }
1517
- /**
1518
- * create a new subscription
1519
- * @return {Subscription}
1520
- */
1521
- _createSubscriptionOnSession(session, request) {
1522
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "requestedPublishingInterval")); // Duration
1523
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "requestedLifetimeCount")); // Counter
1524
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "requestedMaxKeepAliveCount")); // Counter
1525
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "maxNotificationsPerPublish")); // Counter
1526
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "publishingEnabled")); // Boolean
1527
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "priority")); // Byte
1528
- // adjust publishing parameters
1529
- const publishingInterval = request.requestedPublishingInterval || 0;
1530
- const maxKeepAliveCount = request.requestedMaxKeepAliveCount || 0;
1531
- const lifeTimeCount = request.requestedLifetimeCount || 0;
1532
- const subscription = new server_subscription_1.Subscription({
1533
- id: _get_next_subscriptionId(),
1534
- lifeTimeCount,
1535
- maxKeepAliveCount,
1536
- maxNotificationsPerPublish: request.maxNotificationsPerPublish,
1537
- priority: request.priority || 0,
1538
- publishEngine: session.publishEngine,
1539
- publishingEnabled: request.publishingEnabled,
1540
- publishingInterval,
1541
- // -------------------
1542
- sessionId: node_opcua_nodeid_1.NodeId.nullNodeId
1543
- });
1544
- // add subscriptionDiagnostics
1545
- this._exposeSubscriptionDiagnostics(subscription);
1546
- (0, node_opcua_assert_1.assert)(subscription.publishEngine === session.publishEngine);
1547
- session.publishEngine.add_subscription(subscription);
1548
- // eslint-disable-next-line @typescript-eslint/no-this-alias
1549
- const engine = this;
1550
- subscription.once("terminated", function () {
1551
- engine._unexposeSubscriptionDiagnostics(this);
1552
- });
1553
- return subscription;
1554
- }
1555
- __findNode(nodeId) {
1556
- var _a;
1557
- if (nodeId.namespace >= (((_a = this.addressSpace) === null || _a === void 0 ? void 0 : _a.getNamespaceArray().length) || 0)) {
1558
- return null;
1559
- }
1560
- const namespace = this.addressSpace.getNamespace(nodeId.namespace);
1561
- return namespace.findNode2(nodeId);
1562
- }
1563
- _readSingleNode(context, nodeToRead, timestampsToReturn) {
1564
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1565
- const nodeId = nodeToRead.nodeId;
1566
- const attributeId = nodeToRead.attributeId;
1567
- const indexRange = nodeToRead.indexRange;
1568
- const dataEncoding = nodeToRead.dataEncoding;
1569
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1570
- return new node_opcua_data_value_1.DataValue({ statusCode: node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid });
1571
- }
1572
- timestampsToReturn = (0, node_opcua_data_value_1.coerceTimestampsToReturn)(timestampsToReturn);
1573
- const obj = this.__findNode(nodeId);
1574
- let dataValue;
1575
- if (!obj) {
1576
- // may be return BadNodeIdUnknown in dataValue instead ?
1577
- // Object Not Found
1578
- return new node_opcua_data_value_1.DataValue({ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown });
1579
- }
1580
- else {
1581
- // check access
1582
- // BadUserAccessDenied
1583
- // BadNotReadable
1584
- // invalid attributes : BadNodeAttributesInvalid
1585
- // invalid range : BadIndexRangeInvalid
1586
- dataValue = obj.readAttribute(context, attributeId, indexRange, dataEncoding);
1587
- dataValue = (0, node_opcua_data_value_1.apply_timestamps_no_copy)(dataValue, timestampsToReturn, attributeId);
1588
- return dataValue;
1589
- }
1590
- }
1591
- _historyReadSingleNode(context, nodeToRead, historyReadDetails, timestampsToReturn, continuationData, callback) {
1592
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1593
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
1594
- const nodeId = nodeToRead.nodeId;
1595
- const indexRange = nodeToRead.indexRange;
1596
- const dataEncoding = nodeToRead.dataEncoding;
1597
- const continuationPoint = nodeToRead.continuationPoint;
1598
- timestampsToReturn = (0, node_opcua_data_value_1.coerceTimestampsToReturn)(timestampsToReturn);
1599
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1600
- return callback(null, new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid }));
1601
- }
1602
- const obj = this.__findNode(nodeId);
1603
- if (!obj) {
1604
- // may be return BadNodeIdUnknown in dataValue instead ?
1605
- // Object Not Found
1606
- callback(null, new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown }));
1607
- return;
1608
- }
1609
- else {
1610
- // istanbul ignore next
1611
- if (!obj.historyRead) {
1612
- // note : Object and View may also support historyRead to provide Event historical data
1613
- // todo implement historyRead for Object and View
1614
- const msg = " this node doesn't provide historyRead! probably not a UAVariable\n " +
1615
- obj.nodeId.toString() +
1616
- " " +
1617
- obj.browseName.toString() +
1618
- "\n" +
1619
- "with " +
1620
- nodeToRead.toString() +
1621
- "\n" +
1622
- "HistoryReadDetails " +
1623
- historyReadDetails.toString();
1624
- if (doDebug) {
1625
- debugLog(chalk.cyan("ServerEngine#_historyReadSingleNode "), chalk.white.bold(msg));
1626
- }
1627
- const err = new Error(msg);
1628
- // object has no historyRead method
1629
- setImmediate(callback.bind(null, err));
1630
- return;
1631
- }
1632
- // check access
1633
- // BadUserAccessDenied
1634
- // BadNotReadable
1635
- // invalid attributes : BadNodeAttributesInvalid
1636
- // invalid range : BadIndexRangeInvalid
1637
- obj.historyRead(context, historyReadDetails, indexRange, dataEncoding, continuationData, (err, result) => {
1638
- if (err || !result) {
1639
- return callback(err);
1640
- }
1641
- (0, node_opcua_assert_1.assert)(result.statusCode instanceof node_opcua_status_code_1.StatusCode);
1642
- (0, node_opcua_assert_1.assert)(result.isValid());
1643
- // result = apply_timestamps(result, timestampsToReturn, attributeId);
1644
- callback(err, result);
1645
- });
1646
- }
1647
- }
1648
- /**
1649
- */
1650
- __internal_bindMethod(nodeId, func) {
1651
- (0, node_opcua_assert_1.assert)(typeof func === "function");
1652
- (0, node_opcua_assert_1.assert)(nodeId instanceof node_opcua_nodeid_1.NodeId);
1653
- const methodNode = this.addressSpace.findNode(nodeId);
1654
- if (!methodNode) {
1655
- return;
1656
- }
1657
- // istanbul ignore else
1658
- if (methodNode && methodNode.bindMethod) {
1659
- methodNode.bindMethod(func);
1660
- }
1661
- else {
1662
- warningLog(chalk.yellow("WARNING: cannot bind a method with id ") +
1663
- chalk.cyan(nodeId.toString()) +
1664
- chalk.yellow(". please check your nodeset.xml file or add this node programmatically"));
1665
- warningLog((0, node_opcua_debug_1.traceFromThisProjectOnly)());
1666
- }
1667
- }
1668
- _getServerSubscriptionDiagnosticsArrayNode() {
1669
- // istanbul ignore next
1670
- if (!this.addressSpace) {
1671
- if (doDebug) {
1672
- console.warn("ServerEngine#_getServerSubscriptionDiagnosticsArray : no addressSpace");
1673
- }
1674
- return null; // no addressSpace
1675
- }
1676
- const subscriptionDiagnosticsType = this.addressSpace.findVariableType("SubscriptionDiagnosticsType");
1677
- if (!subscriptionDiagnosticsType) {
1678
- if (doDebug) {
1679
- console.warn("ServerEngine#_getServerSubscriptionDiagnosticsArray " + ": cannot find SubscriptionDiagnosticsType");
1680
- }
1681
- }
1682
- // SubscriptionDiagnosticsArray = i=2290
1683
- const subscriptionDiagnosticsArrayNode = this.addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerDiagnostics_SubscriptionDiagnosticsArray));
1684
- return subscriptionDiagnosticsArrayNode;
1685
- }
1686
- }
1687
- exports.ServerEngine = ServerEngine;
1688
- ServerEngine.registry = new node_opcua_object_registry_1.ObjectRegistry();
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.ServerEngine = void 0;
13
+ /**
14
+ * @module node-opcua-server
15
+ */
16
+ const events_1 = require("events");
17
+ const async = require("async");
18
+ const chalk = require("chalk");
19
+ const node_opcua_assert_1 = require("node-opcua-assert");
20
+ const node_opcua_address_space_1 = require("node-opcua-address-space");
21
+ const nodeJS_1 = require("node-opcua-address-space/nodeJS");
22
+ const node_opcua_data_value_1 = require("node-opcua-data-value");
23
+ const node_opcua_common_1 = require("node-opcua-common");
24
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
25
+ const node_opcua_nodeid_1 = require("node-opcua-nodeid");
26
+ const node_opcua_service_read_1 = require("node-opcua-service-read");
27
+ const node_opcua_constants_1 = require("node-opcua-constants");
28
+ const node_opcua_date_time_1 = require("node-opcua-date-time");
29
+ const node_opcua_debug_1 = require("node-opcua-debug");
30
+ const node_opcua_nodesets_1 = require("node-opcua-nodesets");
31
+ const node_opcua_object_registry_1 = require("node-opcua-object-registry");
32
+ const node_opcua_service_call_1 = require("node-opcua-service-call");
33
+ const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
34
+ const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
35
+ const node_opcua_service_history_1 = require("node-opcua-service-history");
36
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
37
+ const node_opcua_types_1 = require("node-opcua-types");
38
+ const node_opcua_variant_1 = require("node-opcua-variant");
39
+ const history_server_capabilities_1 = require("./history_server_capabilities");
40
+ const monitored_item_1 = require("./monitored_item");
41
+ const server_capabilities_1 = require("./server_capabilities");
42
+ const server_publish_engine_1 = require("./server_publish_engine");
43
+ const server_publish_engine_for_orphan_subscriptions_1 = require("./server_publish_engine_for_orphan_subscriptions");
44
+ const server_session_1 = require("./server_session");
45
+ const server_subscription_1 = require("./server_subscription");
46
+ const sessions_compatible_for_transfer_1 = require("./sessions_compatible_for_transfer");
47
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
48
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
49
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
50
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
51
+ function upperCaseFirst(str) {
52
+ return str.slice(0, 1).toUpperCase() + str.slice(1);
53
+ }
54
+ function shutdownAndDisposeAddressSpace() {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ if (this.addressSpace) {
57
+ yield this.addressSpace.shutdown();
58
+ this.addressSpace.dispose();
59
+ delete this.addressSpace;
60
+ }
61
+ });
62
+ }
63
+ function setSubscriptionDurable(inputArguments, context, callback) {
64
+ // see https://reference.opcfoundation.org/v104/Core/docs/Part5/9.3/
65
+ // https://reference.opcfoundation.org/v104/Core/docs/Part4/6.8/
66
+ (0, node_opcua_assert_1.assert)(Array.isArray(inputArguments));
67
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
68
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(context, "session"), " expecting a session id in the context object");
69
+ const session = context.session;
70
+ if (!session) {
71
+ return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
72
+ }
73
+ const subscriptionId = inputArguments[0].value;
74
+ const lifetimeInHours = inputArguments[1].value;
75
+ const subscription = session.getSubscription(subscriptionId);
76
+ if (!subscription) {
77
+ // subscription may belongs to a different session that ours
78
+ if (this.findSubscription(subscriptionId)) {
79
+ // if yes, then access to Subscription data should be denied
80
+ return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied });
81
+ }
82
+ return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
83
+ }
84
+ if (subscription.monitoredItemCount > 0) {
85
+ // This is returned when a Subscription already contains MonitoredItems.
86
+ return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadInvalidState });
87
+ }
88
+ /**
89
+ * MonitoredItems are used to monitor Variable Values for data changes and event notifier
90
+ * Objects for new Events. Subscriptions are used to combine data changes and events of
91
+ * the assigned MonitoredItems to an optimized stream of network messages. A reliable
92
+ * delivery is ensured as long as the lifetime of the Subscription and the queues in the
93
+ * MonitoredItems are long enough for a network interruption between OPC UA Client and
94
+ * Server. All queues that ensure reliable delivery are normally kept in memory and a
95
+ * Server restart would delete them.
96
+ * There are use cases where OPC UA Clients have no permanent network connection to the
97
+ * OPC UA Server or where reliable delivery of data changes and events is necessary
98
+ * even if the OPC UA Server is restarted or the network connection is interrupted
99
+ * for a longer time.
100
+ * To ensure this reliable delivery, the OPC UA Server must store collected data and
101
+ * events in non-volatile memory until the OPC UA Client has confirmed reception.
102
+ * It is possible that there will be data lost if the Server is not shut down gracefully
103
+ * or in case of power failure. But the OPC UA Server should store the queues frequently
104
+ * even if the Server is not shut down.
105
+ * The Method SetSubscriptionDurable defined in OPC 10000-5 is used to set a Subscription
106
+ * into this durable mode and to allow much longer lifetimes and queue sizes than for normal
107
+ * Subscriptions. The Method shall be called before the MonitoredItems are created in the
108
+ * durable Subscription. The Server shall verify that the Method is called within the
109
+ * Session context of the Session that owns the Subscription.
110
+ *
111
+ * A value of 0 for the parameter lifetimeInHours requests the highest lifetime supported by the Server.
112
+ */
113
+ const highestLifetimeInHours = 24 * 100;
114
+ const revisedLifetimeInHours = lifetimeInHours === 0 ? highestLifetimeInHours : Math.max(1, Math.min(lifetimeInHours, highestLifetimeInHours));
115
+ // also adjust subscription life time
116
+ const currentLifeTimeInHours = (subscription.lifeTimeCount * subscription.publishingInterval) / (1000 * 60 * 60);
117
+ if (currentLifeTimeInHours < revisedLifetimeInHours) {
118
+ const requestedLifetimeCount = Math.ceil((revisedLifetimeInHours * (1000 * 60 * 60)) / subscription.publishingInterval);
119
+ subscription.modify({
120
+ requestedMaxKeepAliveCount: subscription.maxKeepAliveCount,
121
+ requestedPublishingInterval: subscription.publishingInterval,
122
+ maxNotificationsPerPublish: subscription.maxNotificationsPerPublish,
123
+ priority: subscription.priority,
124
+ requestedLifetimeCount
125
+ });
126
+ }
127
+ const callMethodResult = new node_opcua_service_call_1.CallMethodResult({
128
+ statusCode: node_opcua_status_code_1.StatusCodes.Good,
129
+ outputArguments: [{ dataType: node_opcua_variant_1.DataType.UInt32, arrayType: node_opcua_variant_1.VariantArrayType.Scalar, value: revisedLifetimeInHours }]
130
+ });
131
+ callback(null, callMethodResult);
132
+ }
133
+ // binding methods
134
+ function getMonitoredItemsId(inputArguments, context, callback) {
135
+ (0, node_opcua_assert_1.assert)(Array.isArray(inputArguments));
136
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
137
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(context, "session"), " expecting a session id in the context object");
138
+ const session = context.session;
139
+ if (!session) {
140
+ return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
141
+ }
142
+ const subscriptionId = inputArguments[0].value;
143
+ const subscription = session.getSubscription(subscriptionId);
144
+ if (!subscription) {
145
+ // subscription may belongs to a different session that ours
146
+ if (this.findSubscription(subscriptionId)) {
147
+ // if yes, then access to Subscription data should be denied
148
+ return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied });
149
+ }
150
+ return callback(null, { statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
151
+ }
152
+ const result = subscription.getMonitoredItems();
153
+ (0, node_opcua_assert_1.assert)(result.statusCode);
154
+ (0, node_opcua_assert_1.assert)(result.serverHandles.length === result.clientHandles.length);
155
+ const callMethodResult = new node_opcua_service_call_1.CallMethodResult({
156
+ statusCode: result.statusCode,
157
+ outputArguments: [
158
+ { dataType: node_opcua_variant_1.DataType.UInt32, arrayType: node_opcua_variant_1.VariantArrayType.Array, value: result.serverHandles },
159
+ { dataType: node_opcua_variant_1.DataType.UInt32, arrayType: node_opcua_variant_1.VariantArrayType.Array, value: result.clientHandles }
160
+ ]
161
+ });
162
+ callback(null, callMethodResult);
163
+ }
164
+ function __bindVariable(self, nodeId, options) {
165
+ options = options || {};
166
+ const variable = self.addressSpace.findNode(nodeId);
167
+ if (variable && variable.bindVariable) {
168
+ variable.bindVariable(options, true);
169
+ (0, node_opcua_assert_1.assert)(typeof variable.asyncRefresh === "function");
170
+ (0, node_opcua_assert_1.assert)(typeof variable.refreshFunc === "function");
171
+ }
172
+ else {
173
+ warningLog("Warning: cannot bind object with id ", nodeId.toString(), " please check your nodeset.xml file or add this node programmatically");
174
+ }
175
+ }
176
+ // note OPCUA 1.03 part 4 page 76
177
+ // The Server-assigned identifier for the Subscription (see 7.14 for IntegerId definition). This identifier shall
178
+ // be unique for the entire Server, not just for the Session, in order to allow the Subscription to be transferred
179
+ // to another Session using the TransferSubscriptions service.
180
+ // After Server start-up the generation of subscriptionIds should start from a random IntegerId or continue from
181
+ // the point before the restart.
182
+ let next_subscriptionId = Math.ceil(Math.random() * 1000000);
183
+ function _get_next_subscriptionId() {
184
+ debugLog(" next_subscriptionId = ", next_subscriptionId);
185
+ return next_subscriptionId++;
186
+ }
187
+ /**
188
+ *
189
+ */
190
+ class ServerEngine extends events_1.EventEmitter {
191
+ constructor(options) {
192
+ super();
193
+ this._globalCounter = { totalMonitoredItemCount: 0 };
194
+ options = options || { applicationUri: "" };
195
+ options.buildInfo = options.buildInfo || {};
196
+ ServerEngine.registry.register(this);
197
+ this._sessions = {};
198
+ this._closedSessions = {};
199
+ this._orphanPublishEngine = undefined; // will be constructed on demand
200
+ this.isAuditing = typeof options.isAuditing === "boolean" ? options.isAuditing : false;
201
+ options.buildInfo.buildDate = options.buildInfo.buildDate || new Date();
202
+ // ---------------------------------------------------- ServerStatusDataType
203
+ this._serverStatus = new node_opcua_common_1.ServerStatusDataType({
204
+ buildInfo: options.buildInfo,
205
+ currentTime: new Date(),
206
+ secondsTillShutdown: 0,
207
+ shutdownReason: { text: "" },
208
+ startTime: new Date(),
209
+ state: node_opcua_common_1.ServerState.NoConfiguration
210
+ });
211
+ // --------------------------------------------------- ServerCapabilities
212
+ options.serverCapabilities = options.serverCapabilities || {};
213
+ // https://profiles.opcfoundation.org/profile
214
+ options.serverCapabilities.serverProfileArray = options.serverCapabilities.serverProfileArray || [
215
+ "http://opcfoundation.org/UA-Profile/Server/Standard",
216
+ "http://opcfoundation.org/UA-Profile/Server/DataAccess",
217
+ "http://opcfoundation.org/UA-Profile/Server/Events",
218
+ "http://opcfoundation.org/UA-Profile/Client/HistoricalAccess",
219
+ "http://opcfoundation.org/UA-Profile/Server/Methods",
220
+ "http://opcfoundation.org/UA-Profile/Server/StandardEventSubscription",
221
+ "http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary",
222
+ "http://opcfoundation.org/UA-Profile/Server/FileAccess",
223
+ "http://opcfoundation.org/UA-Profile/Server/StateMachine"
224
+ // "http://opcfoundation.org/UA-Profile/Transport/wss-uajson",
225
+ // "http://opcfoundation.org/UA-Profile/Transport/wss-uasc-uabinary"
226
+ // "http://opcfoundation.org/UA-Profile/Server/DurableSubscription"
227
+ // "http://opcfoundation.org/UA-Profile/Server/ReverseConnect",
228
+ // "http://opcfoundation.org/UAProfile/Server/NodeManagement",
229
+ // "Embedded UA Server Profile",
230
+ // "Micro Embedded Device Server Profile",
231
+ // "Nano Embedded Device Server Profile"
232
+ ];
233
+ options.serverCapabilities.localeIdArray = options.serverCapabilities.localeIdArray || ["en-EN", "fr-FR"];
234
+ this.serverCapabilities = new server_capabilities_1.ServerCapabilities(options.serverCapabilities);
235
+ // to do when spec is clear about what goes here!
236
+ // spec 1.04 says (in Part 4 7.33 SignedSoftwareCertificate
237
+ // Note: Details on SoftwareCertificates need to be defined in a future version.
238
+ this.serverCapabilities.softwareCertificates = [
239
+ // new SignedSoftwareCertificate({})
240
+ ];
241
+ // make sure minSupportedSampleRate matches MonitoredItem.minimumSamplingInterval
242
+ this.serverCapabilities.__defineGetter__("minSupportedSampleRate", () => {
243
+ return monitored_item_1.MonitoredItem.minimumSamplingInterval;
244
+ });
245
+ this.historyServerCapabilities = new history_server_capabilities_1.HistoryServerCapabilities(options.historyServerCapabilities);
246
+ // --------------------------------------------------- serverDiagnosticsSummary extension Object
247
+ this.serverDiagnosticsSummary = new node_opcua_common_1.ServerDiagnosticsSummaryDataType();
248
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(this.serverDiagnosticsSummary, "currentSessionCount"));
249
+ // note spelling is different for serverDiagnosticsSummary.currentSubscriptionCount
250
+ // and sessionDiagnostics.currentSubscriptionsCount ( with an s)
251
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(this.serverDiagnosticsSummary, "currentSubscriptionCount"));
252
+ this.serverDiagnosticsSummary.__defineGetter__("currentSubscriptionCount", () => {
253
+ // currentSubscriptionCount returns the total number of subscriptions
254
+ // that are currently active on all sessions
255
+ let counter = 0;
256
+ Object.values(this._sessions).forEach((session) => {
257
+ counter += session.currentSubscriptionCount;
258
+ });
259
+ return counter;
260
+ });
261
+ this._internalState = "creating";
262
+ this.setServerState(node_opcua_common_1.ServerState.NoConfiguration);
263
+ this.addressSpace = null;
264
+ this._shutdownTasks = [];
265
+ this._applicationUri = "";
266
+ if (typeof options.applicationUri === "function") {
267
+ this.__defineGetter__("_applicationUri", options.applicationUri);
268
+ }
269
+ else {
270
+ this._applicationUri = options.applicationUri || "<unset _applicationUri>";
271
+ }
272
+ options.serverDiagnosticsEnabled = Object.prototype.hasOwnProperty.call(options, "serverDiagnosticsEnable")
273
+ ? options.serverDiagnosticsEnabled
274
+ : true;
275
+ this.serverDiagnosticsEnabled = options.serverDiagnosticsEnabled;
276
+ }
277
+ isStarted() {
278
+ return !!this._serverStatus;
279
+ }
280
+ dispose() {
281
+ this.addressSpace = null;
282
+ (0, node_opcua_assert_1.assert)(Object.keys(this._sessions).length === 0, "ServerEngine#_sessions not empty");
283
+ this._sessions = {};
284
+ // todo fix me
285
+ this._closedSessions = {};
286
+ (0, node_opcua_assert_1.assert)(Object.keys(this._closedSessions).length === 0, "ServerEngine#_closedSessions not empty");
287
+ this._closedSessions = {};
288
+ if (this._orphanPublishEngine) {
289
+ this._orphanPublishEngine.dispose();
290
+ this._orphanPublishEngine = undefined;
291
+ }
292
+ this._shutdownTasks = [];
293
+ this._serverStatus = null;
294
+ this._internalState = "disposed";
295
+ this.removeAllListeners();
296
+ ServerEngine.registry.unregister(this);
297
+ }
298
+ get startTime() {
299
+ return this._serverStatus.startTime;
300
+ }
301
+ get currentTime() {
302
+ return this._serverStatus.currentTime;
303
+ }
304
+ get buildInfo() {
305
+ return this._serverStatus.buildInfo;
306
+ }
307
+ /**
308
+ * register a function that will be called when the server will perform its shut down.
309
+ * @method registerShutdownTask
310
+ */
311
+ registerShutdownTask(task) {
312
+ (0, node_opcua_assert_1.assert)(typeof task === "function");
313
+ this._shutdownTasks.push(task);
314
+ }
315
+ /**
316
+ * @method shutdown
317
+ */
318
+ shutdown() {
319
+ return __awaiter(this, void 0, void 0, function* () {
320
+ debugLog("ServerEngine#shutdown");
321
+ this._internalState = "shutdown";
322
+ this.setServerState(node_opcua_common_1.ServerState.Shutdown);
323
+ // delete any existing sessions
324
+ const tokens = Object.keys(this._sessions).map((key) => {
325
+ const session = this._sessions[key];
326
+ return session.authenticationToken;
327
+ });
328
+ // delete and close any orphan subscriptions
329
+ if (this._orphanPublishEngine) {
330
+ this._orphanPublishEngine.shutdown();
331
+ }
332
+ for (const token of tokens) {
333
+ this.closeSession(token, true, "Terminated");
334
+ }
335
+ // all sessions must have been terminated
336
+ (0, node_opcua_assert_1.assert)(this.currentSessionCount === 0);
337
+ // all subscriptions must have been terminated
338
+ (0, node_opcua_assert_1.assert)(this.currentSubscriptionCount === 0, "all subscriptions must have been terminated");
339
+ this._shutdownTasks.push(shutdownAndDisposeAddressSpace);
340
+ // perform registerShutdownTask
341
+ for (const task of this._shutdownTasks) {
342
+ yield task.call(this);
343
+ }
344
+ this.dispose();
345
+ });
346
+ }
347
+ /**
348
+ * the number of active sessions
349
+ */
350
+ get currentSessionCount() {
351
+ return this.serverDiagnosticsSummary.currentSessionCount;
352
+ }
353
+ /**
354
+ * the cumulated number of sessions that have been opened since this object exists
355
+ */
356
+ get cumulatedSessionCount() {
357
+ return this.serverDiagnosticsSummary.cumulatedSessionCount;
358
+ }
359
+ /**
360
+ * the number of active subscriptions.
361
+ */
362
+ get currentSubscriptionCount() {
363
+ return this.serverDiagnosticsSummary.currentSubscriptionCount;
364
+ }
365
+ /**
366
+ * the cumulated number of subscriptions that have been created since this object exists
367
+ */
368
+ get cumulatedSubscriptionCount() {
369
+ return this.serverDiagnosticsSummary.cumulatedSubscriptionCount;
370
+ }
371
+ get rejectedSessionCount() {
372
+ return this.serverDiagnosticsSummary.rejectedSessionCount;
373
+ }
374
+ get rejectedRequestsCount() {
375
+ return this.serverDiagnosticsSummary.rejectedRequestsCount;
376
+ }
377
+ get sessionAbortCount() {
378
+ return this.serverDiagnosticsSummary.sessionAbortCount;
379
+ }
380
+ get sessionTimeoutCount() {
381
+ return this.serverDiagnosticsSummary.sessionTimeoutCount;
382
+ }
383
+ get publishingIntervalCount() {
384
+ return this.serverDiagnosticsSummary.publishingIntervalCount;
385
+ }
386
+ incrementSessionTimeoutCount() {
387
+ if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
388
+ // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
389
+ this.serverDiagnosticsSummary.sessionTimeoutCount += 1;
390
+ }
391
+ }
392
+ incrementSessionAbortCount() {
393
+ if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
394
+ // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
395
+ this.serverDiagnosticsSummary.sessionAbortCount += 1;
396
+ }
397
+ }
398
+ incrementRejectedRequestsCount() {
399
+ if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
400
+ // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
401
+ this.serverDiagnosticsSummary.rejectedRequestsCount += 1;
402
+ }
403
+ }
404
+ /**
405
+ * increment rejected session count (also increment rejected requests count)
406
+ */
407
+ incrementRejectedSessionCount() {
408
+ if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
409
+ // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
410
+ this.serverDiagnosticsSummary.rejectedSessionCount += 1;
411
+ }
412
+ this.incrementRejectedRequestsCount();
413
+ }
414
+ incrementSecurityRejectedRequestsCount() {
415
+ if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
416
+ // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
417
+ this.serverDiagnosticsSummary.securityRejectedRequestsCount += 1;
418
+ }
419
+ this.incrementRejectedRequestsCount();
420
+ }
421
+ /**
422
+ * increment rejected session count (also increment rejected requests count)
423
+ */
424
+ incrementSecurityRejectedSessionCount() {
425
+ if (this.serverDiagnosticsSummary && this.serverDiagnosticsEnabled) {
426
+ // The requests include all Services defined in Part 4 of the OPC UA Specification, also requests to create sessions. This number includes the securityRejectedRequestsCount.
427
+ this.serverDiagnosticsSummary.securityRejectedSessionCount += 1;
428
+ }
429
+ this.incrementSecurityRejectedRequestsCount();
430
+ }
431
+ setShutdownTime(date) {
432
+ this._expectedShutdownTime = date;
433
+ }
434
+ setShutdownReason(reason) {
435
+ var _a;
436
+ (_a = this.addressSpace) === null || _a === void 0 ? void 0 : _a.rootFolder.objects.server.serverStatus.shutdownReason.setValueFromSource({
437
+ dataType: node_opcua_variant_1.DataType.LocalizedText,
438
+ value: (0, node_opcua_data_model_1.coerceLocalizedText)(reason)
439
+ });
440
+ }
441
+ /**
442
+ * @method secondsTillShutdown
443
+ * @return the approximate number of seconds until the server will be shut down. The
444
+ * value is only relevant once the state changes into SHUTDOWN.
445
+ */
446
+ secondsTillShutdown() {
447
+ if (!this._expectedShutdownTime) {
448
+ return 0;
449
+ }
450
+ // ToDo: implement a correct solution here
451
+ const now = Date.now();
452
+ return Math.max(0, Math.ceil((this._expectedShutdownTime.getTime() - now) / 1000));
453
+ }
454
+ /**
455
+ * the name of the server
456
+ */
457
+ get serverName() {
458
+ return this._serverStatus.buildInfo.productName;
459
+ }
460
+ /**
461
+ * the server urn
462
+ */
463
+ get serverNameUrn() {
464
+ return this._applicationUri;
465
+ }
466
+ /**
467
+ * the urn of the server namespace
468
+ */
469
+ get serverNamespaceUrn() {
470
+ return this._applicationUri; // "urn:" + engine.serverName;
471
+ }
472
+ get serverStatus() {
473
+ return this._serverStatus;
474
+ }
475
+ setServerState(serverState) {
476
+ var _a, _b, _c, _d, _e, _f;
477
+ (0, node_opcua_assert_1.assert)(serverState !== null && serverState !== undefined);
478
+ (_f = (_e = (_d = (_c = (_b = (_a = this.addressSpace) === null || _a === void 0 ? void 0 : _a.rootFolder) === null || _b === void 0 ? void 0 : _b.objects) === null || _c === void 0 ? void 0 : _c.server) === null || _d === void 0 ? void 0 : _d.serverStatus) === null || _e === void 0 ? void 0 : _e.state) === null || _f === void 0 ? void 0 : _f.setValueFromSource({
479
+ dataType: node_opcua_variant_1.DataType.Int32,
480
+ value: serverState
481
+ });
482
+ }
483
+ getServerDiagnosticsEnabledFlag() {
484
+ const server = this.addressSpace.rootFolder.objects.server;
485
+ const serverDiagnostics = server.getComponentByName("ServerDiagnostics");
486
+ if (!serverDiagnostics) {
487
+ return false;
488
+ }
489
+ return serverDiagnostics.readValue().value.value;
490
+ }
491
+ /**
492
+ * @method initialize
493
+ * @async
494
+ *
495
+ * @param options {Object}
496
+ * @param options.nodeset_filename {String} - [option](default : 'mini.Node.Set2.xml' )
497
+ * @param callback
498
+ */
499
+ initialize(options, callback) {
500
+ (0, node_opcua_assert_1.assert)(!this.addressSpace); // check that 'initialize' has not been already called
501
+ this._internalState = "initializing";
502
+ options = options || {};
503
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
504
+ options.nodeset_filename = options.nodeset_filename || node_opcua_nodesets_1.nodesets.standard;
505
+ const startTime = new Date();
506
+ debugLog("Loading ", options.nodeset_filename, "...");
507
+ this.addressSpace = node_opcua_address_space_1.AddressSpace.create();
508
+ // register namespace 1 (our namespace);
509
+ const serverNamespace = this.addressSpace.registerNamespace(this.serverNamespaceUrn);
510
+ (0, node_opcua_assert_1.assert)(serverNamespace.index === 1);
511
+ // eslint-disable-next-line max-statements
512
+ (0, nodeJS_1.generateAddressSpace)(this.addressSpace, options.nodeset_filename, () => {
513
+ /* istanbul ignore next */
514
+ if (!this.addressSpace) {
515
+ throw new Error("Internal error");
516
+ }
517
+ const addressSpace = this.addressSpace;
518
+ const endTime = new Date();
519
+ debugLog("Loading ", options.nodeset_filename, " done : ", endTime.getTime() - startTime.getTime(), " ms");
520
+ const bindVariableIfPresent = (nodeId, opts) => {
521
+ (0, node_opcua_assert_1.assert)(nodeId instanceof node_opcua_nodeid_1.NodeId);
522
+ (0, node_opcua_assert_1.assert)(!nodeId.isEmpty());
523
+ const obj = addressSpace.findNode(nodeId);
524
+ if (obj) {
525
+ __bindVariable(this, nodeId, opts);
526
+ }
527
+ return obj;
528
+ };
529
+ // -------------------------------------------- install default get/put handler
530
+ const server_NamespaceArray_Id = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_NamespaceArray); // ns=0;i=2255
531
+ bindVariableIfPresent(server_NamespaceArray_Id, {
532
+ get() {
533
+ return new node_opcua_variant_1.Variant({
534
+ arrayType: node_opcua_variant_1.VariantArrayType.Array,
535
+ dataType: node_opcua_variant_1.DataType.String,
536
+ value: addressSpace.getNamespaceArray().map((x) => x.namespaceUri)
537
+ });
538
+ },
539
+ set: null // read only
540
+ });
541
+ const server_NameUrn_var = new node_opcua_variant_1.Variant({
542
+ arrayType: node_opcua_variant_1.VariantArrayType.Array,
543
+ dataType: node_opcua_variant_1.DataType.String,
544
+ value: [
545
+ this.serverNameUrn // this is us !
546
+ ]
547
+ });
548
+ const server_ServerArray_Id = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerArray); // ns=0;i=2254
549
+ bindVariableIfPresent(server_ServerArray_Id, {
550
+ get() {
551
+ return server_NameUrn_var;
552
+ },
553
+ set: null // read only
554
+ });
555
+ // fix DefaultUserRolePermissions and DefaultUserRolePermissions
556
+ // of namespaces
557
+ const namespaces = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.ObjectIds.Server_Namespaces);
558
+ const namespacesNode = addressSpace.findNode(namespaces);
559
+ if (namespacesNode) {
560
+ for (const ns of namespacesNode.getComponents()) {
561
+ const defaultUserRolePermissions = ns.getChildByName("DefaultUserRolePermissions");
562
+ if (defaultUserRolePermissions) {
563
+ defaultUserRolePermissions.setValueFromSource({ dataType: node_opcua_variant_1.DataType.Null });
564
+ }
565
+ const defaultRolePermissions = ns.getChildByName("DefaultRolePermissions");
566
+ if (defaultRolePermissions) {
567
+ defaultRolePermissions.setValueFromSource({ dataType: node_opcua_variant_1.DataType.Null });
568
+ }
569
+ }
570
+ }
571
+ const bindStandardScalar = (id, dataType, func, setter_func) => {
572
+ (0, node_opcua_assert_1.assert)(typeof id === "number", "expecting id to be a number");
573
+ (0, node_opcua_assert_1.assert)(typeof func === "function");
574
+ (0, node_opcua_assert_1.assert)(typeof setter_func === "function" || !setter_func);
575
+ (0, node_opcua_assert_1.assert)(dataType !== null); // check invalid dataType
576
+ let setter_func2 = null;
577
+ if (setter_func) {
578
+ setter_func2 = (variant) => {
579
+ const variable2 = !!variant.value;
580
+ setter_func(variable2);
581
+ return node_opcua_status_code_1.StatusCodes.Good;
582
+ };
583
+ }
584
+ const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(id);
585
+ // make sur the provided function returns a valid value for the variant type
586
+ // This test may not be exhaustive but it will detect obvious mistakes.
587
+ /* istanbul ignore next */
588
+ if (!(0, node_opcua_variant_1.isValidVariant)(node_opcua_variant_1.VariantArrayType.Scalar, dataType, func())) {
589
+ errorLog("func", func());
590
+ throw new Error("bindStandardScalar : func doesn't provide an value of type " + node_opcua_variant_1.DataType[dataType]);
591
+ }
592
+ return bindVariableIfPresent(nodeId, {
593
+ get() {
594
+ return new node_opcua_variant_1.Variant({
595
+ arrayType: node_opcua_variant_1.VariantArrayType.Scalar,
596
+ dataType,
597
+ value: func()
598
+ });
599
+ },
600
+ set: setter_func2
601
+ });
602
+ };
603
+ const bindStandardArray = (id, variantDataType, dataType, func) => {
604
+ (0, node_opcua_assert_1.assert)(typeof func === "function");
605
+ (0, node_opcua_assert_1.assert)(variantDataType !== null); // check invalid dataType
606
+ const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(id);
607
+ // make sur the provided function returns a valid value for the variant type
608
+ // This test may not be exhaustive but it will detect obvious mistakes.
609
+ (0, node_opcua_assert_1.assert)((0, node_opcua_variant_1.isValidVariant)(node_opcua_variant_1.VariantArrayType.Array, variantDataType, func()));
610
+ bindVariableIfPresent(nodeId, {
611
+ get() {
612
+ const value = func();
613
+ (0, node_opcua_assert_1.assert)(Array.isArray(value));
614
+ return new node_opcua_variant_1.Variant({
615
+ arrayType: node_opcua_variant_1.VariantArrayType.Array,
616
+ dataType: variantDataType,
617
+ value
618
+ });
619
+ },
620
+ set: null // read only
621
+ });
622
+ };
623
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_EstimatedReturnTime, node_opcua_variant_1.DataType.DateTime, () => node_opcua_date_time_1.minOPCUADate);
624
+ // TimeZoneDataType
625
+ const timeZoneDataType = addressSpace.findDataType((0, node_opcua_nodeid_1.resolveNodeId)(node_opcua_constants_1.DataTypeIds.TimeZoneDataType));
626
+ const timeZone = new node_opcua_types_1.TimeZoneDataType({
627
+ daylightSavingInOffset: /* boolean*/ false,
628
+ offset: /* int16 */ 0
629
+ });
630
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_LocalTime, node_opcua_variant_1.DataType.ExtensionObject, () => {
631
+ return timeZone;
632
+ });
633
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServiceLevel, node_opcua_variant_1.DataType.Byte, () => {
634
+ return 255;
635
+ });
636
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_Auditing, node_opcua_variant_1.DataType.Boolean, () => {
637
+ return this.isAuditing;
638
+ });
639
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
640
+ const engine = this;
641
+ const makeNotReadableIfEnabledFlagIsFalse = (variable) => {
642
+ const originalIsReadable = variable.isReadable;
643
+ variable.isUserReadable = checkReadableFlag;
644
+ function checkReadableFlag(context) {
645
+ const isEnabled = engine.serverDiagnosticsEnabled;
646
+ return originalIsReadable.call(this, context) && isEnabled;
647
+ }
648
+ for (const c of variable.getAggregates()) {
649
+ if (c.nodeClass === node_opcua_data_model_1.NodeClass.Variable) {
650
+ makeNotReadableIfEnabledFlagIsFalse(c);
651
+ }
652
+ }
653
+ };
654
+ const bindServerDiagnostics = () => {
655
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerDiagnostics_EnabledFlag, node_opcua_variant_1.DataType.Boolean, () => {
656
+ return this.serverDiagnosticsEnabled;
657
+ }, (newFlag) => {
658
+ this.serverDiagnosticsEnabled = newFlag;
659
+ });
660
+ const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerDiagnostics_ServerDiagnosticsSummary);
661
+ const serverDiagnosticsSummaryNode = addressSpace.findNode(nodeId);
662
+ if (serverDiagnosticsSummaryNode) {
663
+ serverDiagnosticsSummaryNode.bindExtensionObject(this.serverDiagnosticsSummary);
664
+ this.serverDiagnosticsSummary = serverDiagnosticsSummaryNode.$extensionObject;
665
+ makeNotReadableIfEnabledFlagIsFalse(serverDiagnosticsSummaryNode);
666
+ }
667
+ };
668
+ const bindServerStatus = () => {
669
+ const serverStatusNode = addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerStatus));
670
+ if (!serverStatusNode) {
671
+ return;
672
+ }
673
+ if (serverStatusNode) {
674
+ serverStatusNode.bindExtensionObject(this._serverStatus);
675
+ serverStatusNode.minimumSamplingInterval = 1000;
676
+ }
677
+ const currentTimeNode = addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerStatus_CurrentTime));
678
+ if (currentTimeNode) {
679
+ currentTimeNode.minimumSamplingInterval = 1000;
680
+ }
681
+ const secondsTillShutdown = addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerStatus_SecondsTillShutdown));
682
+ if (secondsTillShutdown) {
683
+ secondsTillShutdown.minimumSamplingInterval = 1000;
684
+ }
685
+ (0, node_opcua_assert_1.assert)(serverStatusNode.$extensionObject);
686
+ serverStatusNode.$extensionObject = new Proxy(serverStatusNode.$extensionObject, {
687
+ get(target, prop) {
688
+ if (prop === "currentTime") {
689
+ serverStatusNode.currentTime.touchValue();
690
+ return new Date();
691
+ }
692
+ else if (prop === "secondsTillShutdown") {
693
+ serverStatusNode.secondsTillShutdown.touchValue();
694
+ return engine.secondsTillShutdown();
695
+ }
696
+ return target[prop];
697
+ }
698
+ });
699
+ this._serverStatus = serverStatusNode.$extensionObject;
700
+ };
701
+ const bindServerCapabilities = () => {
702
+ bindStandardArray(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_ServerProfileArray, node_opcua_variant_1.DataType.String, node_opcua_variant_1.DataType.String, () => {
703
+ return this.serverCapabilities.serverProfileArray;
704
+ });
705
+ bindStandardArray(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_LocaleIdArray, node_opcua_variant_1.DataType.String, "LocaleId", () => {
706
+ return this.serverCapabilities.localeIdArray;
707
+ });
708
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MinSupportedSampleRate, node_opcua_variant_1.DataType.Double, () => {
709
+ return this.serverCapabilities.minSupportedSampleRate;
710
+ });
711
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxBrowseContinuationPoints, node_opcua_variant_1.DataType.UInt16, () => {
712
+ return this.serverCapabilities.maxBrowseContinuationPoints;
713
+ });
714
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxQueryContinuationPoints, node_opcua_variant_1.DataType.UInt16, () => {
715
+ return this.serverCapabilities.maxQueryContinuationPoints;
716
+ });
717
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxHistoryContinuationPoints, node_opcua_variant_1.DataType.UInt16, () => {
718
+ return this.serverCapabilities.maxHistoryContinuationPoints;
719
+ });
720
+ // new in 1.05
721
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxSessions, node_opcua_variant_1.DataType.UInt32, () => {
722
+ return this.serverCapabilities.maxSessions;
723
+ });
724
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxSubscriptions, node_opcua_variant_1.DataType.UInt32, () => {
725
+ return this.serverCapabilities.maxSubscriptions;
726
+ });
727
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxMonitoredItems, node_opcua_variant_1.DataType.UInt32, () => {
728
+ return this.serverCapabilities.maxMonitoredItems;
729
+ });
730
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxSubscriptionsPerSession, node_opcua_variant_1.DataType.UInt32, () => {
731
+ return this.serverCapabilities.maxSubscriptionsPerSession;
732
+ });
733
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxSelectClauseParameters, node_opcua_variant_1.DataType.UInt32, () => {
734
+ return this.serverCapabilities.maxSelectClauseParameters;
735
+ });
736
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxWhereClauseParameters, node_opcua_variant_1.DataType.UInt32, () => {
737
+ return this.serverCapabilities.maxWhereClauseParameters;
738
+ });
739
+ //bindStandardArray(VariableIds.Server_ServerCapabilities_ConformanceUnits, DataType.QualifiedName, () => {
740
+ // return this.serverCapabilities.conformanceUnits;
741
+ //});
742
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxMonitoredItemsPerSubscription, node_opcua_variant_1.DataType.UInt32, () => {
743
+ return this.serverCapabilities.maxMonitoredItemsPerSubscription;
744
+ });
745
+ // added by DI : Server-specific period of time in milliseconds until the Server will revoke a lock.
746
+ // TODO bindStandardScalar(VariableIds.Server_ServerCapabilities_MaxInactiveLockTime,
747
+ // TODO DataType.UInt16, function () {
748
+ // TODO return self.serverCapabilities.maxInactiveLockTime;
749
+ // TODO });
750
+ bindStandardArray(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_SoftwareCertificates, node_opcua_variant_1.DataType.ExtensionObject, "SoftwareCertificates", () => {
751
+ return this.serverCapabilities.softwareCertificates;
752
+ });
753
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxArrayLength, node_opcua_variant_1.DataType.UInt32, () => {
754
+ return this.serverCapabilities.maxArrayLength;
755
+ });
756
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxStringLength, node_opcua_variant_1.DataType.UInt32, () => {
757
+ return this.serverCapabilities.maxStringLength;
758
+ });
759
+ bindStandardScalar(node_opcua_constants_1.VariableIds.Server_ServerCapabilities_MaxByteStringLength, node_opcua_variant_1.DataType.UInt32, () => {
760
+ return this.serverCapabilities.maxByteStringLength;
761
+ });
762
+ const bindOperationLimits = (operationLimits) => {
763
+ (0, node_opcua_assert_1.assert)(operationLimits !== null && typeof operationLimits === "object");
764
+ const keys = Object.keys(operationLimits);
765
+ keys.forEach((key) => {
766
+ const uid = "Server_ServerCapabilities_OperationLimits_" + upperCaseFirst(key);
767
+ const nodeId = (0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds[uid]);
768
+ (0, node_opcua_assert_1.assert)(!nodeId.isEmpty());
769
+ bindStandardScalar(node_opcua_constants_1.VariableIds[uid], node_opcua_variant_1.DataType.UInt32, () => {
770
+ return operationLimits[key];
771
+ });
772
+ });
773
+ };
774
+ bindOperationLimits(this.serverCapabilities.operationLimits);
775
+ // i=2399 [ProgramStateMachineType_ProgramDiagnostics];
776
+ function fix_ProgramStateMachineType_ProgramDiagnostics() {
777
+ const nodeId = (0, node_opcua_nodeid_1.coerceNodeId)("i=2399"); // ProgramStateMachineType_ProgramDiagnostics
778
+ const variable = addressSpace.findNode(nodeId);
779
+ if (variable) {
780
+ variable.$extensionObject = new node_opcua_types_1.ProgramDiagnosticDataType({});
781
+ // variable.setValueFromSource({
782
+ // dataType: DataType.ExtensionObject,
783
+ // // value: new ProgramDiagnostic2DataType()
784
+ // value: new ProgramDiagnosticDataType({})
785
+ // });
786
+ }
787
+ }
788
+ fix_ProgramStateMachineType_ProgramDiagnostics();
789
+ };
790
+ const bindHistoryServerCapabilities = () => {
791
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_MaxReturnDataValues, node_opcua_variant_1.DataType.UInt32, () => {
792
+ return this.historyServerCapabilities.maxReturnDataValues;
793
+ });
794
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_MaxReturnEventValues, node_opcua_variant_1.DataType.UInt32, () => {
795
+ return this.historyServerCapabilities.maxReturnEventValues;
796
+ });
797
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_AccessHistoryDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
798
+ return this.historyServerCapabilities.accessHistoryDataCapability;
799
+ });
800
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_AccessHistoryEventsCapability, node_opcua_variant_1.DataType.Boolean, () => {
801
+ return this.historyServerCapabilities.accessHistoryEventsCapability;
802
+ });
803
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_InsertDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
804
+ return this.historyServerCapabilities.insertDataCapability;
805
+ });
806
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_ReplaceDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
807
+ return this.historyServerCapabilities.replaceDataCapability;
808
+ });
809
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_UpdateDataCapability, node_opcua_variant_1.DataType.Boolean, () => {
810
+ return this.historyServerCapabilities.updateDataCapability;
811
+ });
812
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_InsertEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
813
+ return this.historyServerCapabilities.insertEventCapability;
814
+ });
815
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_ReplaceEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
816
+ return this.historyServerCapabilities.replaceEventCapability;
817
+ });
818
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_UpdateEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
819
+ return this.historyServerCapabilities.updateEventCapability;
820
+ });
821
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_DeleteEventCapability, node_opcua_variant_1.DataType.Boolean, () => {
822
+ return this.historyServerCapabilities.deleteEventCapability;
823
+ });
824
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_DeleteRawCapability, node_opcua_variant_1.DataType.Boolean, () => {
825
+ return this.historyServerCapabilities.deleteRawCapability;
826
+ });
827
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_DeleteAtTimeCapability, node_opcua_variant_1.DataType.Boolean, () => {
828
+ return this.historyServerCapabilities.deleteAtTimeCapability;
829
+ });
830
+ bindStandardScalar(node_opcua_constants_1.VariableIds.HistoryServerCapabilities_InsertAnnotationCapability, node_opcua_variant_1.DataType.Boolean, () => {
831
+ return this.historyServerCapabilities.insertAnnotationCapability;
832
+ });
833
+ };
834
+ bindServerDiagnostics();
835
+ bindServerStatus();
836
+ bindServerCapabilities();
837
+ bindHistoryServerCapabilities();
838
+ const bindExtraStuff = () => {
839
+ // mainly for compliance
840
+ /*
841
+ // The version number for the data type description. i=104
842
+ bindStandardScalar(VariableIds.DataTypeDescriptionType_DataTypeVersion, DataType.String, () => {
843
+ return "0";
844
+ });
845
+
846
+ const namingRuleDataTypeNode = addressSpace.findDataType(resolveNodeId(DataTypeIds.NamingRuleType))! as UADataType;
847
+
848
+ if (namingRuleDataTypeNode) {
849
+ const namingRuleType = (namingRuleDataTypeNode as any)._getEnumerationInfo().nameIndex; // getEnumeration("NamingRuleType");
850
+ if (!namingRuleType) {
851
+ throw new Error("Cannot find Enumeration definition for NamingRuleType");
852
+ }
853
+ // i=111
854
+ bindStandardScalar(VariableIds.ModellingRuleType_NamingRule, DataType.Int32, () => {
855
+ return 0;
856
+ });
857
+
858
+ // i=112
859
+ bindStandardScalar(VariableIds.ModellingRule_Mandatory_NamingRule, DataType.Int32, () => {
860
+ return namingRuleType.Mandatory ? namingRuleType.Mandatory.value : 0;
861
+ });
862
+
863
+ // i=113
864
+ bindStandardScalar(VariableIds.ModellingRule_Optional_NamingRule, DataType.Int32, () => {
865
+ return namingRuleType.Optional ? namingRuleType.Optional.value : 0;
866
+ });
867
+ // i=114
868
+ bindStandardScalar(VariableIds.ModellingRule_ExposesItsArray_NamingRule, DataType.Int32, () => {
869
+ return namingRuleType.ExposesItsArray ? namingRuleType.ExposesItsArray.value : 0;
870
+ });
871
+ bindStandardScalar(VariableIds.ModellingRule_MandatoryPlaceholder_NamingRule, DataType.Int32, () => {
872
+ return namingRuleType.MandatoryPlaceholder ? namingRuleType.MandatoryPlaceholder.value : 0;
873
+ });
874
+ }
875
+ */
876
+ };
877
+ bindExtraStuff();
878
+ this.__internal_bindMethod((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.MethodIds.Server_GetMonitoredItems), getMonitoredItemsId.bind(this));
879
+ this.__internal_bindMethod((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.MethodIds.Server_SetSubscriptionDurable), setSubscriptionDurable.bind(this));
880
+ // fix getMonitoredItems.outputArguments arrayDimensions
881
+ const fixGetMonitoredItemArgs = () => {
882
+ var _a;
883
+ const objects = (_a = this.addressSpace.rootFolder) === null || _a === void 0 ? void 0 : _a.objects;
884
+ if (!objects || !objects.server || !objects.server.getMonitoredItems) {
885
+ return;
886
+ }
887
+ const outputArguments = objects.server.getMonitoredItems.outputArguments;
888
+ const dataValue = outputArguments.readValue();
889
+ (0, node_opcua_assert_1.assert)(dataValue.value.value[0].arrayDimensions.length === 1 && dataValue.value.value[0].arrayDimensions[0] === 0);
890
+ (0, node_opcua_assert_1.assert)(dataValue.value.value[1].arrayDimensions.length === 1 && dataValue.value.value[1].arrayDimensions[0] === 0);
891
+ };
892
+ fixGetMonitoredItemArgs();
893
+ const prepareServerDiagnostics = () => {
894
+ const addressSpace1 = this.addressSpace;
895
+ if (!addressSpace1.rootFolder.objects) {
896
+ return;
897
+ }
898
+ const server = addressSpace1.rootFolder.objects.server;
899
+ if (!server) {
900
+ return;
901
+ }
902
+ // create SessionsDiagnosticsSummary
903
+ const serverDiagnosticsNode = server.getComponentByName("ServerDiagnostics");
904
+ if (!serverDiagnosticsNode) {
905
+ return;
906
+ }
907
+ if (true) {
908
+ // set serverDiagnosticsNode enabledFlag writeable for admin user only
909
+ // TO DO ...
910
+ serverDiagnosticsNode.enabledFlag.userAccessLevel = (0, node_opcua_data_model_1.makeAccessLevelFlag)("CurrentRead");
911
+ serverDiagnosticsNode.enabledFlag.accessLevel = (0, node_opcua_data_model_1.makeAccessLevelFlag)("CurrentRead");
912
+ }
913
+ // A Server may not expose the SamplingIntervalDiagnosticsArray if it does not use fixed sampling rates.
914
+ // because we are not using fixed sampling rate, we need to remove the optional SamplingIntervalDiagnosticsArray
915
+ // component
916
+ const samplingIntervalDiagnosticsArray = serverDiagnosticsNode.getComponentByName("SamplingIntervalDiagnosticsArray");
917
+ if (samplingIntervalDiagnosticsArray) {
918
+ addressSpace.deleteNode(samplingIntervalDiagnosticsArray);
919
+ const s = serverDiagnosticsNode.getComponents();
920
+ }
921
+ const subscriptionDiagnosticsArrayNode = serverDiagnosticsNode.getComponentByName("SubscriptionDiagnosticsArray");
922
+ (0, node_opcua_assert_1.assert)(subscriptionDiagnosticsArrayNode.nodeClass === node_opcua_data_model_1.NodeClass.Variable);
923
+ (0, node_opcua_address_space_1.bindExtObjArrayNode)(subscriptionDiagnosticsArrayNode, "SubscriptionDiagnosticsType", "subscriptionId");
924
+ makeNotReadableIfEnabledFlagIsFalse(subscriptionDiagnosticsArrayNode);
925
+ const sessionsDiagnosticsSummary = serverDiagnosticsNode.getComponentByName("SessionsDiagnosticsSummary");
926
+ const sessionDiagnosticsArray = sessionsDiagnosticsSummary.getComponentByName("SessionDiagnosticsArray");
927
+ (0, node_opcua_assert_1.assert)(sessionDiagnosticsArray.nodeClass === node_opcua_data_model_1.NodeClass.Variable);
928
+ (0, node_opcua_address_space_1.bindExtObjArrayNode)(sessionDiagnosticsArray, "SessionDiagnosticsVariableType", "sessionId");
929
+ const varType = addressSpace.findVariableType("SessionSecurityDiagnosticsType");
930
+ if (!varType) {
931
+ debugLog("Warning cannot find SessionSecurityDiagnosticsType variable Type");
932
+ }
933
+ else {
934
+ const sessionSecurityDiagnosticsArray = sessionsDiagnosticsSummary.getComponentByName("SessionSecurityDiagnosticsArray");
935
+ (0, node_opcua_assert_1.assert)(sessionSecurityDiagnosticsArray.nodeClass === node_opcua_data_model_1.NodeClass.Variable);
936
+ (0, node_opcua_address_space_1.bindExtObjArrayNode)(sessionSecurityDiagnosticsArray, "SessionSecurityDiagnosticsType", "sessionId");
937
+ (0, node_opcua_address_space_1.ensureObjectIsSecure)(sessionSecurityDiagnosticsArray);
938
+ }
939
+ };
940
+ prepareServerDiagnostics();
941
+ this._internalState = "initialized";
942
+ this.setServerState(node_opcua_common_1.ServerState.Running);
943
+ setImmediate(() => callback());
944
+ });
945
+ }
946
+ /**
947
+ *
948
+ * @method browseSingleNode
949
+ * @param nodeId {NodeId|String} : the nodeid of the element to browse
950
+ * @param browseDescription
951
+ * @param browseDescription.browseDirection {BrowseDirection} :
952
+ * @param browseDescription.referenceTypeId {String|NodeId}
953
+ * @param [context]
954
+ * @return the browse result
955
+ */
956
+ browseSingleNode(nodeId, browseDescription, context) {
957
+ const addressSpace = this.addressSpace;
958
+ return addressSpace.browseSingleNode(nodeId, browseDescription, context);
959
+ }
960
+ browseWithAutomaticExpansion(nodesToBrowse, context) {
961
+ return __awaiter(this, void 0, void 0, function* () {
962
+ // do expansion first
963
+ for (const browseDescription of nodesToBrowse) {
964
+ const nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(browseDescription.nodeId);
965
+ const node = this.addressSpace.findNode(nodeId);
966
+ if (node) {
967
+ if (node.onFirstBrowseAction) {
968
+ try {
969
+ yield node.onFirstBrowseAction();
970
+ node.onFirstBrowseAction = undefined;
971
+ }
972
+ catch (err) {
973
+ if (err instanceof Error) {
974
+ errorLog("onFirstBrowseAction method has failed", err.message);
975
+ }
976
+ errorLog(err);
977
+ }
978
+ (0, node_opcua_assert_1.assert)(node.onFirstBrowseAction === undefined, "expansion can only be made once");
979
+ }
980
+ }
981
+ }
982
+ return this.browse(nodesToBrowse, context);
983
+ });
984
+ }
985
+ /**
986
+ *
987
+ */
988
+ browse(nodesToBrowse, context) {
989
+ const results = [];
990
+ for (const browseDescription of nodesToBrowse) {
991
+ const nodeId = (0, node_opcua_nodeid_1.resolveNodeId)(browseDescription.nodeId);
992
+ const r = this.browseSingleNode(nodeId, browseDescription, context);
993
+ results.push(r);
994
+ }
995
+ return results;
996
+ }
997
+ /**
998
+ *
999
+ * @method readSingleNode
1000
+ * @param context
1001
+ * @param nodeId
1002
+ * @param attributeId
1003
+ * @param [timestampsToReturn=TimestampsToReturn.Neither]
1004
+ * @return DataValue
1005
+ */
1006
+ readSingleNode(context, nodeId, attributeId, timestampsToReturn) {
1007
+ context.currentTime = (0, node_opcua_date_time_1.getCurrentClock)();
1008
+ return this._readSingleNode(context, new node_opcua_types_1.ReadValueId({
1009
+ attributeId,
1010
+ nodeId: (0, node_opcua_nodeid_1.resolveNodeId)(nodeId)
1011
+ }), timestampsToReturn);
1012
+ }
1013
+ /**
1014
+ *
1015
+ *
1016
+ * Maximum age of the value to be read in milliseconds. The age of the value is based on the difference between
1017
+ * the ServerTimestamp and the time when the Server starts processing the request. For example if the Client
1018
+ * specifies a maxAge of 500 milliseconds and it takes 100 milliseconds until the Server starts processing
1019
+ * the request, the age of the returned value could be 600 milliseconds prior to the time it was requested.
1020
+ * If the Server has one or more values of an Attribute that are within the maximum age, it can return any one
1021
+ * of the values or it can read a new value from the data source. The number of values of an Attribute that
1022
+ * a Server has depends on the number of MonitoredItems that are defined for the Attribute. In any case,
1023
+ * the Client can make no assumption about which copy of the data will be returned.
1024
+ * If the Server does not have a value that is within the maximum age, it shall attempt to read a new value
1025
+ * from the data source.
1026
+ * If the Server cannot meet the requested maxAge, it returns its 'best effort' value rather than rejecting the
1027
+ * request.
1028
+ * This may occur when the time it takes the Server to process and return the new data value after it has been
1029
+ * accessed is greater than the specified maximum age.
1030
+ * If maxAge is set to 0, the Server shall attempt to read a new value from the data source.
1031
+ * If maxAge is set to the max Int32 value or greater, the Server shall attempt to get a cached value.
1032
+ * Negative values are invalid for maxAge.
1033
+ *
1034
+ * @return an array of DataValue
1035
+ */
1036
+ read(context, readRequest) {
1037
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1038
+ (0, node_opcua_assert_1.assert)(readRequest instanceof node_opcua_service_read_1.ReadRequest);
1039
+ (0, node_opcua_assert_1.assert)(readRequest.maxAge >= 0);
1040
+ const timestampsToReturn = readRequest.timestampsToReturn;
1041
+ const nodesToRead = readRequest.nodesToRead || [];
1042
+ (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRead));
1043
+ context.currentTime = (0, node_opcua_date_time_1.getCurrentClock)();
1044
+ const dataValues = [];
1045
+ for (const readValueId of nodesToRead) {
1046
+ const dataValue = this._readSingleNode(context, readValueId, timestampsToReturn);
1047
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Server) {
1048
+ dataValue.sourceTimestamp = null;
1049
+ dataValue.sourcePicoseconds = 0;
1050
+ }
1051
+ if ((timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Both || timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Server) &&
1052
+ (!dataValue.serverTimestamp || dataValue.serverTimestamp.getTime() === node_opcua_date_time_1.minOPCUADate.getTime())) {
1053
+ dataValue.serverTimestamp = context.currentTime.timestamp;
1054
+ dataValue.sourcePicoseconds = 0; // context.currentTime.picosecond // do we really need picosecond here ? this would inflate binary data
1055
+ }
1056
+ dataValues.push(dataValue);
1057
+ }
1058
+ return dataValues;
1059
+ }
1060
+ /**
1061
+ *
1062
+ * @method writeSingleNode
1063
+ * @param context
1064
+ * @param writeValue
1065
+ * @param callback
1066
+ * @param callback.err
1067
+ * @param callback.statusCode
1068
+ * @async
1069
+ */
1070
+ writeSingleNode(context, writeValue, callback) {
1071
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1072
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
1073
+ (0, node_opcua_assert_1.assert)(writeValue.schema.name === "WriteValue");
1074
+ (0, node_opcua_assert_1.assert)(writeValue.value instanceof node_opcua_data_value_1.DataValue);
1075
+ if (writeValue.value.value === null) {
1076
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadTypeMismatch);
1077
+ }
1078
+ (0, node_opcua_assert_1.assert)(writeValue.value.value instanceof node_opcua_variant_1.Variant);
1079
+ const nodeId = writeValue.nodeId;
1080
+ const obj = this.__findNode(nodeId);
1081
+ if (!obj) {
1082
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown);
1083
+ }
1084
+ else {
1085
+ obj.writeAttribute(context, writeValue, callback);
1086
+ }
1087
+ }
1088
+ /**
1089
+ * write a collection of nodes
1090
+ * @method write
1091
+ * @param context
1092
+ * @param nodesToWrite
1093
+ * @param callback
1094
+ * @param callback.err
1095
+ * @param callback.results
1096
+ * @async
1097
+ */
1098
+ write(context, nodesToWrite, callback) {
1099
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1100
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
1101
+ context.currentTime = (0, node_opcua_date_time_1.getCurrentClock)();
1102
+ (0, node_opcua_address_space_1.ensureDatatypeExtractedWithCallback)(this.addressSpace, (err2, extraDataTypeManager) => {
1103
+ if (err2) {
1104
+ return callback(err2);
1105
+ }
1106
+ const performWrite = (writeValue, inner_callback) => {
1107
+ (0, node_opcua_address_space_1.resolveOpaqueOnAddressSpace)(this.addressSpace, writeValue.value.value)
1108
+ .then(() => {
1109
+ this.writeSingleNode(context, writeValue, inner_callback);
1110
+ })
1111
+ .catch(inner_callback);
1112
+ };
1113
+ // tslint:disable:array-type
1114
+ async.map(nodesToWrite, performWrite, (err, statusCodes) => {
1115
+ (0, node_opcua_assert_1.assert)(Array.isArray(statusCodes));
1116
+ callback(err, statusCodes);
1117
+ });
1118
+ });
1119
+ }
1120
+ /**
1121
+ *
1122
+ */
1123
+ historyReadSingleNode(context, nodeId, attributeId, historyReadDetails, timestampsToReturn, continuationData, callback) {
1124
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1125
+ callback(null, new node_opcua_service_history_1.HistoryReadResult({
1126
+ statusCode: node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid
1127
+ }));
1128
+ return;
1129
+ }
1130
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1131
+ this._historyReadSingleNode(context, new node_opcua_service_history_1.HistoryReadValueId({
1132
+ nodeId
1133
+ }), historyReadDetails, timestampsToReturn, continuationData, callback);
1134
+ }
1135
+ /**
1136
+ *
1137
+ * @method historyRead
1138
+ * @param context {SessionContext}
1139
+ * @param historyReadRequest {HistoryReadRequest}
1140
+ * @param historyReadRequest.requestHeader {RequestHeader}
1141
+ * @param historyReadRequest.historyReadDetails {HistoryReadDetails}
1142
+ * @param historyReadRequest.timestampsToReturn {TimestampsToReturn}
1143
+ * @param historyReadRequest.releaseContinuationPoints {Boolean}
1144
+ * @param historyReadRequest.nodesToRead {HistoryReadValueId[]}
1145
+ * @param callback
1146
+ * @param callback.err
1147
+ * @param callback.results {HistoryReadResult[]}
1148
+ */
1149
+ historyRead(context, historyReadRequest, callback) {
1150
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1151
+ (0, node_opcua_assert_1.assert)(historyReadRequest instanceof node_opcua_service_history_1.HistoryReadRequest);
1152
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
1153
+ const timestampsToReturn = historyReadRequest.timestampsToReturn;
1154
+ const historyReadDetails = historyReadRequest.historyReadDetails;
1155
+ const releaseContinuationPoints = historyReadRequest.releaseContinuationPoints;
1156
+ (0, node_opcua_assert_1.assert)(historyReadDetails instanceof node_opcua_service_history_1.HistoryReadDetails);
1157
+ // ReadAnnotationDataDetails | ReadAtTimeDetails | ReadEventDetails | ReadProcessedDetails | ReadRawModifiedDetails;
1158
+ const nodesToRead = historyReadRequest.nodesToRead || [];
1159
+ (0, node_opcua_assert_1.assert)(Array.isArray(nodesToRead));
1160
+ const _q = (m) => __awaiter(this, void 0, void 0, function* () {
1161
+ return new Promise((resolve) => {
1162
+ const continuationPoint = m.nodeToRead.continuationPoint;
1163
+ this._historyReadSingleNode(context, m.nodeToRead, m.processDetail, timestampsToReturn, { continuationPoint, releaseContinuationPoints /**, index = ??? */ }, (err, result) => {
1164
+ if (err && !result) {
1165
+ errorLog("Internal error", err.message);
1166
+ result = new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
1167
+ }
1168
+ resolve(result);
1169
+ });
1170
+ });
1171
+ });
1172
+ if (historyReadDetails instanceof node_opcua_types_1.ReadProcessedDetails) {
1173
+ //
1174
+ if (!historyReadDetails.aggregateType || historyReadDetails.aggregateType.length !== nodesToRead.length) {
1175
+ return callback(null, [new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInvalidArgument })]);
1176
+ }
1177
+ const promises = [];
1178
+ let index = 0;
1179
+ for (const nodeToRead of nodesToRead) {
1180
+ const aggregateType = historyReadDetails.aggregateType[index];
1181
+ const processDetail = new node_opcua_types_1.ReadProcessedDetails(Object.assign(Object.assign({}, historyReadDetails), { aggregateType: [aggregateType] }));
1182
+ promises.push(_q({ nodeToRead, processDetail, index }));
1183
+ index++;
1184
+ }
1185
+ Promise.all(promises).then((results) => {
1186
+ callback(null, results);
1187
+ });
1188
+ return;
1189
+ }
1190
+ const _r = (nodeToRead, index) => __awaiter(this, void 0, void 0, function* () {
1191
+ const continuationPoint = nodeToRead.continuationPoint;
1192
+ return new Promise((resolve, reject) => {
1193
+ this._historyReadSingleNode(context, nodeToRead, historyReadDetails, timestampsToReturn, { continuationPoint, releaseContinuationPoints, index }, (err, result) => {
1194
+ if (err && !result) {
1195
+ result = new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
1196
+ }
1197
+ resolve(result);
1198
+ // it's not guaranteed that the historical read process is really asynchronous
1199
+ });
1200
+ });
1201
+ });
1202
+ const promises = [];
1203
+ let index = 0;
1204
+ for (const nodeToRead of nodesToRead) {
1205
+ promises.push(_r(nodeToRead, index));
1206
+ index++;
1207
+ }
1208
+ Promise.all(promises).then((results) => {
1209
+ callback(null, results);
1210
+ });
1211
+ }
1212
+ getOldestUnactivatedSession() {
1213
+ const tmp = Object.values(this._sessions).filter((session1) => {
1214
+ return session1.status === "new";
1215
+ });
1216
+ if (tmp.length === 0) {
1217
+ return null;
1218
+ }
1219
+ let session = tmp[0];
1220
+ for (let i = 1; i < tmp.length; i++) {
1221
+ const c = tmp[i];
1222
+ if (session.creationDate.getTime() < c.creationDate.getTime()) {
1223
+ session = c;
1224
+ }
1225
+ }
1226
+ return session;
1227
+ }
1228
+ /**
1229
+ * create a new server session object.
1230
+ * @class ServerEngine
1231
+ * @method createSession
1232
+ * @param [options] {Object}
1233
+ * @param [options.sessionTimeout = 1000] {Number} sessionTimeout
1234
+ * @param [options.clientDescription] {ApplicationDescription}
1235
+ * @return {ServerSession}
1236
+ */
1237
+ createSession(options) {
1238
+ options = options || {};
1239
+ debugLog("createSession : increasing serverDiagnosticsSummary cumulatedSessionCount/currentSessionCount ");
1240
+ this.serverDiagnosticsSummary.cumulatedSessionCount += 1;
1241
+ this.serverDiagnosticsSummary.currentSessionCount += 1;
1242
+ this.clientDescription = options.clientDescription || new node_opcua_service_endpoints_1.ApplicationDescription({});
1243
+ const sessionTimeout = options.sessionTimeout || 1000;
1244
+ (0, node_opcua_assert_1.assert)(typeof sessionTimeout === "number");
1245
+ const session = new server_session_1.ServerSession(this, sessionTimeout);
1246
+ debugLog("createSession :sessionTimeout = ", session.sessionTimeout);
1247
+ const key = session.authenticationToken.toString();
1248
+ this._sessions[key] = session;
1249
+ // see spec OPC Unified Architecture, Part 2 page 26 Release 1.02
1250
+ // TODO : When a Session is created, the Server adds an entry for the Client
1251
+ // in its SessionDiagnosticsArray Variable
1252
+ session.on("new_subscription", (subscription) => {
1253
+ this.serverDiagnosticsSummary.cumulatedSubscriptionCount += 1;
1254
+ // add the subscription diagnostics in our subscriptions diagnostics array
1255
+ // note currentSubscriptionCount is handled directly with a special getter
1256
+ });
1257
+ session.on("subscription_terminated", (subscription) => {
1258
+ // remove the subscription diagnostics in our subscriptions diagnostics array
1259
+ // note currentSubscriptionCount is handled directly with a special getter
1260
+ });
1261
+ // OPC Unified Architecture, Part 4 23 Release 1.03
1262
+ // Sessions are terminated by the Server automatically if the Client fails to issue a Service request on the
1263
+ // Session within the timeout period negotiated by the Server in the CreateSession Service response.
1264
+ // This protects the Server against Client failures and against situations where a failed underlying
1265
+ // connection cannot be re-established. Clients shall be prepared to submit requests in a timely manner
1266
+ // prevent the Session from closing automatically. Clients may explicitly terminate sessions using the
1267
+ // CloseSession Service.
1268
+ session.on("timeout", () => {
1269
+ // the session hasn't been active for a while , probably because the client has disconnected abruptly
1270
+ // it is now time to close the session completely
1271
+ this.serverDiagnosticsSummary.sessionTimeoutCount += 1;
1272
+ session.sessionName = session.sessionName || "";
1273
+ const channel = session.channel;
1274
+ errorLog(chalk.cyan("Server: closing SESSION "), session.status, chalk.yellow(session.sessionName), chalk.yellow(session.nodeId.toString()), chalk.cyan(" because of timeout = "), session.sessionTimeout, chalk.cyan(" has expired without a keep alive"), chalk.bgCyan("channel = "), channel === null || channel === void 0 ? void 0 : channel.remoteAddress, " port = ", channel === null || channel === void 0 ? void 0 : channel.remotePort);
1275
+ // If a Server terminates a Session for any other reason, Subscriptions associated with the Session,
1276
+ // are not deleted. => deleteSubscription= false
1277
+ this.closeSession(session.authenticationToken, /*deleteSubscription=*/ false, /* reason =*/ "Timeout");
1278
+ this.incrementSessionTimeoutCount();
1279
+ });
1280
+ return session;
1281
+ }
1282
+ /**
1283
+ * @method closeSession
1284
+ * @param authenticationToken
1285
+ * @param deleteSubscriptions {Boolean} : true if session's subscription shall be deleted
1286
+ * @param {String} [reason = "CloseSession"] the reason for closing the session (
1287
+ * shall be "Timeout", "Terminated" or "CloseSession")
1288
+ *
1289
+ *
1290
+ * what the specs say:
1291
+ * -------------------
1292
+ *
1293
+ * If a Client invokes the CloseSession Service then all Subscriptions associated with the Session are also deleted
1294
+ * if the deleteSubscriptions flag is set to TRUE. If a Server terminates a Session for any other reason,
1295
+ * Subscriptions associated with the Session, are not deleted. Each Subscription has its own lifetime to protect
1296
+ * against data loss in the case of a Session termination. In these cases, the Subscription can be reassigned to
1297
+ * another Client before its lifetime expires.
1298
+ */
1299
+ closeSession(authenticationToken, deleteSubscriptions, reason) {
1300
+ reason = reason || "CloseSession";
1301
+ (0, node_opcua_assert_1.assert)(typeof reason === "string");
1302
+ (0, node_opcua_assert_1.assert)(reason === "Timeout" || reason === "Terminated" || reason === "CloseSession" || reason === "Forcing");
1303
+ debugLog("ServerEngine.closeSession ", authenticationToken.toString(), deleteSubscriptions);
1304
+ const session = this.getSession(authenticationToken);
1305
+ // istanbul ignore next
1306
+ if (!session) {
1307
+ throw new Error("cannot find session with this authenticationToken " + authenticationToken.toString());
1308
+ }
1309
+ if (!deleteSubscriptions) {
1310
+ // Live Subscriptions will not be deleted, but transferred to the orphanPublishEngine
1311
+ // until they time out or until a other session transfer them back to it.
1312
+ if (!this._orphanPublishEngine) {
1313
+ this._orphanPublishEngine = new server_publish_engine_for_orphan_subscriptions_1.ServerSidePublishEngineForOrphanSubscription({ maxPublishRequestInQueue: 0 });
1314
+ }
1315
+ debugLog("transferring remaining live subscription to orphanPublishEngine !");
1316
+ server_publish_engine_1.ServerSidePublishEngine.transferSubscriptionsToOrphan(session.publishEngine, this._orphanPublishEngine);
1317
+ }
1318
+ session.close(deleteSubscriptions, reason);
1319
+ (0, node_opcua_assert_1.assert)(session.status === "closed");
1320
+ debugLog(" engine.serverDiagnosticsSummary.currentSessionCount -= 1;");
1321
+ this.serverDiagnosticsSummary.currentSessionCount -= 1;
1322
+ // xx //TODO make sure _closedSessions gets cleaned at some point
1323
+ // xx self._closedSessions[key] = session;
1324
+ // remove sessionDiagnostics from server.ServerDiagnostics.SessionsDiagnosticsSummary.SessionDiagnosticsSummary
1325
+ delete this._sessions[authenticationToken.toString()];
1326
+ session.dispose();
1327
+ }
1328
+ findSubscription(subscriptionId) {
1329
+ const subscriptions = [];
1330
+ Object.values(this._sessions).map((session) => {
1331
+ if (subscriptions.length) {
1332
+ return;
1333
+ }
1334
+ const subscription = session.publishEngine.getSubscriptionById(subscriptionId);
1335
+ if (subscription) {
1336
+ subscriptions.push(subscription);
1337
+ }
1338
+ });
1339
+ if (subscriptions.length) {
1340
+ (0, node_opcua_assert_1.assert)(subscriptions.length === 1);
1341
+ return subscriptions[0];
1342
+ }
1343
+ return this.findOrphanSubscription(subscriptionId);
1344
+ }
1345
+ findOrphanSubscription(subscriptionId) {
1346
+ if (!this._orphanPublishEngine) {
1347
+ return null;
1348
+ }
1349
+ return this._orphanPublishEngine.getSubscriptionById(subscriptionId);
1350
+ }
1351
+ deleteOrphanSubscription(subscription) {
1352
+ if (!this._orphanPublishEngine) {
1353
+ return node_opcua_status_code_1.StatusCodes.BadInternalError;
1354
+ }
1355
+ (0, node_opcua_assert_1.assert)(this.findSubscription(subscription.id));
1356
+ const c = this._orphanPublishEngine.subscriptionCount;
1357
+ subscription.terminate();
1358
+ subscription.dispose();
1359
+ (0, node_opcua_assert_1.assert)(this._orphanPublishEngine.subscriptionCount === c - 1);
1360
+ return node_opcua_status_code_1.StatusCodes.Good;
1361
+ }
1362
+ /**
1363
+ * @method transferSubscription
1364
+ * @param session {ServerSession} - the new session that will own the subscription
1365
+ * @param subscriptionId {IntegerId} - the subscription Id to transfer
1366
+ * @param sendInitialValues {Boolean} - true if initial values will be resent.
1367
+ * @return {TransferResult}
1368
+ */
1369
+ transferSubscription(session, subscriptionId, sendInitialValues) {
1370
+ return __awaiter(this, void 0, void 0, function* () {
1371
+ if (subscriptionId <= 0) {
1372
+ return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
1373
+ }
1374
+ const subscription = this.findSubscription(subscriptionId);
1375
+ if (!subscription) {
1376
+ return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid });
1377
+ }
1378
+ // istanbul ignore next
1379
+ if (!subscription.$session) {
1380
+ return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadInternalError });
1381
+ }
1382
+ // check that session have same userIdentity
1383
+ if (!(0, sessions_compatible_for_transfer_1.sessionsCompatibleForTransfer)(subscription.$session, session)) {
1384
+ return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadUserAccessDenied });
1385
+ }
1386
+ // update diagnostics
1387
+ subscription.subscriptionDiagnostics.transferRequestCount++;
1388
+ // now check that new session has sufficient right
1389
+ // if (session.authenticationToken.toString() !== subscription.authenticationToken.toString()) {
1390
+ // console.log("ServerEngine#transferSubscription => BadUserAccessDenied");
1391
+ // return new TransferResult({ statusCode: StatusCodes.BadUserAccessDenied });
1392
+ // }
1393
+ if (session.publishEngine === subscription.publishEngine) {
1394
+ // subscription is already in this session !!
1395
+ return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNothingToDo });
1396
+ }
1397
+ if (session === subscription.$session) {
1398
+ // subscription is already in this session !!
1399
+ return new node_opcua_service_subscription_1.TransferResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNothingToDo });
1400
+ }
1401
+ // The number of times the subscription has been transferred to an alternate client.
1402
+ subscription.subscriptionDiagnostics.transferredToAltClientCount++;
1403
+ // The number of times the subscription has been transferred to an alternate session for the same client.
1404
+ subscription.subscriptionDiagnostics.transferredToSameClientCount++;
1405
+ const nbSubscriptionBefore = session.publishEngine.subscriptionCount;
1406
+ subscription.$session._unexposeSubscriptionDiagnostics(subscription);
1407
+ yield server_publish_engine_1.ServerSidePublishEngine.transferSubscription(subscription, session.publishEngine, sendInitialValues);
1408
+ subscription.$session = session;
1409
+ session._exposeSubscriptionDiagnostics(subscription);
1410
+ (0, node_opcua_assert_1.assert)(subscription.publishEngine === session.publishEngine);
1411
+ // assert(session.publishEngine.subscriptionCount === nbSubscriptionBefore + 1);
1412
+ const result = new node_opcua_service_subscription_1.TransferResult({
1413
+ availableSequenceNumbers: subscription.getAvailableSequenceNumbers(),
1414
+ statusCode: node_opcua_status_code_1.StatusCodes.Good
1415
+ });
1416
+ // istanbul ignore next
1417
+ if (doDebug) {
1418
+ debugLog("TransferResult", result.toString());
1419
+ }
1420
+ return result;
1421
+ });
1422
+ }
1423
+ /**
1424
+ * retrieve a session by its authenticationToken.
1425
+ *
1426
+ * @method getSession
1427
+ * @param authenticationToken
1428
+ * @param activeOnly
1429
+ * @return {ServerSession}
1430
+ */
1431
+ getSession(authenticationToken, activeOnly) {
1432
+ if (!authenticationToken ||
1433
+ (authenticationToken.identifierType && authenticationToken.identifierType !== node_opcua_nodeid_1.NodeIdType.BYTESTRING)) {
1434
+ return null; // wrong type !
1435
+ }
1436
+ const key = authenticationToken.toString();
1437
+ let session = this._sessions[key];
1438
+ if (!activeOnly && !session) {
1439
+ session = this._closedSessions[key];
1440
+ }
1441
+ return session;
1442
+ }
1443
+ /**
1444
+ */
1445
+ browsePath(browsePath) {
1446
+ return this.addressSpace.browsePath(browsePath);
1447
+ }
1448
+ /**
1449
+ *
1450
+ * performs a call to ```asyncRefresh``` on all variable nodes that provide an async refresh func.
1451
+ *
1452
+ * @method refreshValues
1453
+ * @param nodesToRefresh {Array<Object>} an array containing the node to consider
1454
+ * Each element of the array shall be of the form { nodeId: <xxx>, attributeIds: <value> }.
1455
+ * @param callback
1456
+ * @param callback.err
1457
+ * @param callback.data an array containing value read
1458
+ * The array length matches the number of nodeIds that are candidate for an async refresh (i.e: nodes that
1459
+ * are of type Variable with asyncRefresh func }
1460
+ *
1461
+ * @async
1462
+ */
1463
+ refreshValues(nodesToRefresh, maxAge, callback) {
1464
+ const referenceTime = new Date(Date.now() - maxAge);
1465
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
1466
+ const objectMap = {};
1467
+ for (const nodeToRefresh of nodesToRefresh) {
1468
+ // only consider node for which the caller wants to read the Value attribute
1469
+ // assuming that Value is requested if attributeId is missing,
1470
+ if (nodeToRefresh instanceof node_opcua_types_1.ReadValueId && nodeToRefresh.attributeId !== node_opcua_data_model_1.AttributeIds.Value) {
1471
+ continue;
1472
+ }
1473
+ // ... and that are valid object and instances of Variables ...
1474
+ const obj = this.addressSpace.findNode(nodeToRefresh.nodeId);
1475
+ if (!obj || !(obj.nodeClass === node_opcua_data_model_1.NodeClass.Variable)) {
1476
+ continue;
1477
+ }
1478
+ // ... and that have been declared as asynchronously updating
1479
+ if (typeof obj.refreshFunc !== "function") {
1480
+ continue;
1481
+ }
1482
+ const key = obj.nodeId.toString();
1483
+ if (objectMap[key]) {
1484
+ continue;
1485
+ }
1486
+ objectMap[key] = obj;
1487
+ }
1488
+ const objectArray = Object.values(objectMap);
1489
+ if (objectArray.length === 0) {
1490
+ // nothing to do
1491
+ return callback(null, []);
1492
+ }
1493
+ // perform all asyncRefresh in parallel
1494
+ async.map(objectArray, (obj, inner_callback) => {
1495
+ if (obj.nodeClass !== node_opcua_data_model_1.NodeClass.Variable) {
1496
+ inner_callback(null, new node_opcua_data_value_1.DataValue({
1497
+ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeClassInvalid
1498
+ }));
1499
+ return;
1500
+ }
1501
+ try {
1502
+ obj.asyncRefresh(referenceTime, (err, dataValue) => {
1503
+ inner_callback(err, dataValue);
1504
+ });
1505
+ }
1506
+ catch (err) {
1507
+ // istanbul ignore next
1508
+ if (!(err instanceof Error)) {
1509
+ throw new Error("internal error");
1510
+ }
1511
+ errorLog("asyncRefresh internal error", err);
1512
+ inner_callback(err);
1513
+ }
1514
+ }, (err, arrResult) => {
1515
+ callback(err || null, arrResult);
1516
+ });
1517
+ }
1518
+ _exposeSubscriptionDiagnostics(subscription) {
1519
+ debugLog("ServerEngine#_exposeSubscriptionDiagnostics");
1520
+ const subscriptionDiagnosticsArray = this._getServerSubscriptionDiagnosticsArrayNode();
1521
+ const subscriptionDiagnostics = subscription.subscriptionDiagnostics;
1522
+ (0, node_opcua_assert_1.assert)(subscriptionDiagnostics.$subscription === subscription);
1523
+ (0, node_opcua_assert_1.assert)(subscriptionDiagnostics instanceof node_opcua_common_1.SubscriptionDiagnosticsDataType);
1524
+ if (subscriptionDiagnostics && subscriptionDiagnosticsArray) {
1525
+ (0, node_opcua_address_space_1.addElement)(subscriptionDiagnostics, subscriptionDiagnosticsArray);
1526
+ }
1527
+ }
1528
+ _unexposeSubscriptionDiagnostics(subscription) {
1529
+ const subscriptionDiagnosticsArray = this._getServerSubscriptionDiagnosticsArrayNode();
1530
+ const subscriptionDiagnostics = subscription.subscriptionDiagnostics;
1531
+ (0, node_opcua_assert_1.assert)(subscriptionDiagnostics instanceof node_opcua_common_1.SubscriptionDiagnosticsDataType);
1532
+ if (subscriptionDiagnostics && subscriptionDiagnosticsArray) {
1533
+ const node = subscriptionDiagnosticsArray[subscription.id];
1534
+ (0, node_opcua_address_space_1.removeElement)(subscriptionDiagnosticsArray, subscriptionDiagnostics);
1535
+ /*assert(
1536
+ !(subscriptionDiagnosticsArray as any)[subscription.id],
1537
+ " subscription node must have been removed from subscriptionDiagnosticsArray"
1538
+ );
1539
+ */
1540
+ }
1541
+ debugLog("ServerEngine#_unexposeSubscriptionDiagnostics");
1542
+ }
1543
+ /**
1544
+ * create a new subscription
1545
+ * @return {Subscription}
1546
+ */
1547
+ _createSubscriptionOnSession(session, request) {
1548
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "requestedPublishingInterval")); // Duration
1549
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "requestedLifetimeCount")); // Counter
1550
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "requestedMaxKeepAliveCount")); // Counter
1551
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "maxNotificationsPerPublish")); // Counter
1552
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "publishingEnabled")); // Boolean
1553
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "priority")); // Byte
1554
+ // adjust publishing parameters
1555
+ const publishingInterval = request.requestedPublishingInterval || 0;
1556
+ const maxKeepAliveCount = request.requestedMaxKeepAliveCount || 0;
1557
+ const lifeTimeCount = request.requestedLifetimeCount || 0;
1558
+ const subscription = new server_subscription_1.Subscription({
1559
+ id: _get_next_subscriptionId(),
1560
+ lifeTimeCount,
1561
+ maxKeepAliveCount,
1562
+ maxNotificationsPerPublish: request.maxNotificationsPerPublish,
1563
+ priority: request.priority || 0,
1564
+ publishEngine: session.publishEngine,
1565
+ publishingEnabled: request.publishingEnabled,
1566
+ publishingInterval,
1567
+ // -------------------
1568
+ sessionId: node_opcua_nodeid_1.NodeId.nullNodeId,
1569
+ globalCounter: this._globalCounter,
1570
+ serverCapabilities: this.serverCapabilities // shared
1571
+ });
1572
+ // add subscriptionDiagnostics
1573
+ this._exposeSubscriptionDiagnostics(subscription);
1574
+ (0, node_opcua_assert_1.assert)(subscription.publishEngine === session.publishEngine);
1575
+ session.publishEngine.add_subscription(subscription);
1576
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1577
+ const engine = this;
1578
+ subscription.once("terminated", function () {
1579
+ engine._unexposeSubscriptionDiagnostics(this);
1580
+ });
1581
+ return subscription;
1582
+ }
1583
+ __findNode(nodeId) {
1584
+ var _a;
1585
+ if (nodeId.namespace >= (((_a = this.addressSpace) === null || _a === void 0 ? void 0 : _a.getNamespaceArray().length) || 0)) {
1586
+ return null;
1587
+ }
1588
+ const namespace = this.addressSpace.getNamespace(nodeId.namespace);
1589
+ return namespace.findNode2(nodeId);
1590
+ }
1591
+ _readSingleNode(context, nodeToRead, timestampsToReturn) {
1592
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1593
+ const nodeId = nodeToRead.nodeId;
1594
+ const attributeId = nodeToRead.attributeId;
1595
+ const indexRange = nodeToRead.indexRange;
1596
+ const dataEncoding = nodeToRead.dataEncoding;
1597
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1598
+ return new node_opcua_data_value_1.DataValue({ statusCode: node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid });
1599
+ }
1600
+ timestampsToReturn = (0, node_opcua_data_value_1.coerceTimestampsToReturn)(timestampsToReturn);
1601
+ const obj = this.__findNode(nodeId);
1602
+ let dataValue;
1603
+ if (!obj) {
1604
+ // may be return BadNodeIdUnknown in dataValue instead ?
1605
+ // Object Not Found
1606
+ return new node_opcua_data_value_1.DataValue({ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown });
1607
+ }
1608
+ else {
1609
+ // check access
1610
+ // BadUserAccessDenied
1611
+ // BadNotReadable
1612
+ // invalid attributes : BadNodeAttributesInvalid
1613
+ // invalid range : BadIndexRangeInvalid
1614
+ dataValue = obj.readAttribute(context, attributeId, indexRange, dataEncoding);
1615
+ dataValue = (0, node_opcua_data_value_1.apply_timestamps_no_copy)(dataValue, timestampsToReturn, attributeId);
1616
+ return dataValue;
1617
+ }
1618
+ }
1619
+ _historyReadSingleNode(context, nodeToRead, historyReadDetails, timestampsToReturn, continuationData, callback) {
1620
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
1621
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
1622
+ const nodeId = nodeToRead.nodeId;
1623
+ const indexRange = nodeToRead.indexRange;
1624
+ const dataEncoding = nodeToRead.dataEncoding;
1625
+ const continuationPoint = nodeToRead.continuationPoint;
1626
+ timestampsToReturn = (0, node_opcua_data_value_1.coerceTimestampsToReturn)(timestampsToReturn);
1627
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1628
+ return callback(null, new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid }));
1629
+ }
1630
+ const obj = this.__findNode(nodeId);
1631
+ if (!obj) {
1632
+ // may be return BadNodeIdUnknown in dataValue instead ?
1633
+ // Object Not Found
1634
+ callback(null, new node_opcua_service_history_1.HistoryReadResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown }));
1635
+ return;
1636
+ }
1637
+ else {
1638
+ // istanbul ignore next
1639
+ if (!obj.historyRead) {
1640
+ // note : Object and View may also support historyRead to provide Event historical data
1641
+ // todo implement historyRead for Object and View
1642
+ const msg = " this node doesn't provide historyRead! probably not a UAVariable\n " +
1643
+ obj.nodeId.toString() +
1644
+ " " +
1645
+ obj.browseName.toString() +
1646
+ "\n" +
1647
+ "with " +
1648
+ nodeToRead.toString() +
1649
+ "\n" +
1650
+ "HistoryReadDetails " +
1651
+ historyReadDetails.toString();
1652
+ if (doDebug) {
1653
+ debugLog(chalk.cyan("ServerEngine#_historyReadSingleNode "), chalk.white.bold(msg));
1654
+ }
1655
+ const err = new Error(msg);
1656
+ // object has no historyRead method
1657
+ setImmediate(callback.bind(null, err));
1658
+ return;
1659
+ }
1660
+ // check access
1661
+ // BadUserAccessDenied
1662
+ // BadNotReadable
1663
+ // invalid attributes : BadNodeAttributesInvalid
1664
+ // invalid range : BadIndexRangeInvalid
1665
+ obj.historyRead(context, historyReadDetails, indexRange, dataEncoding, continuationData, (err, result) => {
1666
+ if (err || !result) {
1667
+ return callback(err);
1668
+ }
1669
+ (0, node_opcua_assert_1.assert)(result.statusCode instanceof node_opcua_status_code_1.StatusCode);
1670
+ (0, node_opcua_assert_1.assert)(result.isValid());
1671
+ // result = apply_timestamps(result, timestampsToReturn, attributeId);
1672
+ callback(err, result);
1673
+ });
1674
+ }
1675
+ }
1676
+ /**
1677
+ */
1678
+ __internal_bindMethod(nodeId, func) {
1679
+ (0, node_opcua_assert_1.assert)(typeof func === "function");
1680
+ (0, node_opcua_assert_1.assert)(nodeId instanceof node_opcua_nodeid_1.NodeId);
1681
+ const methodNode = this.addressSpace.findNode(nodeId);
1682
+ if (!methodNode) {
1683
+ return;
1684
+ }
1685
+ // istanbul ignore else
1686
+ if (methodNode && methodNode.bindMethod) {
1687
+ methodNode.bindMethod(func);
1688
+ }
1689
+ else {
1690
+ warningLog(chalk.yellow("WARNING: cannot bind a method with id ") +
1691
+ chalk.cyan(nodeId.toString()) +
1692
+ chalk.yellow(". please check your nodeset.xml file or add this node programmatically"));
1693
+ warningLog((0, node_opcua_debug_1.traceFromThisProjectOnly)());
1694
+ }
1695
+ }
1696
+ _getServerSubscriptionDiagnosticsArrayNode() {
1697
+ // istanbul ignore next
1698
+ if (!this.addressSpace) {
1699
+ if (doDebug) {
1700
+ console.warn("ServerEngine#_getServerSubscriptionDiagnosticsArray : no addressSpace");
1701
+ }
1702
+ return null; // no addressSpace
1703
+ }
1704
+ const subscriptionDiagnosticsType = this.addressSpace.findVariableType("SubscriptionDiagnosticsType");
1705
+ if (!subscriptionDiagnosticsType) {
1706
+ if (doDebug) {
1707
+ console.warn("ServerEngine#_getServerSubscriptionDiagnosticsArray " + ": cannot find SubscriptionDiagnosticsType");
1708
+ }
1709
+ }
1710
+ // SubscriptionDiagnosticsArray = i=2290
1711
+ const subscriptionDiagnosticsArrayNode = this.addressSpace.findNode((0, node_opcua_nodeid_1.makeNodeId)(node_opcua_constants_1.VariableIds.Server_ServerDiagnostics_SubscriptionDiagnosticsArray));
1712
+ return subscriptionDiagnosticsArrayNode;
1713
+ }
1714
+ }
1715
+ exports.ServerEngine = ServerEngine;
1716
+ ServerEngine.registry = new node_opcua_object_registry_1.ObjectRegistry();
1689
1717
  //# sourceMappingURL=server_engine.js.map