node-opcua-server 2.98.0 → 2.98.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/base_server.d.ts +110 -0
  2. package/dist/base_server.js +491 -0
  3. package/dist/base_server.js.map +1 -0
  4. package/dist/factory.d.ts +12 -0
  5. package/dist/factory.js +24 -0
  6. package/dist/factory.js.map +1 -0
  7. package/dist/filter/check_where_clause_on_address_space.d.ts +3 -0
  8. package/dist/filter/check_where_clause_on_address_space.js +23 -0
  9. package/dist/filter/check_where_clause_on_address_space.js.map +1 -0
  10. package/dist/filter/extract_event_fields.d.ts +10 -0
  11. package/dist/filter/extract_event_fields.js +18 -0
  12. package/dist/filter/extract_event_fields.js.map +1 -0
  13. package/dist/helper.d.ts +10 -0
  14. package/dist/helper.js +76 -0
  15. package/dist/helper.js.map +1 -0
  16. package/dist/history_server_capabilities.d.ts +35 -0
  17. package/dist/history_server_capabilities.js +44 -0
  18. package/dist/history_server_capabilities.js.map +1 -0
  19. package/dist/i_channel_data.d.ts +13 -0
  20. package/dist/i_channel_data.js +3 -0
  21. package/dist/i_channel_data.js.map +1 -0
  22. package/dist/i_register_server_manager.d.ts +16 -0
  23. package/dist/i_register_server_manager.js +3 -0
  24. package/dist/i_register_server_manager.js.map +1 -0
  25. package/dist/i_server_side_publish_engine.d.ts +36 -0
  26. package/dist/i_server_side_publish_engine.js +50 -0
  27. package/dist/i_server_side_publish_engine.js.map +1 -0
  28. package/dist/i_socket_data.d.ts +11 -0
  29. package/dist/i_socket_data.js +3 -0
  30. package/dist/i_socket_data.js.map +1 -0
  31. package/dist/index.d.ts +16 -0
  32. package/dist/index.js +33 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/monitored_item.d.ts +188 -0
  35. package/dist/monitored_item.js +1113 -0
  36. package/dist/monitored_item.js.map +1 -0
  37. package/dist/node_sampler.d.ts +3 -0
  38. package/dist/node_sampler.js +80 -0
  39. package/dist/node_sampler.js.map +1 -0
  40. package/dist/opcua_server.d.ts +747 -0
  41. package/dist/opcua_server.js +2429 -0
  42. package/dist/opcua_server.js.map +1 -0
  43. package/dist/queue.d.ts +11 -0
  44. package/dist/queue.js +72 -0
  45. package/dist/queue.js.map +1 -0
  46. package/dist/register_server_manager.d.ts +96 -0
  47. package/dist/register_server_manager.js +585 -0
  48. package/dist/register_server_manager.js.map +1 -0
  49. package/dist/register_server_manager_hidden.d.ts +17 -0
  50. package/dist/register_server_manager_hidden.js +28 -0
  51. package/dist/register_server_manager_hidden.js.map +1 -0
  52. package/dist/register_server_manager_mdns_only.d.ts +22 -0
  53. package/dist/register_server_manager_mdns_only.js +56 -0
  54. package/dist/register_server_manager_mdns_only.js.map +1 -0
  55. package/dist/sampling_func.d.ts +3 -0
  56. package/dist/sampling_func.js +3 -0
  57. package/dist/sampling_func.js.map +1 -0
  58. package/dist/server_capabilities.d.ts +148 -0
  59. package/dist/server_capabilities.js +102 -0
  60. package/dist/server_capabilities.js.map +1 -0
  61. package/dist/server_end_point.d.ts +185 -0
  62. package/dist/server_end_point.js +841 -0
  63. package/dist/server_end_point.js.map +1 -0
  64. package/dist/server_engine.d.ts +318 -0
  65. package/dist/server_engine.js +1775 -0
  66. package/dist/server_engine.js.map +1 -0
  67. package/dist/server_publish_engine.d.ts +113 -0
  68. package/dist/server_publish_engine.js +542 -0
  69. package/dist/server_publish_engine.js.map +1 -0
  70. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -0
  71. package/dist/server_publish_engine_for_orphan_subscriptions.js +52 -0
  72. package/dist/server_publish_engine_for_orphan_subscriptions.js.map +1 -0
  73. package/dist/server_session.d.ts +185 -0
  74. package/dist/server_session.js +758 -0
  75. package/dist/server_session.js.map +1 -0
  76. package/dist/server_subscription.d.ts +421 -0
  77. package/dist/server_subscription.js +1348 -0
  78. package/dist/server_subscription.js.map +1 -0
  79. package/dist/sessions_compatible_for_transfer.d.ts +2 -0
  80. package/dist/sessions_compatible_for_transfer.js +40 -0
  81. package/dist/sessions_compatible_for_transfer.js.map +1 -0
  82. package/dist/user_manager.d.ts +32 -0
  83. package/dist/user_manager.js +99 -0
  84. package/dist/user_manager.js.map +1 -0
  85. package/dist/user_manager_ua.d.ts +3 -0
  86. package/dist/user_manager_ua.js +40 -0
  87. package/dist/user_manager_ua.js.map +1 -0
  88. package/dist/validate_filter.d.ts +5 -0
  89. package/dist/validate_filter.js +82 -0
  90. package/dist/validate_filter.js.map +1 -0
  91. package/package.json +51 -47
  92. package/test_helpers/create_certificates.js +0 -1
