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