node-opcua-server 2.51.0

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