@@ -0,0 +1,1348 @@
1
+ "use strict";
2
+ /**
3
+ * @module node-opcua-server
4
+ */
5
+ // tslint:disable:no-console
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.Subscription = exports.SubscriptionState = void 0;
17
+ const events_1 = require("events");
18
+ const chalk = require("chalk");
19
+ const node_opcua_address_space_1 = require("node-opcua-address-space");
20
+ const node_opcua_assert_1 = require("node-opcua-assert");
21
+ const node_opcua_common_1 = require("node-opcua-common");
22
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
23
+ const node_opcua_debug_1 = require("node-opcua-debug");
24
+ const node_opcua_nodeid_1 = require("node-opcua-nodeid");
25
+ const node_opcua_object_registry_1 = require("node-opcua-object-registry");
26
+ const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
27
+ const node_opcua_service_filter_1 = require("node-opcua-service-filter");
28
+ const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
29
+ const node_opcua_service_subscription_2 = require("node-opcua-service-subscription");
30
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
31
+ const node_opcua_types_1 = require("node-opcua-types");
32
+ const queue_1 = require("./queue");
33
+ const monitored_item_1 = require("./monitored_item");
34
+ const validate_filter_1 = require("./validate_filter");
35
+ const i_server_side_publish_engine_1 = require("./i_server_side_publish_engine");
36
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
37
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
38
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
39
+ const maxNotificationMessagesInQueue = 100;
40
+ var SubscriptionState;
41
+ (function (SubscriptionState) {
42
+ SubscriptionState[SubscriptionState["CLOSED"] = 1] = "CLOSED";
43
+ SubscriptionState[SubscriptionState["CREATING"] = 2] = "CREATING";
44
+ SubscriptionState[SubscriptionState["NORMAL"] = 3] = "NORMAL";
45
+ // The keep-alive counter is not used in this state.
46
+ SubscriptionState[SubscriptionState["LATE"] = 4] = "LATE";
47
+ // ready to be sent, but there are no Publish requests queued. When in this state, the next Publish
48
+ // request is processed when it is received. The keep-alive counter is not used in this state.
49
+ SubscriptionState[SubscriptionState["KEEPALIVE"] = 5] = "KEEPALIVE";
50
+ // alive counter to count down to 0 from its maximum.
51
+ SubscriptionState[SubscriptionState["TERMINATED"] = 6] = "TERMINATED";
52
+ })(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {}));
53
+ function _adjust_publishing_interval(publishingInterval) {
54
+ publishingInterval =
55
+ publishingInterval === undefined || Number.isNaN(publishingInterval)
56
+ ? Subscription.defaultPublishingInterval
57
+ : publishingInterval;
58
+ publishingInterval = Math.max(publishingInterval, Subscription.minimumPublishingInterval);
59
+ publishingInterval = Math.min(publishingInterval, Subscription.maximumPublishingInterval);
60
+ return publishingInterval;
61
+ }
62
+ const minimumMaxKeepAliveCount = 2;
63
+ const maximumMaxKeepAliveCount = 12000;
64
+ function _adjust_maxKeepAliveCount(maxKeepAliveCount /*,publishingInterval*/) {
65
+ maxKeepAliveCount = maxKeepAliveCount || minimumMaxKeepAliveCount;
66
+ maxKeepAliveCount = Math.max(maxKeepAliveCount, minimumMaxKeepAliveCount);
67
+ maxKeepAliveCount = Math.min(maxKeepAliveCount, maximumMaxKeepAliveCount);
68
+ return maxKeepAliveCount;
69
+ }
70
+ const MaxUint32 = 0xFFFFFFFF;
71
+ function _adjust_lifeTimeCount(lifeTimeCount, maxKeepAliveCount, publishingInterval) {
72
+ lifeTimeCount = lifeTimeCount || 1;
73
+ const minTicks = Math.ceil(Subscription.minimumLifetimeDuration / publishingInterval);
74
+ const maxTicks = Math.floor(Subscription.maximumLifetimeDuration / publishingInterval);
75
+ lifeTimeCount = Math.max(minTicks, lifeTimeCount);
76
+ lifeTimeCount = Math.min(maxTicks, lifeTimeCount);
77
+ // let's make sure that lifeTimeCount is at least three time maxKeepAliveCount
78
+ // Note : the specs say ( part 3 - CreateSubscriptionParameter )
79
+ // "The lifetime count shall be a minimum of three times the keep keep-alive count."
80
+ lifeTimeCount = Math.max(lifeTimeCount, Math.min(maxKeepAliveCount * 3, MaxUint32));
81
+ return lifeTimeCount;
82
+ }
83
+ function _adjust_publishingEnable(publishingEnabled) {
84
+ return publishingEnabled === null || publishingEnabled === undefined ? true : !!publishingEnabled;
85
+ }
86
+ function _adjust_maxNotificationsPerPublish(maxNotificationsPerPublish) {
87
+ (0, node_opcua_assert_1.assert)(Subscription.maxNotificationPerPublishHighLimit > 0, "Subscription.maxNotificationPerPublishHighLimit must be positive");
88
+ maxNotificationsPerPublish = maxNotificationsPerPublish || 0;
89
+ (0, node_opcua_assert_1.assert)(typeof maxNotificationsPerPublish === "number");
90
+ // must be strictly positive
91
+ maxNotificationsPerPublish = maxNotificationsPerPublish >= 0 ? maxNotificationsPerPublish : 0;
92
+ if (maxNotificationsPerPublish === 0) {
93
+ // if zero then => use our HighLimit
94
+ maxNotificationsPerPublish = Subscription.maxNotificationPerPublishHighLimit;
95
+ }
96
+ else {
97
+ // if not zero then should be capped by maxNotificationPerPublishHighLimit
98
+ maxNotificationsPerPublish = Math.min(Subscription.maxNotificationPerPublishHighLimit, maxNotificationsPerPublish);
99
+ }
100
+ (0, node_opcua_assert_1.assert)(maxNotificationsPerPublish !== 0 && maxNotificationsPerPublish <= Subscription.maxNotificationPerPublishHighLimit);
101
+ return maxNotificationsPerPublish;
102
+ }
103
+ function w(s, length) {
104
+ return ("000" + s).padStart(length);
105
+ }
106
+ function t(d) {
107
+ return w(d.getHours(), 2) + ":" + w(d.getMinutes(), 2) + ":" + w(d.getSeconds(), 2) + ":" + w(d.getMilliseconds(), 3);
108
+ }
109
+ function _getSequenceNumbers(arr) {
110
+ return arr.map((notificationMessage) => notificationMessage.sequenceNumber);
111
+ }
112
+ function analyseEventFilterResult(node, eventFilter) {
113
+ /* istanbul ignore next */
114
+ if (!(eventFilter instanceof node_opcua_service_filter_1.EventFilter)) {
115
+ throw new Error("Internal Error");
116
+ }
117
+ const selectClauseResults = (0, node_opcua_service_filter_1.checkSelectClauses)(node, eventFilter.selectClauses || []);
118
+ const whereClauseResult = new node_opcua_types_1.ContentFilterResult();
119
+ return new node_opcua_types_1.EventFilterResult({
120
+ selectClauseDiagnosticInfos: [],
121
+ selectClauseResults,
122
+ whereClauseResult
123
+ });
124
+ }
125
+ function analyseDataChangeFilterResult(node, dataChangeFilter) {
126
+ (0, node_opcua_assert_1.assert)(dataChangeFilter instanceof node_opcua_service_subscription_2.DataChangeFilter);
127
+ // the opcua specification doesn't provide dataChangeFilterResult
128
+ return null;
129
+ }
130
+ function analyseAggregateFilterResult(node, aggregateFilter) {
131
+ (0, node_opcua_assert_1.assert)(aggregateFilter instanceof node_opcua_service_subscription_1.AggregateFilter);
132
+ return new node_opcua_types_1.AggregateFilterResult({});
133
+ }
134
+ function _process_filter(node, filter) {
135
+ if (!filter) {
136
+ return null;
137
+ }
138
+ if (filter instanceof node_opcua_service_filter_1.EventFilter) {
139
+ return analyseEventFilterResult(node, filter);
140
+ }
141
+ else if (filter instanceof node_opcua_service_subscription_2.DataChangeFilter) {
142
+ return analyseDataChangeFilterResult(node, filter);
143
+ }
144
+ else if (filter instanceof node_opcua_service_subscription_1.AggregateFilter) {
145
+ return analyseAggregateFilterResult(node, filter);
146
+ }
147
+ // istanbul ignore next
148
+ throw new Error("invalid filter");
149
+ }
150
+ /**
151
+ * @private
152
+ */
153
+ function createSubscriptionDiagnostics(subscription) {
154
+ (0, node_opcua_assert_1.assert)(subscription instanceof Subscription);
155
+ const subscriptionDiagnostics = new node_opcua_common_1.SubscriptionDiagnosticsDataType({});
156
+ const subscription_subscriptionDiagnostics = subscriptionDiagnostics;
157
+ subscription_subscriptionDiagnostics.$subscription = subscription;
158
+ // "sessionId"
159
+ subscription_subscriptionDiagnostics.__defineGetter__("sessionId", function () {
160
+ if (!this.$subscription) {
161
+ return node_opcua_nodeid_1.NodeId.nullNodeId;
162
+ }
163
+ return this.$subscription.getSessionId();
164
+ });
165
+ subscription_subscriptionDiagnostics.__defineGetter__("subscriptionId", function () {
166
+ if (!this.$subscription) {
167
+ return 0;
168
+ }
169
+ return this.$subscription.id;
170
+ });
171
+ subscription_subscriptionDiagnostics.__defineGetter__("priority", function () {
172
+ if (!this.$subscription) {
173
+ return 0;
174
+ }
175
+ return this.$subscription.priority;
176
+ });
177
+ subscription_subscriptionDiagnostics.__defineGetter__("publishingInterval", function () {
178
+ if (!this.$subscription) {
179
+ return 0;
180
+ }
181
+ return this.$subscription.publishingInterval;
182
+ });
183
+ subscription_subscriptionDiagnostics.__defineGetter__("maxLifetimeCount", function () {
184
+ return this.$subscription.lifeTimeCount;
185
+ });
186
+ subscription_subscriptionDiagnostics.__defineGetter__("maxKeepAliveCount", function () {
187
+ if (!this.$subscription) {
188
+ return 0;
189
+ }
190
+ return this.$subscription.maxKeepAliveCount;
191
+ });
192
+ subscription_subscriptionDiagnostics.__defineGetter__("maxNotificationsPerPublish", function () {
193
+ if (!this.$subscription) {
194
+ return 0;
195
+ }
196
+ return this.$subscription.maxNotificationsPerPublish;
197
+ });
198
+ subscription_subscriptionDiagnostics.__defineGetter__("publishingEnabled", function () {
199
+ if (!this.$subscription) {
200
+ return false;
201
+ }
202
+ return this.$subscription.publishingEnabled;
203
+ });
204
+ subscription_subscriptionDiagnostics.__defineGetter__("monitoredItemCount", function () {
205
+ if (!this.$subscription) {
206
+ return 0;
207
+ }
208
+ return this.$subscription.monitoredItemCount;
209
+ });
210
+ subscription_subscriptionDiagnostics.__defineGetter__("nextSequenceNumber", function () {
211
+ if (!this.$subscription) {
212
+ return 0;
213
+ }
214
+ return this.$subscription._get_future_sequence_number();
215
+ });
216
+ subscription_subscriptionDiagnostics.__defineGetter__("disabledMonitoredItemCount", function () {
217
+ if (!this.$subscription) {
218
+ return 0;
219
+ }
220
+ return this.$subscription.disabledMonitoredItemCount;
221
+ });
222
+ /* those member of self.subscriptionDiagnostics are handled directly
223
+
224
+ modifyCount
225
+ enableCount,
226
+ disableCount,
227
+ republishRequestCount,
228
+ notificationsCount,
229
+ publishRequestCount,
230
+ dataChangeNotificationsCount,
231
+ eventNotificationsCount,
232
+ */
233
+ /*
234
+ those members are not updated yet in the code :
235
+ "republishMessageRequestCount",
236
+ "republishMessageCount",
237
+ "transferRequestCount",
238
+ "transferredToAltClientCount",
239
+ "transferredToSameClientCount",
240
+ "latePublishRequestCount",
241
+ "unacknowledgedMessageCount",
242
+ "discardedMessageCount",
243
+ "monitoringQueueOverflowCount",
244
+ "eventQueueOverFlowCount"
245
+ */
246
+ subscription_subscriptionDiagnostics.__defineGetter__("currentKeepAliveCount", function () {
247
+ if (!this.$subscription) {
248
+ return 0;
249
+ }
250
+ return this.$subscription.currentKeepAliveCount;
251
+ });
252
+ subscription_subscriptionDiagnostics.__defineGetter__("currentLifetimeCount", function () {
253
+ if (!this.$subscription) {
254
+ return 0;
255
+ }
256
+ return this.$subscription.currentLifetimeCount;
257
+ });
258
+ // add object in Variable SubscriptionDiagnosticArray (i=2290) ( Array of SubscriptionDiagnostics)
259
+ // add properties in Variable to reflect
260
+ return subscriptionDiagnostics;
261
+ }
262
+ let g_monitoredItemId = Math.ceil(Math.random() * 100000);
263
+ function getNextMonitoredItemId() {
264
+ return g_monitoredItemId++;
265
+ }
266
+ // function myFilter<T>(t1: any, chunk: any[]): T[] {
267
+ // return chunk.filter(filter_instanceof.bind(null, t1));
268
+ // }
269
+ // function makeNotificationData(notifications_chunk: QueueItem): NotificationData {
270
+ // const dataChangedNotificationData = myFilter<MonitoredItemNotification>(MonitoredItemNotification, notifications_chunk);
271
+ // const eventNotificationListData = myFilter<EventFieldList>(EventFieldList, notifications_chunk);
272
+ // assert(notifications_chunk.length === dataChangedNotificationData.length + eventNotificationListData.length);
273
+ // const notifications: (DataChangeNotification | EventNotificationList)[] = [];
274
+ // // add dataChangeNotification
275
+ // if (dataChangedNotificationData.length) {
276
+ // const dataChangeNotification = new DataChangeNotification({
277
+ // diagnosticInfos: [],
278
+ // monitoredItems: dataChangedNotificationData
279
+ // });
280
+ // notifications.push(dataChangeNotification);
281
+ // }
282
+ // // add dataChangeNotification
283
+ // if (eventNotificationListData.length) {
284
+ // const eventNotificationList = new EventNotificationList({
285
+ // events: eventNotificationListData
286
+ // });
287
+ // notifications.push(eventNotificationList);
288
+ // }
289
+ // return notifications.length === 0 ? null : notifications;
290
+ // }
291
+ const INVALID_ID = -1;
292
+ /**
293
+ * The Subscription class used in the OPCUA server side.
294
+ */
295
+ class Subscription extends events_1.EventEmitter {
296
+ /**
297
+ * @deprecated use serverCapacity.maxMonitoredItems and serverCapacity.maxMonitoredItemsPerSubscription instead
298
+ */
299
+ static get maxMonitoredItemCount() {
300
+ return Subscription.defaultMaxMonitoredItemCount;
301
+ }
302
+ set state(value) {
303
+ if (this._state !== value) {
304
+ this._state = value;
305
+ this.emit("stateChanged", value);
306
+ }
307
+ }
308
+ get state() {
309
+ return this._state;
310
+ }
311
+ get sessionId() {
312
+ return this.$session ? this.$session.nodeId : node_opcua_nodeid_1.NodeId.nullNodeId;
313
+ }
314
+ get currentLifetimeCount() {
315
+ return this._life_time_counter;
316
+ }
317
+ get currentKeepAliveCount() {
318
+ return this._keep_alive_counter;
319
+ }
320
+ constructor(options) {
321
+ super();
322
+ this._state = -1;
323
+ this._keep_alive_counter = 0;
324
+ this._hasUncollectedMonitoredItemNotifications = false;
325
+ options = options || {};
326
+ Subscription.registry.register(this);
327
+ (0, node_opcua_assert_1.assert)(this.sessionId instanceof node_opcua_nodeid_1.NodeId, "expecting a sessionId NodeId");
328
+ this.publishEngine = options.publishEngine;
329
+ this.id = options.id || INVALID_ID;
330
+ this.priority = options.priority || 0;
331
+ this.publishingInterval = _adjust_publishing_interval(options.publishingInterval);
332
+ this.maxKeepAliveCount = _adjust_maxKeepAliveCount(options.maxKeepAliveCount); // , this.publishingInterval);
333
+ this.resetKeepAliveCounter();
334
+ this.lifeTimeCount = _adjust_lifeTimeCount(options.lifeTimeCount || 0, this.maxKeepAliveCount, this.publishingInterval);
335
+ this.maxNotificationsPerPublish = _adjust_maxNotificationsPerPublish(options.maxNotificationsPerPublish);
336
+ this._life_time_counter = 0;
337
+ this.resetLifeTimeCounter();
338
+ // notification message that are ready to be sent to the client
339
+ this._pending_notifications = new queue_1.Queue();
340
+ this._sent_notification_messages = [];
341
+ this._sequence_number_generator = new node_opcua_secure_channel_1.SequenceNumberGenerator();
342
+ // initial state of the subscription
343
+ this.state = SubscriptionState.CREATING;
344
+ this.publishIntervalCount = 0;
345
+ this.monitoredItems = {}; // monitored item map
346
+ this.monitoredItemIdCounter = 0;
347
+ this.publishingEnabled = _adjust_publishingEnable(options.publishingEnabled);
348
+ this.subscriptionDiagnostics = createSubscriptionDiagnostics(this);
349
+ // A boolean value that is set to TRUE to mean that either a NotificationMessage or a keep-alive
350
+ // Message has been sent on the Subscription. It is a flag that is used to ensure that either a
351
+ // NotificationMessage or a keep-alive Message is sent out the first time the publishing
352
+ // timer expires.
353
+ this.messageSent = false;
354
+ this.timerId = null;
355
+ this._start_timer({ firstTime: true });
356
+ debugLog(chalk.green(`creating subscription ${this.id}`));
357
+ this.serverCapabilities = options.serverCapabilities;
358
+ this.serverCapabilities.maxMonitoredItems =
359
+ this.serverCapabilities.maxMonitoredItems || Subscription.defaultMaxMonitoredItemCount;
360
+ this.serverCapabilities.maxMonitoredItemsPerSubscription =
361
+ this.serverCapabilities.maxMonitoredItemsPerSubscription || Subscription.defaultMaxMonitoredItemCount;
362
+ this.globalCounter = options.globalCounter;
363
+ }
364
+ getSessionId() {
365
+ return this.sessionId;
366
+ }
367
+ toString() {
368
+ let str = "Subscription:\n";
369
+ str += " subscriptionId " + this.id + "\n";
370
+ str += " sessionId " + this.getSessionId().toString() + "\n";
371
+ str += " publishingEnabled " + this.publishingEnabled + "\n";
372
+ str += " maxKeepAliveCount " + this.maxKeepAliveCount + "\n";
373
+ str += " publishingInterval " + this.publishingInterval + "\n";
374
+ str += " lifeTimeCount " + this.lifeTimeCount + "\n";
375
+ str += " maxKeepAliveCount " + this.maxKeepAliveCount + "\n";
376
+ return str;
377
+ }
378
+ /**
379
+ * modify subscription parameters
380
+ * @param param
381
+ */
382
+ modify(param) {
383
+ // update diagnostic counter
384
+ this.subscriptionDiagnostics.modifyCount += 1;
385
+ const publishingInterval_old = this.publishingInterval;
386
+ param.requestedPublishingInterval = param.requestedPublishingInterval || 0;
387
+ param.requestedMaxKeepAliveCount = param.requestedMaxKeepAliveCount || this.maxKeepAliveCount;
388
+ param.requestedLifetimeCount = param.requestedLifetimeCount || this.lifeTimeCount;
389
+ this.publishingInterval = _adjust_publishing_interval(param.requestedPublishingInterval);
390
+ this.maxKeepAliveCount = _adjust_maxKeepAliveCount(param.requestedMaxKeepAliveCount);
391
+ this.lifeTimeCount = _adjust_lifeTimeCount(param.requestedLifetimeCount, this.maxKeepAliveCount, this.publishingInterval);
392
+ this.maxNotificationsPerPublish = _adjust_maxNotificationsPerPublish(param.maxNotificationsPerPublish || 0);
393
+ this.priority = param.priority || 0;
394
+ this.resetLifeTimeAndKeepAliveCounters();
395
+ if (publishingInterval_old !== this.publishingInterval) {
396
+ // todo
397
+ }
398
+ this._stop_timer();
399
+ this._start_timer({ firstTime: false });
400
+ }
401
+ /**
402
+ * set publishing mode
403
+ * @param publishingEnabled
404
+ */
405
+ setPublishingMode(publishingEnabled) {
406
+ this.publishingEnabled = !!publishingEnabled;
407
+ // update diagnostics
408
+ if (this.publishingEnabled) {
409
+ this.subscriptionDiagnostics.enableCount += 1;
410
+ }
411
+ else {
412
+ this.subscriptionDiagnostics.disableCount += 1;
413
+ }
414
+ this.resetLifeTimeCounter();
415
+ if (!publishingEnabled && this.state !== SubscriptionState.CLOSED) {
416
+ this.state = SubscriptionState.NORMAL;
417
+ }
418
+ return node_opcua_status_code_1.StatusCodes.Good;
419
+ }
420
+ /**
421
+ * @private
422
+ */
423
+ get keepAliveCounterHasExpired() {
424
+ return this._keep_alive_counter >= this.maxKeepAliveCount || this.state === SubscriptionState.LATE;
425
+ }
426
+ /**
427
+ * Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
428
+ * the CreateSubscription Service( 5.13.2).
429
+ * @private
430
+ */
431
+ resetLifeTimeCounter() {
432
+ this._life_time_counter = 0;
433
+ }
434
+ /**
435
+ * @private
436
+ */
437
+ increaseLifeTimeCounter() {
438
+ this._life_time_counter += 1;
439
+ if (this._life_time_counter >= this.lifeTimeCount) {
440
+ this.emit("lifeTimeExpired");
441
+ }
442
+ this.emit("lifeTimeCounterChanged", this._life_time_counter);
443
+ }
444
+ /**
445
+ * True if the subscription life time has expired.
446
+ *
447
+ */
448
+ get lifeTimeHasExpired() {
449
+ (0, node_opcua_assert_1.assert)(this.lifeTimeCount > 0);
450
+ return this._life_time_counter >= this.lifeTimeCount;
451
+ }
452
+ /**
453
+ * number of milliseconds before this subscription times out (lifeTimeHasExpired === true);
454
+ */
455
+ get timeToExpiration() {
456
+ return (this.lifeTimeCount - this._life_time_counter) * this.publishingInterval;
457
+ }
458
+ get timeToKeepAlive() {
459
+ return (this.maxKeepAliveCount - this._keep_alive_counter) * this.publishingInterval;
460
+ }
461
+ /**
462
+ * Terminates the subscription.
463
+ * Calling this method will also remove any monitored items.
464
+ *
465
+ */
466
+ terminate() {
467
+ (0, node_opcua_assert_1.assert)(arguments.length === 0);
468
+ debugLog("Subscription#terminate status", SubscriptionState[this.state]);
469
+ if (this.state === SubscriptionState.CLOSED) {
470
+ // todo verify if asserting is required here
471
+ return;
472
+ }
473
+ // stop timer
474
+ this._stop_timer();
475
+ debugLog("terminating Subscription ", this.id, " with ", this.monitoredItemCount, " monitored items");
476
+ // dispose all monitoredItem
477
+ const keys = Object.keys(this.monitoredItems);
478
+ for (const key of keys) {
479
+ const status = this.removeMonitoredItem(parseInt(key, 10));
480
+ (0, node_opcua_assert_1.assert)(status === node_opcua_status_code_1.StatusCodes.Good);
481
+ }
482
+ (0, node_opcua_assert_1.assert)(this.monitoredItemCount === 0);
483
+ if (this.$session && this.$session._unexposeSubscriptionDiagnostics) {
484
+ this.$session._unexposeSubscriptionDiagnostics(this);
485
+ }
486
+ this.state = SubscriptionState.CLOSED;
487
+ /**
488
+ * notify the subscription owner that the subscription has been terminated.
489
+ * @event "terminated"
490
+ */
491
+ this.emit("terminated");
492
+ if (this.publishEngine) {
493
+ this.publishEngine.on_close_subscription(this);
494
+ }
495
+ }
496
+ setTriggering(triggeringItemId, linksToAdd, linksToRemove) {
497
+ /** Bad_NothingToDo, Bad_TooManyOperations,Bad_SubscriptionIdInvalid, Bad_MonitoredItemIdInvalid */
498
+ linksToAdd = linksToAdd || [];
499
+ linksToRemove = linksToRemove || [];
500
+ if (linksToAdd.length === 0 && linksToRemove.length === 0) {
501
+ return { statusCode: node_opcua_status_code_1.StatusCodes.BadNothingToDo, addResults: [], removeResults: [] };
502
+ }
503
+ const triggeringItem = this.getMonitoredItem(triggeringItemId);
504
+ const monitoredItemsToAdd = linksToAdd.map((id) => this.getMonitoredItem(id));
505
+ const monitoredItemsToRemove = linksToRemove.map((id) => this.getMonitoredItem(id));
506
+ if (!triggeringItem) {
507
+ const removeResults1 = monitoredItemsToRemove.map((m) => m ? node_opcua_status_code_1.StatusCodes.Good : node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid);
508
+ const addResults1 = monitoredItemsToAdd.map((m) => m ? node_opcua_status_code_1.StatusCodes.Good : node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid);
509
+ return {
510
+ statusCode: node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid,
511
+ addResults: addResults1,
512
+ removeResults: removeResults1
513
+ };
514
+ }
515
+ //
516
+ // note: it seems that CTT imposed that we do remove before add
517
+ const removeResults = monitoredItemsToRemove.map((m) => !m ? node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid : triggeringItem.removeLinkItem(m.monitoredItemId));
518
+ const addResults = monitoredItemsToAdd.map((m) => !m ? node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid : triggeringItem.addLinkItem(m.monitoredItemId));
519
+ const statusCode = node_opcua_status_code_1.StatusCodes.Good;
520
+ // do binding
521
+ return {
522
+ statusCode,
523
+ addResults,
524
+ removeResults
525
+ };
526
+ }
527
+ dispose() {
528
+ if (doDebug) {
529
+ debugLog("Subscription#dispose", this.id, this.monitoredItemCount);
530
+ }
531
+ (0, node_opcua_assert_1.assert)(this.monitoredItemCount === 0, "MonitoredItems haven't been deleted first !!!");
532
+ (0, node_opcua_assert_1.assert)(this.timerId === null, "Subscription timer haven't been terminated");
533
+ if (this.subscriptionDiagnostics) {
534
+ this.subscriptionDiagnostics.$subscription = null;
535
+ }
536
+ this.publishEngine = undefined;
537
+ this._pending_notifications.clear();
538
+ this._sent_notification_messages = [];
539
+ this.$session = undefined;
540
+ this.removeAllListeners();
541
+ Subscription.registry.unregister(this);
542
+ }
543
+ get aborted() {
544
+ const session = this.$session;
545
+ if (!session) {
546
+ return true;
547
+ }
548
+ return session.aborted;
549
+ }
550
+ /**
551
+ * number of pending notifications
552
+ */
553
+ get pendingNotificationsCount() {
554
+ return this._pending_notifications ? this._pending_notifications.size : 0;
555
+ }
556
+ /**
557
+ * is 'true' if there are pending notifications for this subscription. (i.e moreNotifications)
558
+ */
559
+ get hasPendingNotifications() {
560
+ return this.pendingNotificationsCount > 0;
561
+ }
562
+ /**
563
+ * number of sent notifications
564
+ */
565
+ get sentNotificationMessageCount() {
566
+ return this._sent_notification_messages.length;
567
+ }
568
+ /**
569
+ * @internal
570
+ */
571
+ _flushSentNotifications() {
572
+ const tmp = this._sent_notification_messages;
573
+ this._sent_notification_messages = [];
574
+ return tmp;
575
+ }
576
+ /**
577
+ * number of monitored items handled by this subscription
578
+ */
579
+ get monitoredItemCount() {
580
+ return Object.keys(this.monitoredItems).length;
581
+ }
582
+ /**
583
+ * number of disabled monitored items.
584
+ */
585
+ get disabledMonitoredItemCount() {
586
+ return Object.values(this.monitoredItems).reduce((cumul, monitoredItem) => {
587
+ return cumul + (monitoredItem.monitoringMode === node_opcua_service_subscription_2.MonitoringMode.Disabled ? 1 : 0);
588
+ }, 0);
589
+ }
590
+ /**
591
+ * The number of unacknowledged messages saved in the republish queue.
592
+ */
593
+ get unacknowledgedMessageCount() {
594
+ return this.subscriptionDiagnostics.unacknowledgedMessageCount;
595
+ }
596
+ /**
597
+ * adjust monitored item sampling interval
598
+ * - an samplingInterval ===0 means that we use a event-base model ( no sampling)
599
+ * - otherwise the sampling is adjusted
600
+ * @private
601
+ */
602
+ adjustSamplingInterval(samplingInterval, node) {
603
+ if (samplingInterval < 0) {
604
+ // - The value -1 indicates that the default sampling interval defined by the publishing
605
+ // interval of the Subscription is requested.
606
+ // - Any negative number is interpreted as -1.
607
+ samplingInterval = this.publishingInterval;
608
+ }
609
+ else if (samplingInterval === 0) {
610
+ // OPCUA 1.0.3 Part 4 - 5.12.1.2
611
+ // The value 0 indicates that the Server should use the fastest practical rate.
612
+ // The fastest supported sampling interval may be equal to 0, which indicates
613
+ // that the data item is exception-based rather than being sampled at some period.
614
+ // An exception-based model means that the underlying system does not require
615
+ // sampling and reports data changes.
616
+ const dataValueSamplingInterval = node.readAttribute(node_opcua_address_space_1.SessionContext.defaultContext, node_opcua_data_model_1.AttributeIds.MinimumSamplingInterval);
617
+ // TODO if attributeId === AttributeIds.Value : sampling interval required here
618
+ if (dataValueSamplingInterval.statusCode.isGood()) {
619
+ // node provides a Minimum sampling interval ...
620
+ samplingInterval = dataValueSamplingInterval.value.value;
621
+ (0, node_opcua_assert_1.assert)(samplingInterval >= 0 && samplingInterval <= monitored_item_1.MonitoredItem.maximumSamplingInterval);
622
+ // note : at this stage, a samplingInterval===0 means that the data item is really exception-based
623
+ }
624
+ }
625
+ else if (samplingInterval < monitored_item_1.MonitoredItem.minimumSamplingInterval) {
626
+ samplingInterval = monitored_item_1.MonitoredItem.minimumSamplingInterval;
627
+ }
628
+ else if (samplingInterval > monitored_item_1.MonitoredItem.maximumSamplingInterval) {
629
+ // If the requested samplingInterval is higher than the
630
+ // maximum sampling interval supported by the Server, the maximum sampling
631
+ // interval is returned.
632
+ samplingInterval = monitored_item_1.MonitoredItem.maximumSamplingInterval;
633
+ }
634
+ const node_minimumSamplingInterval = node && node.minimumSamplingInterval ? node.minimumSamplingInterval : 0;
635
+ samplingInterval = Math.max(samplingInterval, node_minimumSamplingInterval);
636
+ return samplingInterval;
637
+ }
638
+ /**
639
+ * create a monitored item
640
+ * @param addressSpace - address space
641
+ * @param timestampsToReturn - the timestamp to return
642
+ * @param monitoredItemCreateRequest - the parameters describing the monitored Item to create
643
+ */
644
+ preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest) {
645
+ (0, node_opcua_assert_1.assert)(monitoredItemCreateRequest instanceof node_opcua_service_subscription_2.MonitoredItemCreateRequest);
646
+ function handle_error(statusCode) {
647
+ return {
648
+ createResult: new node_opcua_service_subscription_2.MonitoredItemCreateResult({ statusCode }),
649
+ monitoredItemCreateRequest
650
+ };
651
+ }
652
+ const itemToMonitor = monitoredItemCreateRequest.itemToMonitor;
653
+ const node = addressSpace.findNode(itemToMonitor.nodeId);
654
+ if (!node) {
655
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown);
656
+ }
657
+ if (itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value && !(node.nodeClass === node_opcua_data_model_1.NodeClass.Variable)) {
658
+ // AttributeIds.Value is only valid for monitoring value of UAVariables.
659
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadAttributeIdInvalid);
660
+ }
661
+ if (itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.INVALID) {
662
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadAttributeIdInvalid);
663
+ }
664
+ if (!itemToMonitor.indexRange.isValid()) {
665
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadIndexRangeInvalid);
666
+ }
667
+ // check dataEncoding applies only on Values
668
+ if (itemToMonitor.dataEncoding.name && itemToMonitor.attributeId !== node_opcua_data_model_1.AttributeIds.Value) {
669
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadDataEncodingInvalid);
670
+ }
671
+ // check dataEncoding
672
+ if (!(0, node_opcua_data_model_1.isValidDataEncoding)(itemToMonitor.dataEncoding)) {
673
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadDataEncodingUnsupported);
674
+ }
675
+ // check that item can be read by current user session
676
+ // filter
677
+ const requestedParameters = monitoredItemCreateRequest.requestedParameters;
678
+ const filter = requestedParameters.filter;
679
+ const statusCodeFilter = (0, validate_filter_1.validateFilter)(filter, itemToMonitor, node);
680
+ if (statusCodeFilter !== node_opcua_status_code_1.StatusCodes.Good) {
681
+ return handle_error(statusCodeFilter);
682
+ }
683
+ // do we have enough room for new monitored items ?
684
+ if (this.monitoredItemCount >= this.serverCapabilities.maxMonitoredItemsPerSubscription) {
685
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadTooManyMonitoredItems);
686
+ }
687
+ if (this.globalCounter.totalMonitoredItemCount >= this.serverCapabilities.maxMonitoredItems) {
688
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadTooManyMonitoredItems);
689
+ }
690
+ const createResult = this._createMonitoredItemStep2(timestampsToReturn, monitoredItemCreateRequest, node);
691
+ (0, node_opcua_assert_1.assert)(createResult.statusCode.isGood());
692
+ const monitoredItem = this.getMonitoredItem(createResult.monitoredItemId);
693
+ // istanbul ignore next
694
+ if (!monitoredItem) {
695
+ throw new Error("internal error");
696
+ }
697
+ // TODO: fix old way to set node. !!!!
698
+ monitoredItem.setNode(node);
699
+ this.emit("monitoredItem", monitoredItem, itemToMonitor);
700
+ return { monitoredItem, monitoredItemCreateRequest, createResult };
701
+ }
702
+ applyOnMonitoredItem(functor) {
703
+ return __awaiter(this, void 0, void 0, function* () {
704
+ for (const m of Object.values(this.monitoredItems)) {
705
+ yield functor(m);
706
+ }
707
+ });
708
+ }
709
+ postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult) {
710
+ this._createMonitoredItemStep3(monitoredItem, monitoredItemCreateRequest);
711
+ }
712
+ createMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest) {
713
+ const { monitoredItem, createResult } = this.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
714
+ this.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
715
+ return createResult;
716
+ }
717
+ /**
718
+ * get a monitoredItem by Id.
719
+ * @param monitoredItemId : the id of the monitored item to get.
720
+ * @return the monitored item matching monitoredItemId
721
+ */
722
+ getMonitoredItem(monitoredItemId) {
723
+ return this.monitoredItems[monitoredItemId] || null;
724
+ }
725
+ /**
726
+ * remove a monitored Item from the subscription.
727
+ * @param monitoredItemId : the id of the monitored item to get.
728
+ */
729
+ removeMonitoredItem(monitoredItemId) {
730
+ debugLog("Removing monitoredIem ", monitoredItemId);
731
+ if (!Object.prototype.hasOwnProperty.call(this.monitoredItems, monitoredItemId.toString())) {
732
+ return node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid;
733
+ }
734
+ const monitoredItem = this.monitoredItems[monitoredItemId];
735
+ monitoredItem.terminate();
736
+ monitoredItem.dispose();
737
+ /**
738
+ *
739
+ * notify that a monitored item has been removed from the subscription
740
+ * @param monitoredItem {MonitoredItem}
741
+ */
742
+ this.emit("removeMonitoredItem", monitoredItem);
743
+ delete this.monitoredItems[monitoredItemId];
744
+ this.globalCounter.totalMonitoredItemCount -= 1;
745
+ this._removePendingNotificationsFor(monitoredItemId);
746
+ // flush pending notifications
747
+ // assert(this._pending_notifications.size === 0);
748
+ return node_opcua_status_code_1.StatusCodes.Good;
749
+ }
750
+ /**
751
+ * rue if monitored Item have uncollected Notifications
752
+ */
753
+ get hasUncollectedMonitoredItemNotifications() {
754
+ if (this._hasUncollectedMonitoredItemNotifications) {
755
+ return true;
756
+ }
757
+ const keys = Object.keys(this.monitoredItems);
758
+ const n = keys.length;
759
+ for (let i = 0; i < n; i++) {
760
+ const key = parseInt(keys[i], 10);
761
+ const monitoredItem = this.monitoredItems[key];
762
+ if (monitoredItem.hasMonitoredItemNotifications) {
763
+ this._hasUncollectedMonitoredItemNotifications = true;
764
+ return true;
765
+ }
766
+ }
767
+ return false;
768
+ }
769
+ get subscriptionId() {
770
+ return this.id;
771
+ }
772
+ getMessageForSequenceNumber(sequenceNumber) {
773
+ const notification_message = this._sent_notification_messages.find((e) => e.sequenceNumber === sequenceNumber);
774
+ return notification_message || null;
775
+ }
776
+ /**
777
+ * returns true if the notification has expired
778
+ * @param notification
779
+ */
780
+ notificationHasExpired(notification) {
781
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(notification, "start_tick"));
782
+ (0, node_opcua_assert_1.assert)(isFinite(notification.start_tick + this.maxKeepAliveCount));
783
+ return notification.start_tick + this.maxKeepAliveCount < this.publishIntervalCount;
784
+ }
785
+ /**
786
+ * returns in an array the sequence numbers of the notifications that have been sent
787
+ * and that haven't been acknowledged yet.
788
+ */
789
+ getAvailableSequenceNumbers() {
790
+ const availableSequenceNumbers = _getSequenceNumbers(this._sent_notification_messages);
791
+ return availableSequenceNumbers;
792
+ }
793
+ /**
794
+ * acknowledges a notification identified by its sequence number
795
+ */
796
+ acknowledgeNotification(sequenceNumber) {
797
+ debugLog("acknowledgeNotification ", sequenceNumber);
798
+ let foundIndex = -1;
799
+ this._sent_notification_messages.forEach((e, index) => {
800
+ if (e.sequenceNumber === sequenceNumber) {
801
+ foundIndex = index;
802
+ }
803
+ });
804
+ if (foundIndex === -1) {
805
+ if (doDebug) {
806
+ debugLog(chalk.red("acknowledging sequence FAILED !!! "), chalk.cyan(sequenceNumber.toString()));
807
+ }
808
+ return node_opcua_status_code_1.StatusCodes.BadSequenceNumberUnknown;
809
+ }
810
+ else {
811
+ if (doDebug) {
812
+ debugLog(chalk.yellow("acknowledging sequence "), chalk.cyan(sequenceNumber.toString()));
813
+ }
814
+ this._sent_notification_messages.splice(foundIndex, 1);
815
+ this.subscriptionDiagnostics.unacknowledgedMessageCount--;
816
+ return node_opcua_status_code_1.StatusCodes.Good;
817
+ }
818
+ }
819
+ /**
820
+ * getMonitoredItems is used to get information about monitored items of a subscription.Its intended
821
+ * use is defined in Part 4. This method is the implementation of the Standard OPCUA GetMonitoredItems Method.
822
+ * from spec:
823
+ * This method can be used to get the list of monitored items in a subscription if CreateMonitoredItems
824
+ * failed due to a network interruption and the client does not know if the creation succeeded in the server.
825
+ *
826
+ */
827
+ getMonitoredItems() {
828
+ const monitoredItems = Object.keys(this.monitoredItems);
829
+ const monitoredItemCount = monitoredItems.length;
830
+ const result = {
831
+ clientHandles: new Uint32Array(monitoredItemCount),
832
+ serverHandles: new Uint32Array(monitoredItemCount),
833
+ statusCode: node_opcua_status_code_1.StatusCodes.Good
834
+ };
835
+ for (let index = 0; index < monitoredItemCount; index++) {
836
+ const monitoredItemId = monitoredItems[index];
837
+ const serverHandle = parseInt(monitoredItemId, 10);
838
+ const monitoredItem = this.getMonitoredItem(serverHandle);
839
+ result.clientHandles[index] = monitoredItem.clientHandle;
840
+ // TODO: serverHandle is defined anywhere in the OPCUA Specification 1.02
841
+ // I am not sure what shall be reported for serverHandle...
842
+ // using monitoredItem.monitoredItemId instead...
843
+ // May be a clarification in the OPCUA Spec is required.
844
+ result.serverHandles[index] = serverHandle;
845
+ }
846
+ return result;
847
+ }
848
+ /**
849
+ * @private
850
+ */
851
+ resendInitialValues() {
852
+ return __awaiter(this, void 0, void 0, function* () {
853
+ const promises = [];
854
+ for (const monitoredItem of Object.values(this.monitoredItems)) {
855
+ (0, node_opcua_assert_1.assert)(monitoredItem.clientHandle !== 4294967295);
856
+ promises.push(monitoredItem.resendInitialValues());
857
+ }
858
+ yield Promise.all(promises);
859
+ this._harvestMonitoredItems();
860
+ });
861
+ }
862
+ /**
863
+ * @private
864
+ */
865
+ notifyTransfer() {
866
+ var _a;
867
+ // OPCUA UA Spec 1.0.3 : part 3 - page 82 - 5.13.7 TransferSubscriptions:
868
+ // If the Server transfers the Subscription to the new Session, the Server shall issue
869
+ // a StatusChangeNotification notificationMessage with the status code
870
+ // Good_SubscriptionTransferred to the old Session.
871
+ debugLog(chalk.red(" Subscription => Notifying Transfer "));
872
+ const notificationData = new node_opcua_service_subscription_2.StatusChangeNotification({
873
+ status: node_opcua_status_code_1.StatusCodes.GoodSubscriptionTransferred
874
+ });
875
+ if (this.publishEngine.pendingPublishRequestCount) {
876
+ // the GoodSubscriptionTransferred can be processed immediately
877
+ this._addNotificationMessage(notificationData);
878
+ debugLog(chalk.red("pendingPublishRequestCount"), (_a = this.publishEngine) === null || _a === void 0 ? void 0 : _a.pendingPublishRequestCount);
879
+ this._publish_pending_notifications();
880
+ }
881
+ else {
882
+ debugLog(chalk.red("Cannot send GoodSubscriptionTransferred => lets create a TransferredSubscription "));
883
+ const ts = new i_server_side_publish_engine_1.TransferredSubscription({
884
+ generator: this._sequence_number_generator,
885
+ id: this.id,
886
+ publishEngine: this.publishEngine
887
+ });
888
+ ts._pending_notification = notificationData;
889
+ this.publishEngine._closed_subscriptions.push(ts);
890
+ }
891
+ }
892
+ /**
893
+ *
894
+ * the server invokes the resetLifeTimeAndKeepAliveCounters method of the subscription
895
+ * when the server has send a Publish Response, so that the subscription
896
+ * can reset its life time counter.
897
+ *
898
+ * @private
899
+ */
900
+ resetLifeTimeAndKeepAliveCounters() {
901
+ this.resetLifeTimeCounter();
902
+ this.resetKeepAliveCounter();
903
+ }
904
+ _updateCounters(notificationMessage) {
905
+ for (const notificationData of notificationMessage.notificationData || []) {
906
+ // update diagnostics
907
+ if (notificationData instanceof node_opcua_service_subscription_2.DataChangeNotification) {
908
+ const nbNotifs = notificationData.monitoredItems.length;
909
+ this.subscriptionDiagnostics.dataChangeNotificationsCount += nbNotifs;
910
+ this.subscriptionDiagnostics.notificationsCount += nbNotifs;
911
+ }
912
+ else if (notificationData instanceof node_opcua_service_subscription_2.EventNotificationList) {
913
+ const nbNotifs = notificationData.events.length;
914
+ this.subscriptionDiagnostics.eventNotificationsCount += nbNotifs;
915
+ this.subscriptionDiagnostics.notificationsCount += nbNotifs;
916
+ }
917
+ else {
918
+ (0, node_opcua_assert_1.assert)(notificationData instanceof node_opcua_service_subscription_2.StatusChangeNotification);
919
+ // TODO
920
+ // note: :there is no way to count StatusChangeNotifications in opcua yet.
921
+ }
922
+ }
923
+ }
924
+ /**
925
+ * _publish_pending_notifications send a "notification" event:
926
+ *
927
+ * @private
928
+ * @precondition
929
+ * - pendingPublishRequestCount > 0
930
+ */
931
+ _publish_pending_notifications() {
932
+ var _a;
933
+ const publishEngine = this.publishEngine;
934
+ const subscriptionId = this.id;
935
+ // preconditions
936
+ (0, node_opcua_assert_1.assert)(publishEngine.pendingPublishRequestCount > 0);
937
+ (0, node_opcua_assert_1.assert)(this.hasPendingNotifications);
938
+ const notificationMessage = this._popNotificationToSend();
939
+ if (notificationMessage.notificationData.length === 0) {
940
+ return; // nothing to do
941
+ }
942
+ const moreNotifications = this.hasPendingNotifications;
943
+ this.emit("notification", notificationMessage);
944
+ // Update counters ....
945
+ this._updateCounters(notificationMessage);
946
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(notificationMessage, "sequenceNumber"));
947
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(notificationMessage, "notificationData"));
948
+ // update diagnostics
949
+ this.subscriptionDiagnostics.publishRequestCount += 1;
950
+ const response = new node_opcua_service_subscription_2.PublishResponse({
951
+ moreNotifications,
952
+ notificationMessage: {
953
+ notificationData: notificationMessage.notificationData,
954
+ sequenceNumber: this._get_next_sequence_number()
955
+ },
956
+ subscriptionId
957
+ });
958
+ this._sent_notification_messages.push(response.notificationMessage);
959
+ // get available sequence number;
960
+ const availableSequenceNumbers = this.getAvailableSequenceNumbers();
961
+ (0, node_opcua_assert_1.assert)(!response.notificationMessage ||
962
+ availableSequenceNumbers[availableSequenceNumbers.length - 1] === response.notificationMessage.sequenceNumber);
963
+ response.availableSequenceNumbers = availableSequenceNumbers;
964
+ publishEngine._send_response(this, response);
965
+ this.messageSent = true;
966
+ this.subscriptionDiagnostics.unacknowledgedMessageCount++;
967
+ this.resetLifeTimeAndKeepAliveCounters();
968
+ if (doDebug) {
969
+ debugLog("Subscription sending a notificationMessage subscriptionId=", subscriptionId, "sequenceNumber = ", notificationMessage.sequenceNumber.toString(), (_a = notificationMessage.notificationData) === null || _a === void 0 ? void 0 : _a.map((x) => x === null || x === void 0 ? void 0 : x.constructor.name).join(" "));
970
+ // debugLog(notificationMessage.toString());
971
+ }
972
+ if (this.state !== SubscriptionState.CLOSED) {
973
+ (0, node_opcua_assert_1.assert)(notificationMessage.notificationData.length > 0, "We are not expecting a keep-alive message here");
974
+ this.state = SubscriptionState.NORMAL;
975
+ debugLog("subscription " + this.id + chalk.bgYellow(" set to NORMAL"));
976
+ }
977
+ }
978
+ process_subscription() {
979
+ (0, node_opcua_assert_1.assert)(this.publishEngine.pendingPublishRequestCount > 0);
980
+ if (!this.publishingEnabled) {
981
+ // no publish to do, except keep alive
982
+ debugLog(" -> no publish to do, except keep alive");
983
+ this._process_keepAlive();
984
+ return;
985
+ }
986
+ if (!this.hasPendingNotifications && this.hasUncollectedMonitoredItemNotifications) {
987
+ // collect notification from monitored items
988
+ this._harvestMonitoredItems();
989
+ }
990
+ // let process them first
991
+ if (this.hasPendingNotifications) {
992
+ this._publish_pending_notifications();
993
+ if (this.state === SubscriptionState.NORMAL && this.hasPendingNotifications) {
994
+ // istanbul ignore next
995
+ if (doDebug) {
996
+ debugLog(" -> pendingPublishRequestCount > 0 " + "&& normal state => re-trigger tick event immediately ");
997
+ }
998
+ // let process an new publish request
999
+ setImmediate(this._tick.bind(this));
1000
+ }
1001
+ }
1002
+ else {
1003
+ this._process_keepAlive();
1004
+ }
1005
+ }
1006
+ _get_future_sequence_number() {
1007
+ return this._sequence_number_generator ? this._sequence_number_generator.future() : 0;
1008
+ }
1009
+ _process_keepAlive() {
1010
+ this.increaseKeepAliveCounter();
1011
+ if (this.keepAliveCounterHasExpired) {
1012
+ debugLog(` -> _process_keepAlive => keepAliveCounterHasExpired`);
1013
+ if (this._sendKeepAliveResponse()) {
1014
+ this.resetLifeTimeAndKeepAliveCounters();
1015
+ }
1016
+ else {
1017
+ debugLog(" -> subscription.state === LATE , " +
1018
+ "because keepAlive Response cannot be send due to lack of PublishRequest");
1019
+ if (this.messageSent || this.keepAliveCounterHasExpired) {
1020
+ this.state = SubscriptionState.LATE;
1021
+ }
1022
+ }
1023
+ }
1024
+ }
1025
+ _stop_timer() {
1026
+ if (this.timerId) {
1027
+ debugLog(chalk.bgWhite.blue("Subscription#_stop_timer subscriptionId="), this.id);
1028
+ clearInterval(this.timerId);
1029
+ this.timerId = null;
1030
+ }
1031
+ }
1032
+ _start_timer({ firstTime }) {
1033
+ debugLog(chalk.bgWhite.blue("Subscription#_start_timer subscriptionId="), this.id, " publishingInterval = ", this.publishingInterval);
1034
+ (0, node_opcua_assert_1.assert)(this.timerId === null);
1035
+ // from the spec:
1036
+ // When a Subscription is created, the first Message is sent at the end of the first publishing cycle to
1037
+ // inform the Client that the Subscription is operational. A NotificationMessage is sent if there are
1038
+ // Notifications ready to be reported. If there are none, a keep-alive Message is sent instead that
1039
+ // contains a sequence number of 1, indicating that the first NotificationMessage has not yet been sent.
1040
+ // This is the only time a keep-alive Message is sent without waiting for the maximum keep-alive count
1041
+ // to be reached, as specified in (f) above.
1042
+ // make sure that a keep-alive Message will be send at the end of the first publishing cycle
1043
+ // if there are no Notifications ready.
1044
+ this._keep_alive_counter = 0; // this.maxKeepAliveCount;
1045
+ if (firstTime) {
1046
+ (0, node_opcua_assert_1.assert)(this.messageSent === false);
1047
+ (0, node_opcua_assert_1.assert)(this.state === SubscriptionState.CREATING);
1048
+ }
1049
+ (0, node_opcua_assert_1.assert)(this.publishingInterval >= Subscription.minimumPublishingInterval);
1050
+ this.timerId = setInterval(this._tick.bind(this), this.publishingInterval);
1051
+ }
1052
+ // counter
1053
+ _get_next_sequence_number() {
1054
+ return this._sequence_number_generator ? this._sequence_number_generator.next() : 0;
1055
+ }
1056
+ /**
1057
+ * @private
1058
+ */
1059
+ _tick() {
1060
+ // istanbul ignore next
1061
+ if (doDebug) {
1062
+ debugLog(`Subscription#_tick id ${this.id} aborted=${this.aborted} state=${SubscriptionState[this.state]}`);
1063
+ }
1064
+ if (this.state === SubscriptionState.CLOSED) {
1065
+ warningLog(`Warning: Subscription#_tick id ${this.id} called while subscription is CLOSED`);
1066
+ return;
1067
+ }
1068
+ this.discardOldSentNotifications();
1069
+ // istanbul ignore next
1070
+ if (doDebug) {
1071
+ debugLog(t(new Date()) + " " + this._life_time_counter + "/" + this.lifeTimeCount + chalk.cyan(" Subscription#_tick"), " processing subscriptionId=", this.id, "hasUncollectedMonitoredItemNotifications = ", this.hasUncollectedMonitoredItemNotifications, " publishingIntervalCount =", this.publishIntervalCount);
1072
+ }
1073
+ // give a chance to the publish engine to cancel timed out publish requests
1074
+ this.publishEngine._on_tick();
1075
+ this.publishIntervalCount += 1;
1076
+ if (this.state === SubscriptionState.LATE) {
1077
+ this.increaseLifeTimeCounter();
1078
+ }
1079
+ if (this.lifeTimeHasExpired) {
1080
+ /* istanbul ignore next */
1081
+ doDebug && debugLog(chalk.red.bold(`Subscription ${this.id} has expired !!!!! => Terminating`));
1082
+ /**
1083
+ * notify the subscription owner that the subscription has expired by exceeding its life time.
1084
+ * @event expired
1085
+ *
1086
+ */
1087
+ this.emit("expired");
1088
+ // notify new terminated status only when subscription has timeout.
1089
+ doDebug && debugLog("adding StatusChangeNotification notification message for BadTimeout subscription = ", this.id);
1090
+ this._addNotificationMessage(new node_opcua_service_subscription_2.StatusChangeNotification({ status: node_opcua_status_code_1.StatusCodes.BadTimeout }));
1091
+ // kill timer and delete monitored items and transfer pending notification messages
1092
+ this.terminate();
1093
+ return;
1094
+ }
1095
+ const publishEngine = this.publishEngine;
1096
+ // istanbul ignore next
1097
+ doDebug && debugLog("Subscription#_tick self._pending_notifications= ", this._pending_notifications.size);
1098
+ if (publishEngine.pendingPublishRequestCount === 0 &&
1099
+ (this.hasPendingNotifications || this.hasUncollectedMonitoredItemNotifications)) {
1100
+ // istanbul ignore next
1101
+ doDebug &&
1102
+ debugLog("subscription set to LATE hasPendingNotifications = ", this.hasPendingNotifications, " hasUncollectedMonitoredItemNotifications =", this.hasUncollectedMonitoredItemNotifications);
1103
+ this.state = SubscriptionState.LATE;
1104
+ return;
1105
+ }
1106
+ if (publishEngine.pendingPublishRequestCount > 0) {
1107
+ if (this.hasPendingNotifications) {
1108
+ // simply pop pending notification and send it
1109
+ this.process_subscription();
1110
+ }
1111
+ else if (this.hasUncollectedMonitoredItemNotifications) {
1112
+ this.process_subscription();
1113
+ }
1114
+ else {
1115
+ this._process_keepAlive();
1116
+ }
1117
+ }
1118
+ else {
1119
+ if (this.state !== SubscriptionState.LATE) {
1120
+ this._process_keepAlive();
1121
+ }
1122
+ else {
1123
+ this.resetKeepAliveCounter();
1124
+ }
1125
+ }
1126
+ }
1127
+ /**
1128
+ * @private
1129
+ */
1130
+ _sendKeepAliveResponse() {
1131
+ const future_sequence_number = this._get_future_sequence_number();
1132
+ if (this.publishEngine.send_keep_alive_response(this.id, future_sequence_number)) {
1133
+ this.messageSent = true;
1134
+ // istanbul ignore next
1135
+ doDebug &&
1136
+ debugLog(` -> Subscription#_sendKeepAliveResponse subscriptionId ${this.id} future_sequence_number ${future_sequence_number}`);
1137
+ /**
1138
+ * notify the subscription owner that a keepalive message has to be sent.
1139
+ * @event keepalive
1140
+ *
1141
+ */
1142
+ this.emit("keepalive", future_sequence_number);
1143
+ this.state = SubscriptionState.KEEPALIVE;
1144
+ return true;
1145
+ }
1146
+ return false;
1147
+ }
1148
+ /**
1149
+ * Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
1150
+ * the CreateSubscription Service( 5.13.2).
1151
+ * @private
1152
+ */
1153
+ resetKeepAliveCounter() {
1154
+ this._keep_alive_counter = 0;
1155
+ // istanbul ignore next
1156
+ doDebug &&
1157
+ debugLog(" -> subscriptionId", this.id, " Resetting keepAliveCounter = ", this._keep_alive_counter, this.maxKeepAliveCount);
1158
+ }
1159
+ /**
1160
+ * @private
1161
+ */
1162
+ increaseKeepAliveCounter() {
1163
+ this._keep_alive_counter += 1;
1164
+ // istanbul ignore next
1165
+ doDebug &&
1166
+ debugLog(" -> subscriptionId", this.id, " Increasing keepAliveCounter = ", this._keep_alive_counter, this.maxKeepAliveCount);
1167
+ }
1168
+ /**
1169
+ * @private
1170
+ */
1171
+ _addNotificationMessage(notificationData, monitoredItemId) {
1172
+ // istanbul ignore next
1173
+ doDebug && debugLog(chalk.yellow("Subscription#_addNotificationMessage"), notificationData.toString());
1174
+ this._pending_notifications.push({
1175
+ monitoredItemId,
1176
+ notification: notificationData,
1177
+ publishTime: new Date(),
1178
+ start_tick: this.publishIntervalCount
1179
+ });
1180
+ }
1181
+ /**
1182
+ * @internal
1183
+ * @param monitoredItemId
1184
+ */
1185
+ _removePendingNotificationsFor(monitoredItemId) {
1186
+ const nbRemovedNotification = this._pending_notifications.filterOut((e) => e.monitoredItemId === monitoredItemId);
1187
+ doDebug && debugLog(`Removed ${nbRemovedNotification} notifications`);
1188
+ }
1189
+ /**
1190
+ * Extract the next Notification that is ready to be sent to the client.
1191
+ * @return the Notification to send._pending_notifications
1192
+ */
1193
+ _popNotificationToSend() {
1194
+ (0, node_opcua_assert_1.assert)(this._pending_notifications.size > 0);
1195
+ const notificationMessage = new node_opcua_service_subscription_2.NotificationMessage({
1196
+ sequenceNumber: 0xffffffff,
1197
+ notificationData: [],
1198
+ publishTime: new Date()
1199
+ }); //
1200
+ const dataChangeNotifications = new node_opcua_service_subscription_2.DataChangeNotification({
1201
+ monitoredItems: []
1202
+ });
1203
+ const eventNotificationList = new node_opcua_service_subscription_2.EventNotificationList({
1204
+ events: []
1205
+ });
1206
+ let statusChangeNotification;
1207
+ let i = 0;
1208
+ let hasEventFieldList = 0;
1209
+ let hasMonitoredItemNotification = 0;
1210
+ const m = this.maxNotificationsPerPublish;
1211
+ while (i < m && this._pending_notifications.size > 0) {
1212
+ if (hasEventFieldList || hasMonitoredItemNotification) {
1213
+ const notification1 = this._pending_notifications.first().notification;
1214
+ if (notification1 instanceof node_opcua_service_subscription_2.StatusChangeNotification) {
1215
+ break;
1216
+ }
1217
+ }
1218
+ const notification = this._pending_notifications.shift().notification;
1219
+ if (notification instanceof node_opcua_service_subscription_2.MonitoredItemNotification) {
1220
+ (0, node_opcua_assert_1.assert)(notification.clientHandle !== 4294967295);
1221
+ dataChangeNotifications.monitoredItems.push(notification);
1222
+ hasMonitoredItemNotification = 1;
1223
+ }
1224
+ else if (notification instanceof node_opcua_types_1.EventFieldList) {
1225
+ eventNotificationList.events.push(notification);
1226
+ hasEventFieldList = 1;
1227
+ }
1228
+ else if (notification instanceof node_opcua_service_subscription_2.StatusChangeNotification) {
1229
+ // to do
1230
+ statusChangeNotification = notification;
1231
+ break;
1232
+ }
1233
+ i += 1;
1234
+ }
1235
+ if (dataChangeNotifications.monitoredItems.length) {
1236
+ notificationMessage.notificationData.push(dataChangeNotifications);
1237
+ }
1238
+ if (eventNotificationList.events.length) {
1239
+ notificationMessage.notificationData.push(eventNotificationList);
1240
+ }
1241
+ if (statusChangeNotification) {
1242
+ notificationMessage.notificationData.push(statusChangeNotification);
1243
+ }
1244
+ return notificationMessage;
1245
+ }
1246
+ /**
1247
+ * discardOldSentNotification find all sent notification message that have expired keep-alive
1248
+ * and destroy them.
1249
+ * @private
1250
+ *
1251
+ * Subscriptions maintain a retransmission queue of sent NotificationMessages.
1252
+ * NotificationMessages are retained in this queue until they are acknowledged or until they have
1253
+ * been in the queue for a minimum of one keep-alive interval.
1254
+ *
1255
+ */
1256
+ discardOldSentNotifications() {
1257
+ // Sessions maintain a retransmission queue of sent NotificationMessages. NotificationMessages
1258
+ // are retained in this queue until they are acknowledged. The Session shall maintain a
1259
+ // retransmission queue size of at least two times the number of Publish requests per Session the
1260
+ // Server supports. Clients are required to acknowledge NotificationMessages as they are received. In the
1261
+ // case of a retransmission queue overflow, the oldest sent NotificationMessage gets deleted. If a
1262
+ // Subscription is transferred to another Session, the queued NotificationMessages for this
1263
+ // Subscription are moved from the old to the new Session.
1264
+ if (maxNotificationMessagesInQueue <= this._sent_notification_messages.length) {
1265
+ doDebug && debugLog("discardOldSentNotifications = ", this._sent_notification_messages.length);
1266
+ this._sent_notification_messages.splice(this._sent_notification_messages.length - maxNotificationMessagesInQueue);
1267
+ }
1268
+ }
1269
+ /**
1270
+ * @param timestampsToReturn
1271
+ * @param monitoredItemCreateRequest
1272
+ * @param node
1273
+ * @private
1274
+ */
1275
+ _createMonitoredItemStep2(timestampsToReturn, monitoredItemCreateRequest, node) {
1276
+ // note : most of the parameter inconsistencies shall have been handled by the caller
1277
+ // any error here will raise an assert here
1278
+ (0, node_opcua_assert_1.assert)(monitoredItemCreateRequest instanceof node_opcua_service_subscription_2.MonitoredItemCreateRequest);
1279
+ const itemToMonitor = monitoredItemCreateRequest.itemToMonitor;
1280
+ // xx check if attribute Id invalid (we only support Value or EventNotifier )
1281
+ // xx assert(itemToMonitor.attributeId !== AttributeIds.INVALID);
1282
+ this.monitoredItemIdCounter += 1;
1283
+ const monitoredItemId = getNextMonitoredItemId();
1284
+ const requestedParameters = monitoredItemCreateRequest.requestedParameters;
1285
+ // adjust requestedParameters.samplingInterval
1286
+ requestedParameters.samplingInterval = this.adjustSamplingInterval(requestedParameters.samplingInterval, node);
1287
+ // reincorporate monitoredItemId and itemToMonitor into the requestedParameters
1288
+ const options = requestedParameters;
1289
+ options.monitoredItemId = monitoredItemId;
1290
+ options.itemToMonitor = itemToMonitor;
1291
+ const monitoredItem = new monitored_item_1.MonitoredItem(options);
1292
+ monitoredItem.timestampsToReturn = timestampsToReturn;
1293
+ monitoredItem.$subscription = this;
1294
+ (0, node_opcua_assert_1.assert)(monitoredItem.monitoredItemId === monitoredItemId);
1295
+ this.monitoredItems[monitoredItemId] = monitoredItem;
1296
+ this.globalCounter.totalMonitoredItemCount += 1;
1297
+ (0, node_opcua_assert_1.assert)(monitoredItem.clientHandle !== 4294967295);
1298
+ const filterResult = _process_filter(node, requestedParameters.filter);
1299
+ const monitoredItemCreateResult = new node_opcua_service_subscription_2.MonitoredItemCreateResult({
1300
+ filterResult,
1301
+ monitoredItemId,
1302
+ revisedQueueSize: monitoredItem.queueSize,
1303
+ revisedSamplingInterval: monitoredItem.samplingInterval,
1304
+ statusCode: node_opcua_status_code_1.StatusCodes.Good
1305
+ });
1306
+ // this.emit("monitoredItem", monitoredItem, itemToMonitor);
1307
+ return monitoredItemCreateResult;
1308
+ }
1309
+ /**
1310
+ *
1311
+ * @param monitoredItem
1312
+ * @param monitoredItemCreateRequest
1313
+ * @private
1314
+ */
1315
+ _createMonitoredItemStep3(monitoredItem, monitoredItemCreateRequest) {
1316
+ if (!monitoredItem) {
1317
+ return;
1318
+ }
1319
+ (0, node_opcua_assert_1.assert)(monitoredItem.monitoringMode === node_opcua_service_subscription_2.MonitoringMode.Invalid);
1320
+ (0, node_opcua_assert_1.assert)(typeof monitoredItem.samplingFunc === "function", " expecting a sampling function here");
1321
+ const monitoringMode = monitoredItemCreateRequest.monitoringMode; // Disabled, Sampling, Reporting
1322
+ monitoredItem.setMonitoringMode(monitoringMode);
1323
+ }
1324
+ _harvestMonitoredItems() {
1325
+ for (const monitoredItem of Object.values(this.monitoredItems)) {
1326
+ const notifications_chunks = monitoredItem.extractMonitoredItemNotifications();
1327
+ for (const chunk of notifications_chunks) {
1328
+ this._addNotificationMessage(chunk, monitoredItem.monitoredItemId);
1329
+ }
1330
+ }
1331
+ this._hasUncollectedMonitoredItemNotifications = false;
1332
+ }
1333
+ }
1334
+ Subscription.minimumPublishingInterval = 50; // fastest possible
1335
+ Subscription.defaultPublishingInterval = 1000; // one second
1336
+ Subscription.maximumPublishingInterval = 1000 * 60; // one minute
1337
+ Subscription.maxNotificationPerPublishHighLimit = 1000;
1338
+ Subscription.minimumLifetimeDuration = 5 * 1000; // // we want 2 seconds minimum lifetime for any subscription
1339
+ Subscription.maximumLifetimeDuration = 60 * 60 * 1000; // 1 hour
1340
+ /**
1341
+ * maximum number of monitored item in a subscription to be used
1342
+ * when serverCapacity.maxMonitoredItems and serverCapacity.maxMonitoredItemsPerSubscription are not set.
1343
+ */
1344
+ Subscription.defaultMaxMonitoredItemCount = 20000;
1345
+ Subscription.registry = new node_opcua_object_registry_1.ObjectRegistry();
1346
+ exports.Subscription = Subscription;
1347
+ (0, node_opcua_assert_1.assert)(Subscription.maximumPublishingInterval < 2147483647, "maximumPublishingInterval cannot exceed (2**31-1) ms ");
1348
+ //# sourceMappingURL=server_subscription.js.map