node-opcua-server 2.63.1 → 2.64.1

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