node-opcua-samples 2.113.0 → 2.114.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.
@@ -23,15 +23,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  __setModuleDefault(result, mod);
24
24
  return result;
25
25
  };
26
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
27
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28
- return new (P || (P = Promise))(function (resolve, reject) {
29
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32
- step((generator = generator.apply(thisArg, _arguments || [])).next());
33
- });
34
- };
35
26
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
27
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
28
  };
@@ -54,137 +45,121 @@ const treeify = require("treeify");
54
45
  function w(str, l) {
55
46
  return str.padEnd(l).substring(0, l);
56
47
  }
57
- function enumerateAllConditionTypes(session) {
58
- return __awaiter(this, void 0, void 0, function* () {
59
- const tree = {};
60
- const conditionEventTypes = {};
61
- function findAllNodeOfType(tree1, typeNodeId1, browseName) {
62
- return __awaiter(this, void 0, void 0, function* () {
63
- const browseDesc1 = {
64
- nodeId: typeNodeId1,
65
- referenceTypeId: (0, node_opcua_1.resolveNodeId)("HasSubtype"),
66
- browseDirection: node_opcua_1.BrowseDirection.Forward,
67
- includeSubtypes: true,
68
- resultMask: 63
69
- };
70
- const browseDesc2 = {
71
- nodeId: typeNodeId1,
72
- referenceTypeId: (0, node_opcua_1.resolveNodeId)("HasTypeDefinition"),
73
- browseDirection: node_opcua_1.BrowseDirection.Inverse,
74
- includeSubtypes: true,
75
- resultMask: 63
76
- };
77
- const browseDesc3 = {
78
- nodeId: typeNodeId1,
79
- referenceTypeId: (0, node_opcua_1.resolveNodeId)("HasTypeDefinition"),
80
- browseDirection: node_opcua_1.BrowseDirection.Forward,
81
- includeSubtypes: true,
82
- resultMask: 63
83
- };
84
- const nodesToBrowse = [browseDesc1, browseDesc2, browseDesc3];
85
- const browseResults = yield session.browse(nodesToBrowse);
86
- tree1[browseName] = {};
87
- browseResults[0].references = browseResults[0].references || [];
88
- const promises = [];
89
- for (const reference of browseResults[0].references) {
90
- conditionEventTypes[reference.nodeId.toString()] = reference.browseName.toString();
91
- promises.push(findAllNodeOfType(tree1[browseName], reference.nodeId, reference.browseName.toString()));
92
- }
93
- yield Promise.all(promises);
94
- });
95
- }
96
- const typeNodeId = (0, node_opcua_1.resolveNodeId)("ConditionType");
97
- yield findAllNodeOfType(tree, typeNodeId, "ConditionType");
98
- return tree;
99
- });
100
- }
101
- function enumerateAllAlarmAndConditionInstances(session) {
102
- return __awaiter(this, void 0, void 0, function* () {
103
- const conditions = {};
104
- const found = [];
105
- function isConditionEventType(nodeId) {
106
- return Object.prototype.hasOwnProperty.call(conditions, nodeId.toString());
107
- }
108
- function exploreForObjectOfType(session1, nodeId) {
109
- return __awaiter(this, void 0, void 0, function* () {
110
- function worker(element) {
111
- return __awaiter(this, void 0, void 0, function* () {
112
- const nodeToBrowse = {
113
- nodeId: element.nodeId,
114
- referenceTypeId: (0, node_opcua_1.resolveNodeId)("HierarchicalReferences"),
115
- browseDirection: node_opcua_1.BrowseDirection.Forward,
116
- includeSubtypes: true,
117
- nodeClassMask: 0x1,
118
- resultMask: 63
119
- };
120
- const browseResult = yield session1.browse(nodeToBrowse);
121
- for (const ref of browseResult.references) {
122
- if (isConditionEventType(ref.typeDefinition)) {
123
- //
124
- const alarm = {
125
- parent: element.nodeId,
126
- alarmNodeId: ref.nodeId,
127
- browseName: ref.browseName,
128
- typeDefinition: ref.typeDefinition,
129
- typeDefinitionName: conditions[ref.typeDefinition.toString()]
130
- };
131
- found.push(alarm);
132
- }
133
- else {
134
- yield worker(ref.nodeId);
135
- }
136
- }
137
- });
138
- }
139
- yield worker(nodeId);
140
- });
141
- }
142
- yield enumerateAllConditionTypes(session);
143
- yield exploreForObjectOfType(session, (0, node_opcua_1.resolveNodeId)("RootFolder"));
144
- return Object.values(conditions);
145
- });
146
- }
147
- function _getAllEventTypes(session, baseNodeId, tree) {
148
- return __awaiter(this, void 0, void 0, function* () {
48
+ async function enumerateAllConditionTypes(session) {
49
+ const tree = {};
50
+ const conditionEventTypes = {};
51
+ async function findAllNodeOfType(tree1, typeNodeId1, browseName) {
149
52
  const browseDesc1 = {
150
- nodeId: baseNodeId,
53
+ nodeId: typeNodeId1,
151
54
  referenceTypeId: (0, node_opcua_1.resolveNodeId)("HasSubtype"),
152
55
  browseDirection: node_opcua_1.BrowseDirection.Forward,
153
56
  includeSubtypes: true,
154
- nodeClassMask: node_opcua_1.NodeClassMask.ObjectType,
155
57
  resultMask: 63
156
58
  };
157
- const browseResult = yield session.browse(browseDesc1);
158
- // to do continuation points
159
- for (const reference of browseResult.references) {
160
- const subtree = { nodeId: reference.nodeId.toString() };
161
- tree[reference.browseName.toString()] = subtree;
162
- yield _getAllEventTypes(session, reference.nodeId, subtree);
59
+ const browseDesc2 = {
60
+ nodeId: typeNodeId1,
61
+ referenceTypeId: (0, node_opcua_1.resolveNodeId)("HasTypeDefinition"),
62
+ browseDirection: node_opcua_1.BrowseDirection.Inverse,
63
+ includeSubtypes: true,
64
+ resultMask: 63
65
+ };
66
+ const browseDesc3 = {
67
+ nodeId: typeNodeId1,
68
+ referenceTypeId: (0, node_opcua_1.resolveNodeId)("HasTypeDefinition"),
69
+ browseDirection: node_opcua_1.BrowseDirection.Forward,
70
+ includeSubtypes: true,
71
+ resultMask: 63
72
+ };
73
+ const nodesToBrowse = [browseDesc1, browseDesc2, browseDesc3];
74
+ const browseResults = await session.browse(nodesToBrowse);
75
+ tree1[browseName] = {};
76
+ browseResults[0].references = browseResults[0].references || [];
77
+ const promises = [];
78
+ for (const reference of browseResults[0].references) {
79
+ conditionEventTypes[reference.nodeId.toString()] = reference.browseName.toString();
80
+ promises.push(findAllNodeOfType(tree1[browseName], reference.nodeId, reference.browseName.toString()));
163
81
  }
164
- });
82
+ await Promise.all(promises);
83
+ }
84
+ const typeNodeId = (0, node_opcua_1.resolveNodeId)("ConditionType");
85
+ await findAllNodeOfType(tree, typeNodeId, "ConditionType");
86
+ return tree;
87
+ }
88
+ async function enumerateAllAlarmAndConditionInstances(session) {
89
+ const conditions = {};
90
+ const found = [];
91
+ function isConditionEventType(nodeId) {
92
+ return Object.prototype.hasOwnProperty.call(conditions, nodeId.toString());
93
+ }
94
+ async function exploreForObjectOfType(session1, nodeId) {
95
+ async function worker(element) {
96
+ const nodeToBrowse = {
97
+ nodeId: element.nodeId,
98
+ referenceTypeId: (0, node_opcua_1.resolveNodeId)("HierarchicalReferences"),
99
+ browseDirection: node_opcua_1.BrowseDirection.Forward,
100
+ includeSubtypes: true,
101
+ nodeClassMask: 0x1,
102
+ resultMask: 63
103
+ };
104
+ const browseResult = await session1.browse(nodeToBrowse);
105
+ for (const ref of browseResult.references) {
106
+ if (isConditionEventType(ref.typeDefinition)) {
107
+ //
108
+ const alarm = {
109
+ parent: element.nodeId,
110
+ alarmNodeId: ref.nodeId,
111
+ browseName: ref.browseName,
112
+ typeDefinition: ref.typeDefinition,
113
+ typeDefinitionName: conditions[ref.typeDefinition.toString()]
114
+ };
115
+ found.push(alarm);
116
+ }
117
+ else {
118
+ await worker(ref.nodeId);
119
+ }
120
+ }
121
+ }
122
+ await worker(nodeId);
123
+ }
124
+ await enumerateAllConditionTypes(session);
125
+ await exploreForObjectOfType(session, (0, node_opcua_1.resolveNodeId)("RootFolder"));
126
+ return Object.values(conditions);
127
+ }
128
+ async function _getAllEventTypes(session, baseNodeId, tree) {
129
+ const browseDesc1 = {
130
+ nodeId: baseNodeId,
131
+ referenceTypeId: (0, node_opcua_1.resolveNodeId)("HasSubtype"),
132
+ browseDirection: node_opcua_1.BrowseDirection.Forward,
133
+ includeSubtypes: true,
134
+ nodeClassMask: node_opcua_1.NodeClassMask.ObjectType,
135
+ resultMask: 63
136
+ };
137
+ const browseResult = await session.browse(browseDesc1);
138
+ // to do continuation points
139
+ for (const reference of browseResult.references) {
140
+ const subtree = { nodeId: reference.nodeId.toString() };
141
+ tree[reference.browseName.toString()] = subtree;
142
+ await _getAllEventTypes(session, reference.nodeId, subtree);
143
+ }
165
144
  }
166
145
  /**
167
146
  * getAllEventType recursively
168
147
  */
169
- function getAllEventTypes(session) {
170
- return __awaiter(this, void 0, void 0, function* () {
171
- const baseNodeId = (0, node_opcua_1.makeNodeId)(node_opcua_1.ObjectTypeIds.BaseEventType);
172
- const result = {};
173
- yield _getAllEventTypes(session, baseNodeId, result);
174
- return result;
175
- });
148
+ async function getAllEventTypes(session) {
149
+ const baseNodeId = (0, node_opcua_1.makeNodeId)(node_opcua_1.ObjectTypeIds.BaseEventType);
150
+ const result = {};
151
+ await _getAllEventTypes(session, baseNodeId, result);
152
+ return result;
176
153
  }
177
- function monitorAlarm(subscription, alarmNodeId) {
178
- return __awaiter(this, void 0, void 0, function* () {
179
- try {
180
- yield (0, node_opcua_1.callConditionRefresh)(subscription);
181
- }
182
- catch (err) {
183
- if (util_1.types.isNativeError(err)) {
184
- console.log(" monitorAlarm failed , may be your server doesn't support A&E", err.message);
185
- }
154
+ async function monitorAlarm(subscription, alarmNodeId) {
155
+ try {
156
+ await (0, node_opcua_1.callConditionRefresh)(subscription);
157
+ }
158
+ catch (err) {
159
+ if (util_1.types.isNativeError(err)) {
160
+ console.log(" monitorAlarm failed , may be your server doesn't support A&E", err.message);
186
161
  }
187
- });
162
+ }
188
163
  }
189
164
  function getTick() {
190
165
  return Date.now();
@@ -192,498 +167,496 @@ function getTick() {
192
167
  let theSubscription;
193
168
  let the_session;
194
169
  let client;
195
- function main() {
196
- return __awaiter(this, void 0, void 0, function* () {
197
- // ts-node bin/simple_client.ts --endpoint opc.tcp://localhost:53530/OPCUA/SimulationServer --node "ns=5;s=Sinusoid1"
198
- const argv = yield (0, yargs_1.default)(process.argv)
199
- .wrap(132)
200
- // .usage("Usage: $0 -d --endpoint <endpointUrl> [--securityMode (None|SignAndEncrypt|Sign)] [--securityPolicy (None|Basic256|Basic128Rsa15)] --node <node_id_to_monitor> --crawl")
201
- .option("endpoint", {
202
- alias: "e",
203
- demandOption: true,
204
- describe: "the end point to connect to "
205
- })
206
- .option("securityMode", {
207
- alias: "s",
208
- default: "None",
209
- describe: "the security mode ( None Sign SignAndEncrypt )"
210
- })
211
- .option("securityPolicy", {
212
- alias: "P",
213
- default: "None",
214
- describe: "the policy mode : (" + Object.keys(node_opcua_1.SecurityPolicy).join(" - ") + ")"
215
- })
216
- .option("userName", {
217
- alias: "u",
218
- describe: "specify the user name of a UserNameIdentityToken"
219
- })
220
- .option("password", {
221
- alias: "p",
222
- describe: "specify the password of a UserNameIdentityToken"
223
- })
224
- .option("node", {
225
- alias: "n",
226
- describe: "the nodeId of the value to monitor"
227
- })
228
- .option("timeout", {
229
- alias: "t",
230
- describe: " the timeout of the session in second => (-1 for infinity)"
231
- })
232
- .option("debug", {
233
- alias: "d",
234
- boolean: true,
235
- describe: " display more verbose information"
236
- })
237
- .option("history", {
238
- alias: "h",
239
- describe: "make an historical read"
240
- })
241
- .option("crawl", {
242
- alias: "c",
243
- describe: "crawl"
244
- })
245
- .option("discovery", {
246
- alias: "D",
247
- describe: "specify the endpoint uri of discovery server (by default same as server endpoint uri)"
248
- })
249
- .example("simple_client --endpoint opc.tcp://localhost:49230 -P=Basic256Rsa256 -s=Sign", "")
250
- .example("simple_client -e opc.tcp://localhost:49230 -P=Basic256Sha256 -s=Sign -u JoeDoe -p P@338@rd ", "")
251
- .example('simple_client --endpoint opc.tcp://localhost:49230 -n="ns=0;i=2258"', "").argv;
252
- const securityMode = (0, node_opcua_1.coerceMessageSecurityMode)(argv.securityMode);
253
- if (securityMode === node_opcua_1.MessageSecurityMode.Invalid) {
254
- throw new Error("Invalid Security mode");
255
- }
256
- const securityPolicy = (0, node_opcua_1.coerceSecurityPolicy)(argv.securityPolicy);
257
- if (securityPolicy === node_opcua_1.SecurityPolicy.Invalid) {
258
- throw new Error("Invalid securityPolicy");
259
- }
260
- const timeout = argv.timeout * 1000 || 20000;
261
- const monitored_node = (0, node_opcua_1.coerceNodeId)(argv.node || (0, node_opcua_1.makeNodeId)(node_opcua_1.VariableIds.Server_ServerStatus_CurrentTime));
262
- console.log(chalk_1.default.cyan("securityMode = "), securityMode.toString());
263
- console.log(chalk_1.default.cyan("securityPolicy = "), securityPolicy.toString());
264
- console.log(chalk_1.default.cyan("timeout = "), timeout ? timeout : " Infinity ");
265
- console.log(" monitoring node id = ", monitored_node);
266
- const endpointUrl = argv.endpoint;
267
- if (!endpointUrl) {
268
- yargs_1.default.showHelp();
269
- process.exit(0);
270
- }
271
- const discoveryUrl = argv.discovery ? argv.discovery : endpointUrl;
272
- const doCrawling = !!argv.crawl;
273
- const doHistory = !!argv.history;
274
- const optionsInitial = {
275
- securityMode,
276
- securityPolicy,
277
- endpointMustExist: false,
278
- keepSessionAlive: true,
279
- connectionStrategy: {
280
- initialDelay: 2000,
281
- maxDelay: 10 * 1000,
282
- maxRetry: 10
283
- },
284
- discoveryUrl
285
- };
286
- client = node_opcua_1.OPCUAClient.create(optionsInitial);
287
- client.on("backoff", (retry, delay) => {
288
- console.log(chalk_1.default.bgWhite.yellow("backoff attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
289
- });
290
- console.log(" connecting to ", chalk_1.default.cyan.bold(endpointUrl));
291
- console.log(" strategy", client.connectionStrategy);
292
- try {
293
- yield client.connect(endpointUrl);
294
- console.log(" Connected ! exact endpoint url is ", client.endpointUrl);
295
- }
296
- catch (err) {
297
- console.log(chalk_1.default.red(" Cannot connect to ") + endpointUrl);
298
- if (util_1.types.isNativeError(err)) {
299
- console.log(" Error = ", err.message);
300
- }
301
- return;
170
+ async function main() {
171
+ // ts-node bin/simple_client.ts --endpoint opc.tcp://localhost:53530/OPCUA/SimulationServer --node "ns=5;s=Sinusoid1"
172
+ const argv = await (0, yargs_1.default)(process.argv)
173
+ .wrap(132)
174
+ // .usage("Usage: $0 -d --endpoint <endpointUrl> [--securityMode (None|SignAndEncrypt|Sign)] [--securityPolicy (None|Basic256|Basic128Rsa15)] --node <node_id_to_monitor> --crawl")
175
+ .option("endpoint", {
176
+ alias: "e",
177
+ demandOption: true,
178
+ describe: "the end point to connect to "
179
+ })
180
+ .option("securityMode", {
181
+ alias: "s",
182
+ default: "None",
183
+ describe: "the security mode ( None Sign SignAndEncrypt )"
184
+ })
185
+ .option("securityPolicy", {
186
+ alias: "P",
187
+ default: "None",
188
+ describe: "the policy mode : (" + Object.keys(node_opcua_1.SecurityPolicy).join(" - ") + ")"
189
+ })
190
+ .option("userName", {
191
+ alias: "u",
192
+ describe: "specify the user name of a UserNameIdentityToken"
193
+ })
194
+ .option("password", {
195
+ alias: "p",
196
+ describe: "specify the password of a UserNameIdentityToken"
197
+ })
198
+ .option("node", {
199
+ alias: "n",
200
+ describe: "the nodeId of the value to monitor"
201
+ })
202
+ .option("timeout", {
203
+ alias: "t",
204
+ describe: " the timeout of the session in second => (-1 for infinity)"
205
+ })
206
+ .option("debug", {
207
+ alias: "d",
208
+ boolean: true,
209
+ describe: " display more verbose information"
210
+ })
211
+ .option("history", {
212
+ alias: "h",
213
+ describe: "make an historical read"
214
+ })
215
+ .option("crawl", {
216
+ alias: "c",
217
+ describe: "crawl"
218
+ })
219
+ .option("discovery", {
220
+ alias: "D",
221
+ describe: "specify the endpoint uri of discovery server (by default same as server endpoint uri)"
222
+ })
223
+ .example("simple_client --endpoint opc.tcp://localhost:49230 -P=Basic256Rsa256 -s=Sign", "")
224
+ .example("simple_client -e opc.tcp://localhost:49230 -P=Basic256Sha256 -s=Sign -u JoeDoe -p P@338@rd ", "")
225
+ .example('simple_client --endpoint opc.tcp://localhost:49230 -n="ns=0;i=2258"', "").argv;
226
+ const securityMode = (0, node_opcua_1.coerceMessageSecurityMode)(argv.securityMode);
227
+ if (securityMode === node_opcua_1.MessageSecurityMode.Invalid) {
228
+ throw new Error("Invalid Security mode");
229
+ }
230
+ const securityPolicy = (0, node_opcua_1.coerceSecurityPolicy)(argv.securityPolicy);
231
+ if (securityPolicy === node_opcua_1.SecurityPolicy.Invalid) {
232
+ throw new Error("Invalid securityPolicy");
233
+ }
234
+ const timeout = argv.timeout * 1000 || 20000;
235
+ const monitored_node = (0, node_opcua_1.coerceNodeId)(argv.node || (0, node_opcua_1.makeNodeId)(node_opcua_1.VariableIds.Server_ServerStatus_CurrentTime));
236
+ console.log(chalk_1.default.cyan("securityMode = "), securityMode.toString());
237
+ console.log(chalk_1.default.cyan("securityPolicy = "), securityPolicy.toString());
238
+ console.log(chalk_1.default.cyan("timeout = "), timeout ? timeout : " Infinity ");
239
+ console.log(" monitoring node id = ", monitored_node);
240
+ const endpointUrl = argv.endpoint;
241
+ if (!endpointUrl) {
242
+ yargs_1.default.showHelp();
243
+ process.exit(0);
244
+ }
245
+ const discoveryUrl = argv.discovery ? argv.discovery : endpointUrl;
246
+ const doCrawling = !!argv.crawl;
247
+ const doHistory = !!argv.history;
248
+ const optionsInitial = {
249
+ securityMode,
250
+ securityPolicy,
251
+ endpointMustExist: false,
252
+ keepSessionAlive: true,
253
+ connectionStrategy: {
254
+ initialDelay: 2000,
255
+ maxDelay: 10 * 1000,
256
+ maxRetry: 10
257
+ },
258
+ discoveryUrl
259
+ };
260
+ client = node_opcua_1.OPCUAClient.create(optionsInitial);
261
+ client.on("backoff", (retry, delay) => {
262
+ console.log(chalk_1.default.bgWhite.yellow("backoff attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
263
+ });
264
+ console.log(" connecting to ", chalk_1.default.cyan.bold(endpointUrl));
265
+ console.log(" strategy", client.connectionStrategy);
266
+ try {
267
+ await client.connect(endpointUrl);
268
+ console.log(" Connected ! exact endpoint url is ", client.endpointUrl);
269
+ }
270
+ catch (err) {
271
+ console.log(chalk_1.default.red(" Cannot connect to ") + endpointUrl);
272
+ if (util_1.types.isNativeError(err)) {
273
+ console.log(" Error = ", err.message);
302
274
  }
303
- const endpoints = yield client.getEndpoints();
304
- if (argv.debug) {
305
- fs.writeFileSync("tmp/endpoints.log", JSON.stringify(endpoints, null, " "));
306
- console.log(treeify.asTree(endpoints, true));
275
+ return;
276
+ }
277
+ const endpoints = await client.getEndpoints();
278
+ if (argv.debug) {
279
+ fs.writeFileSync("tmp/endpoints.log", JSON.stringify(endpoints, null, " "));
280
+ console.log(treeify.asTree(endpoints, true));
281
+ }
282
+ const table = new Table();
283
+ let serverCertificate;
284
+ let i = 0;
285
+ for (const endpoint of endpoints) {
286
+ table.cell("endpoint", endpoint.endpointUrl + "");
287
+ table.cell("Application URI", endpoint.server.applicationUri);
288
+ table.cell("Product URI", endpoint.server.productUri);
289
+ table.cell("Application Name", endpoint.server.applicationName.text);
290
+ table.cell("Security Mode", node_opcua_1.MessageSecurityMode[endpoint.securityMode].toString());
291
+ table.cell("securityPolicyUri", endpoint.securityPolicyUri);
292
+ table.cell("Type", node_opcua_1.ApplicationType[endpoint.server.applicationType]);
293
+ table.cell("certificate", "..." /*endpoint.serverCertificate*/);
294
+ endpoint.server.discoveryUrls = endpoint.server.discoveryUrls || [];
295
+ table.cell("discoveryUrls", endpoint.server.discoveryUrls.join(" - "));
296
+ serverCertificate = endpoint.serverCertificate;
297
+ const certificate_filename = path.join(__dirname, "../certificates/PKI/server_certificate" + i + ".pem");
298
+ if (serverCertificate) {
299
+ fs.writeFile(certificate_filename, (0, node_opcua_crypto_1.toPem)(serverCertificate, "CERTIFICATE"), () => {
300
+ /**/
301
+ });
307
302
  }
308
- const table = new Table();
309
- let serverCertificate;
310
- let i = 0;
311
- for (const endpoint of endpoints) {
312
- table.cell("endpoint", endpoint.endpointUrl + "");
313
- table.cell("Application URI", endpoint.server.applicationUri);
314
- table.cell("Product URI", endpoint.server.productUri);
315
- table.cell("Application Name", endpoint.server.applicationName.text);
316
- table.cell("Security Mode", node_opcua_1.MessageSecurityMode[endpoint.securityMode].toString());
317
- table.cell("securityPolicyUri", endpoint.securityPolicyUri);
318
- table.cell("Type", node_opcua_1.ApplicationType[endpoint.server.applicationType]);
319
- table.cell("certificate", "..." /*endpoint.serverCertificate*/);
320
- endpoint.server.discoveryUrls = endpoint.server.discoveryUrls || [];
321
- table.cell("discoveryUrls", endpoint.server.discoveryUrls.join(" - "));
322
- serverCertificate = endpoint.serverCertificate;
323
- const certificate_filename = path.join(__dirname, "../certificates/PKI/server_certificate" + i + ".pem");
324
- if (serverCertificate) {
325
- fs.writeFile(certificate_filename, (0, node_opcua_crypto_1.toPem)(serverCertificate, "CERTIFICATE"), () => {
326
- /**/
327
- });
328
- }
329
- table.newRow();
330
- i++;
303
+ table.newRow();
304
+ i++;
305
+ }
306
+ console.log(table.toString());
307
+ for (const endpoint of endpoints) {
308
+ console.log("Identify Token for : Security Mode=", endpoint.securityMode.toString(), " Policy=", endpoint.securityPolicyUri);
309
+ const table2 = new Table();
310
+ for (const token of endpoint.userIdentityTokens) {
311
+ table2.cell("policyId", token.policyId);
312
+ table2.cell("tokenType", token.tokenType.toString());
313
+ table2.cell("issuedTokenType", token.issuedTokenType);
314
+ table2.cell("issuerEndpointUrl", token.issuerEndpointUrl);
315
+ table2.cell("securityPolicyUri", token.securityPolicyUri);
316
+ table2.newRow();
331
317
  }
332
- console.log(table.toString());
333
- for (const endpoint of endpoints) {
334
- console.log("Identify Token for : Security Mode=", endpoint.securityMode.toString(), " Policy=", endpoint.securityPolicyUri);
335
- const table2 = new Table();
336
- for (const token of endpoint.userIdentityTokens) {
337
- table2.cell("policyId", token.policyId);
338
- table2.cell("tokenType", token.tokenType.toString());
339
- table2.cell("issuedTokenType", token.issuedTokenType);
340
- table2.cell("issuerEndpointUrl", token.issuerEndpointUrl);
341
- table2.cell("securityPolicyUri", token.securityPolicyUri);
342
- table2.newRow();
343
- }
344
- console.log(table2.toString());
318
+ console.log(table2.toString());
319
+ }
320
+ await client.disconnect();
321
+ // reconnect using the correct end point URL now
322
+ console.log(chalk_1.default.cyan("Server Certificate :"));
323
+ console.log(chalk_1.default.yellow((0, node_opcua_1.hexDump)(serverCertificate)));
324
+ console.log(" adjusted endpoint Url =", client.endpointUrl);
325
+ const adjustedEndpointUrl = client.endpointUrl;
326
+ const options = {
327
+ securityMode,
328
+ securityPolicy,
329
+ // we specify here server certificate
330
+ serverCertificate,
331
+ defaultSecureTokenLifetime: 40000,
332
+ endpointMustExist: false,
333
+ connectionStrategy: {
334
+ initialDelay: 2000,
335
+ maxDelay: 10 * 1000,
336
+ maxRetry: 10
345
337
  }
346
- yield client.disconnect();
347
- // reconnect using the correct end point URL now
348
- console.log(chalk_1.default.cyan("Server Certificate :"));
349
- console.log(chalk_1.default.yellow((0, node_opcua_1.hexDump)(serverCertificate)));
350
- console.log(" adjusted endpoint Url =", client.endpointUrl);
351
- const adjustedEndpointUrl = client.endpointUrl;
352
- const options = {
353
- securityMode,
354
- securityPolicy,
355
- // we specify here server certificate
356
- serverCertificate,
357
- defaultSecureTokenLifetime: 40000,
358
- endpointMustExist: false,
359
- connectionStrategy: {
360
- initialDelay: 2000,
361
- maxDelay: 10 * 1000,
362
- maxRetry: 10
363
- }
338
+ };
339
+ console.log("Options = ", options.securityMode.toString(), options.securityPolicy.toString());
340
+ client = node_opcua_1.OPCUAClient.create(options);
341
+ console.log(" --------------------------------- Now connecting again to ", chalk_1.default.cyan.bold(adjustedEndpointUrl));
342
+ await client.connect(adjustedEndpointUrl);
343
+ console.log(" Connected ! exact endpoint url is ", client.endpointUrl);
344
+ let userIdentity = { type: node_opcua_1.UserTokenType.Anonymous }; // anonymous
345
+ if (argv.userName && argv.password) {
346
+ userIdentity = {
347
+ type: node_opcua_1.UserTokenType.UserName,
348
+ password: argv.password,
349
+ userName: argv.userName
364
350
  };
365
- console.log("Options = ", options.securityMode.toString(), options.securityPolicy.toString());
366
- client = node_opcua_1.OPCUAClient.create(options);
367
- console.log(" --------------------------------- Now connecting again to ", chalk_1.default.cyan.bold(adjustedEndpointUrl));
368
- yield client.connect(adjustedEndpointUrl);
369
- console.log(" Connected ! exact endpoint url is ", client.endpointUrl);
370
- let userIdentity = { type: node_opcua_1.UserTokenType.Anonymous }; // anonymous
371
- if (argv.userName && argv.password) {
372
- userIdentity = {
373
- type: node_opcua_1.UserTokenType.UserName,
374
- password: argv.password,
375
- userName: argv.userName
376
- };
377
- }
378
- console.log(" now creating Session !");
379
- the_session = yield client.createSession(userIdentity);
380
- client.on("connection_reestablished", () => {
381
- console.log(chalk_1.default.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!! CONNECTION RE-ESTABLISHED !!!!!!!!!!!!!!!!!!!"));
382
- });
383
- console.log(chalk_1.default.yellow(" session created"));
384
- console.log(" sessionId : ", the_session.sessionId.toString());
385
- client.on("backoff", (retry, delay) => {
386
- console.log(chalk_1.default.bgWhite.yellow("backoff attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
387
- });
388
- client.on("start_reconnection", () => {
389
- console.log(chalk_1.default.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!! Starting Reconnection !!!!!!!!!!!!!!!!!!!"));
351
+ }
352
+ console.log(" now creating Session !");
353
+ the_session = await client.createSession(userIdentity);
354
+ client.on("connection_reestablished", () => {
355
+ console.log(chalk_1.default.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!! CONNECTION RE-ESTABLISHED !!!!!!!!!!!!!!!!!!!"));
356
+ });
357
+ console.log(chalk_1.default.yellow(" session created"));
358
+ console.log(" sessionId : ", the_session.sessionId.toString());
359
+ client.on("backoff", (retry, delay) => {
360
+ console.log(chalk_1.default.bgWhite.yellow("backoff attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
361
+ });
362
+ client.on("start_reconnection", () => {
363
+ console.log(chalk_1.default.bgWhite.red(" !!!!!!!!!!!!!!!!!!!!!!!! Starting Reconnection !!!!!!!!!!!!!!!!!!!"));
364
+ });
365
+ // -----------------------------------------------------------------------------------------------------------
366
+ // NAMESPACE
367
+ // display namespace array
368
+ // -----------------------------------------------------------------------------------------------------------
369
+ const server_NamespaceArray_Id = (0, node_opcua_1.makeNodeId)(node_opcua_1.VariableIds.Server_NamespaceArray); // ns=0;i=2006
370
+ const dataValue = await the_session.readVariableValue(server_NamespaceArray_Id);
371
+ console.log(" --- NAMESPACE ARRAY ---");
372
+ const namespaceArray = dataValue.value.value;
373
+ for (const namespace of namespaceArray) {
374
+ console.log(" Namespace ", namespace.index, " : ", namespace);
375
+ }
376
+ console.log(" -----------------------");
377
+ // -----------------------------------------------------------------------------------------------------------
378
+ // enumerate all EVENT TYPES
379
+ // -----------------------------------------------------------------------------------------------------------
380
+ const result = getAllEventTypes(the_session);
381
+ console.log(chalk_1.default.cyan("---------------------------------------------------- All Event Types "));
382
+ console.log(treeify.asTree(result, true));
383
+ console.log(" -----------------------");
384
+ // -----------------------------------------------------------------------------------------------------------
385
+ // Node Crawling
386
+ // -----------------------------------------------------------------------------------------------------------
387
+ let t1;
388
+ let t2;
389
+ function print_stat() {
390
+ t2 = Date.now();
391
+ const str = util.format("R= %d W= %d T=%d t= %d", client.bytesRead, client.bytesWritten, client.transactionsPerformed, t2 - t1);
392
+ console.log(chalk_1.default.yellow.bold(str));
393
+ }
394
+ if (doCrawling) {
395
+ (0, node_opcua_1.assert)(the_session !== null && typeof the_session === "object");
396
+ const crawler = new node_opcua_client_crawler_1.NodeCrawler(the_session);
397
+ let t5 = Date.now();
398
+ client.on("send_request", () => {
399
+ t1 = Date.now();
390
400
  });
391
- // -----------------------------------------------------------------------------------------------------------
392
- // NAMESPACE
393
- // display namespace array
394
- // -----------------------------------------------------------------------------------------------------------
395
- const server_NamespaceArray_Id = (0, node_opcua_1.makeNodeId)(node_opcua_1.VariableIds.Server_NamespaceArray); // ns=0;i=2006
396
- const dataValue = yield the_session.readVariableValue(server_NamespaceArray_Id);
397
- console.log(" --- NAMESPACE ARRAY ---");
398
- const namespaceArray = dataValue.value.value;
399
- for (const namespace of namespaceArray) {
400
- console.log(" Namespace ", namespace.index, " : ", namespace);
401
- }
402
- console.log(" -----------------------");
403
- // -----------------------------------------------------------------------------------------------------------
404
- // enumerate all EVENT TYPES
405
- // -----------------------------------------------------------------------------------------------------------
406
- const result = getAllEventTypes(the_session);
407
- console.log(chalk_1.default.cyan("---------------------------------------------------- All Event Types "));
408
- console.log(treeify.asTree(result, true));
409
- console.log(" -----------------------");
410
- // -----------------------------------------------------------------------------------------------------------
411
- // Node Crawling
412
- // -----------------------------------------------------------------------------------------------------------
413
- let t1;
414
- let t2;
415
- function print_stat() {
416
- t2 = Date.now();
417
- const str = util.format("R= %d W= %d T=%d t= %d", client.bytesRead, client.bytesWritten, client.transactionsPerformed, t2 - t1);
418
- console.log(chalk_1.default.yellow.bold(str));
419
- }
420
- if (doCrawling) {
421
- (0, node_opcua_1.assert)(the_session !== null && typeof the_session === "object");
422
- const crawler = new node_opcua_client_crawler_1.NodeCrawler(the_session);
423
- let t5 = Date.now();
424
- client.on("send_request", () => {
425
- t1 = Date.now();
401
+ client.on("receive_response", print_stat);
402
+ t5 = Date.now();
403
+ // xx crawler.on("browsed", function (element) {
404
+ // xx console.log("->",(new Date()).getTime()-t,element.browseName.name,element.nodeId.toString());
405
+ // xx });
406
+ const nodeId = "ObjectsFolder";
407
+ console.log("now crawling object folder ...please wait...");
408
+ const obj = await crawler.read(nodeId);
409
+ console.log(" Time = ", new Date().getTime() - t5);
410
+ console.log(" read = ", crawler.readCounter);
411
+ console.log(" browse = ", crawler.browseCounter);
412
+ console.log(" browseNext = ", crawler.browseNextCounter);
413
+ console.log(" transaction = ", crawler.transactionCounter);
414
+ if (false) {
415
+ // todo : treeify.asTree performance is *very* slow on large object, replace with better implementation
416
+ // xx console.log(treeify.asTree(obj, true));
417
+ treeify.asLines(obj, true, true, (line) => {
418
+ console.log(line);
426
419
  });
427
- client.on("receive_response", print_stat);
428
- t5 = Date.now();
429
- // xx crawler.on("browsed", function (element) {
430
- // xx console.log("->",(new Date()).getTime()-t,element.browseName.name,element.nodeId.toString());
431
- // xx });
432
- const nodeId = "ObjectsFolder";
433
- console.log("now crawling object folder ...please wait...");
434
- const obj = yield crawler.read(nodeId);
435
- console.log(" Time = ", new Date().getTime() - t5);
436
- console.log(" read = ", crawler.readCounter);
437
- console.log(" browse = ", crawler.browseCounter);
438
- console.log(" browseNext = ", crawler.browseNextCounter);
439
- console.log(" transaction = ", crawler.transactionCounter);
440
- if (false) {
441
- // todo : treeify.asTree performance is *very* slow on large object, replace with better implementation
442
- // xx console.log(treeify.asTree(obj, true));
443
- treeify.asLines(obj, true, true, (line) => {
444
- console.log(line);
445
- });
446
- }
447
- crawler.dispose();
448
420
  }
449
- client.removeListener("receive_response", print_stat);
450
- // -----------------------------------------------------------------------------------------------------------------
451
- // enumerate all Condition Types exposed by the server
452
- // -----------------------------------------------------------------------------------------------------------------
453
- console.log("--------------------------------------------------------------- Enumerate all Condition Types exposed by the server");
454
- const conditionTree = yield enumerateAllConditionTypes(the_session);
455
- console.log(treeify.asTree(conditionTree));
421
+ crawler.dispose();
422
+ }
423
+ client.removeListener("receive_response", print_stat);
424
+ // -----------------------------------------------------------------------------------------------------------------
425
+ // enumerate all Condition Types exposed by the server
426
+ // -----------------------------------------------------------------------------------------------------------------
427
+ console.log("--------------------------------------------------------------- Enumerate all Condition Types exposed by the server");
428
+ const conditionTree = await enumerateAllConditionTypes(the_session);
429
+ console.log(treeify.asTree(conditionTree));
430
+ console.log(" -----------------------------------------------------------------------------------------------------------------");
431
+ // -----------------------------------------------------------------------------------------------------------------
432
+ // enumerate all objects that have an Alarm & Condition instances
433
+ // -----------------------------------------------------------------------------------------------------------------
434
+ const alarms = await enumerateAllAlarmAndConditionInstances(the_session);
435
+ console.log(" -------------------------------------------------------------- Alarms & Conditions ------------------------");
436
+ for (const alarm of alarms) {
437
+ console.log("parent = ", chalk_1.default.cyan(w(alarm.parent.toString(), 30)), chalk_1.default.green.bold(w(alarm.typeDefinitionName, 30)), "alarmName = ", chalk_1.default.cyan(w(alarm.browseName.toString(), 30)), chalk_1.default.yellow(w(alarm.alarmNodeId.toString(), 40)));
438
+ }
439
+ console.log(" -----------------------------------------------------------------------------------------------------------------");
440
+ // -----------------------------------------------------------------------------------------------------------------
441
+ // Testing if server implements QueryFirst
442
+ // -----------------------------------------------------------------------------------------------------------------
443
+ try {
444
+ console.log(" ---------------------------------------------------------- Testing QueryFirst");
445
+ const queryFirstRequest = {
446
+ view: {
447
+ viewId: node_opcua_1.NodeId.nullNodeId
448
+ },
449
+ nodeTypes: [
450
+ {
451
+ typeDefinitionNode: (0, node_opcua_1.makeExpandedNodeId)("i=58"),
452
+ includeSubTypes: true,
453
+ dataToReturn: [
454
+ {
455
+ attributeId: node_opcua_1.AttributeIds.AccessLevel,
456
+ relativePath: undefined
457
+ }
458
+ ]
459
+ }
460
+ ]
461
+ };
462
+ const queryFirstResult = await the_session.queryFirst(queryFirstRequest);
456
463
  console.log(" -----------------------------------------------------------------------------------------------------------------");
457
- // -----------------------------------------------------------------------------------------------------------------
458
- // enumerate all objects that have an Alarm & Condition instances
459
- // -----------------------------------------------------------------------------------------------------------------
460
- const alarms = yield enumerateAllAlarmAndConditionInstances(the_session);
461
- console.log(" -------------------------------------------------------------- Alarms & Conditions ------------------------");
462
- for (const alarm of alarms) {
463
- console.log("parent = ", chalk_1.default.cyan(w(alarm.parent.toString(), 30)), chalk_1.default.green.bold(w(alarm.typeDefinitionName, 30)), "alarmName = ", chalk_1.default.cyan(w(alarm.browseName.toString(), 30)), chalk_1.default.yellow(w(alarm.alarmNodeId.toString(), 40)));
464
+ }
465
+ catch (err) {
466
+ if (util_1.types.isNativeError(err)) {
467
+ console.log(" Server is not supporting queryFirst err=", err.message);
464
468
  }
469
+ }
470
+ // create Read
471
+ if (doHistory) {
472
+ console.log(" ---------------------------------------------------------- History Read------------------------");
473
+ const now = Date.now();
474
+ const start = now - 1000; // read 1 seconds of history
475
+ const historicalReadResult = await the_session.readHistoryValue(monitored_node, new Date(start), new Date(now));
476
+ console.log(historicalReadResult.toString());
465
477
  console.log(" -----------------------------------------------------------------------------------------------------------------");
466
- // -----------------------------------------------------------------------------------------------------------------
467
- // Testing if server implements QueryFirst
468
- // -----------------------------------------------------------------------------------------------------------------
469
- try {
470
- console.log(" ---------------------------------------------------------- Testing QueryFirst");
471
- const queryFirstRequest = {
472
- view: {
473
- viewId: node_opcua_1.NodeId.nullNodeId
474
- },
475
- nodeTypes: [
476
- {
477
- typeDefinitionNode: (0, node_opcua_1.makeExpandedNodeId)("i=58"),
478
- includeSubTypes: true,
479
- dataToReturn: [
480
- {
481
- attributeId: node_opcua_1.AttributeIds.AccessLevel,
482
- relativePath: undefined
483
- }
484
- ]
485
- }
486
- ]
487
- };
488
- const queryFirstResult = yield the_session.queryFirst(queryFirstRequest);
489
- console.log(" -----------------------------------------------------------------------------------------------------------------");
490
- }
491
- catch (err) {
492
- if (util_1.types.isNativeError(err)) {
493
- console.log(" Server is not supporting queryFirst err=", err.message);
494
- }
495
- }
496
- // create Read
497
- if (doHistory) {
498
- console.log(" ---------------------------------------------------------- History Read------------------------");
499
- const now = Date.now();
500
- const start = now - 1000; // read 1 seconds of history
501
- const historicalReadResult = yield the_session.readHistoryValue(monitored_node, new Date(start), new Date(now));
502
- console.log(historicalReadResult.toString());
503
- console.log(" -----------------------------------------------------------------------------------------------------------------");
504
- }
505
- // ----------------------------------------------------------------------------------
506
- // create subscription
507
- // ----------------------------------------------------------------------------------
508
- console.log(" ---------------------------------------------------------- Create Subscription ");
509
- const parameters = {
510
- maxNotificationsPerPublish: 10,
511
- priority: 10,
512
- publishingEnabled: true,
513
- requestedLifetimeCount: 1000,
514
- requestedMaxKeepAliveCount: 12,
515
- requestedPublishingInterval: 2000
516
- };
517
- theSubscription = yield the_session.createSubscription2(parameters);
518
- let t = getTick();
519
- console.log("started subscription :", theSubscription.subscriptionId);
520
- console.log(" revised parameters ");
521
- console.log(" revised maxKeepAliveCount ", theSubscription.maxKeepAliveCount, " ( requested ", parameters.requestedMaxKeepAliveCount + ")");
522
- console.log(" revised lifetimeCount ", theSubscription.lifetimeCount, " ( requested ", parameters.requestedLifetimeCount + ")");
523
- console.log(" revised publishingInterval ", theSubscription.publishingInterval, " ( requested ", parameters.requestedPublishingInterval + ")");
524
- theSubscription
525
- .on("internal_error", (err) => {
526
- console.log(" received internal error", err.message);
527
- })
528
- .on("keepalive", () => {
529
- const t4 = getTick();
530
- const span = t4 - t;
531
- t = t4;
532
- console.log("keepalive ", span / 1000, "sec", " pending request on server = ", theSubscription.getPublishEngine().nbPendingPublishRequests);
533
- })
534
- .on("terminated", () => {
535
- /* */
536
- });
537
- try {
538
- const results1 = yield theSubscription.getMonitoredItems();
539
- console.log("MonitoredItems clientHandles", results1.clientHandles);
540
- console.log("MonitoredItems serverHandles", results1.serverHandles);
541
- }
542
- catch (err) {
543
- if (util_1.types.isNativeError(err)) {
544
- console.log("Server doesn't seems to implement getMonitoredItems method ", err.message);
545
- }
546
- }
547
- // get_monitored_item
548
- // monitor_a_variable_node_value
549
- console.log("Monitoring monitor_a_variable_node_value");
550
- // ---------------------------------------------------------------
551
- // monitor a variable node value
552
- // ---------------------------------------------------------------
553
- console.log(" Monitoring node ", monitored_node.toString());
554
- const monitoredItem = node_opcua_1.ClientMonitoredItem.create(theSubscription, {
555
- attributeId: node_opcua_1.AttributeIds.Value,
556
- nodeId: monitored_node
557
- }, {
558
- discardOldest: true,
559
- queueSize: 10000,
560
- samplingInterval: 1000
561
- // xx filter: { parameterTypeId: "ns=0;i=0", encodingMask: 0 },
562
- });
563
- monitoredItem.on("initialized", () => {
564
- console.log("monitoredItem initialized");
565
- });
566
- monitoredItem.on("changed", (dataValue1) => {
567
- console.log(monitoredItem.itemToMonitor.nodeId.toString(), " value has changed to " + dataValue1.value.toString());
568
- });
569
- monitoredItem.on("err", (err_message) => {
570
- console.log(monitoredItem.itemToMonitor.nodeId.toString(), chalk_1.default.red(" ERROR"), err_message);
571
- });
572
- const results = yield theSubscription.getMonitoredItems();
573
- console.log("MonitoredItems clientHandles", results.clientHandles);
574
- console.log("MonitoredItems serverHandles", results.serverHandles);
575
- console.log("Monitoring monitor_the_object_events");
576
- // ---------------------------------------------------------------
577
- // monitor the object events
578
- // ---------------------------------------------------------------
579
- const baseEventTypeId = "i=2041"; // BaseEventType;
580
- const serverObjectId = "i=2253";
581
- const fields = [
582
- "EventId",
583
- "EventType",
584
- "SourceNode",
585
- "SourceName",
586
- "Time",
587
- "ReceiveTime",
588
- "Message",
589
- "Severity",
590
- // ConditionType
591
- "ConditionClassId",
592
- "ConditionClassName",
593
- "ConditionName",
594
- "BranchId",
595
- "Retain",
596
- "EnabledState",
597
- "Quality",
598
- "LastSeverity",
599
- "Comment",
600
- "ClientUserId",
601
- // AcknowledgeConditionType
602
- "AckedState",
603
- "ConfirmedState",
604
- // AlarmConditionType
605
- "ActiveState",
606
- "InputNode",
607
- "SuppressedState",
608
- "HighLimit",
609
- "LowLimit",
610
- "HighHighLimit",
611
- "LowLowLimit",
612
- "Value"
613
- ];
614
- const eventFilter = (0, node_opcua_1.constructEventFilter)(fields, (0, node_opcua_1.ofType)("ConditionType"));
615
- const event_monitoringItem = node_opcua_1.ClientMonitoredItem.create(theSubscription, {
616
- attributeId: node_opcua_1.AttributeIds.EventNotifier,
617
- nodeId: serverObjectId
618
- }, {
619
- discardOldest: true,
620
- filter: eventFilter,
621
- queueSize: 100000
622
- });
623
- event_monitoringItem.on("initialized", () => {
624
- console.log("event_monitoringItem initialized");
625
- });
626
- event_monitoringItem.on("changed", (eventFields) => {
627
- (0, node_opcua_1.dumpEvent)(the_session, fields, eventFields);
628
- });
629
- event_monitoringItem.on("err", (err_message) => {
630
- console.log(chalk_1.default.red("event_monitoringItem ", baseEventTypeId, " ERROR"), err_message);
631
- });
632
- console.log("--------------------------------------------- Monitoring alarms");
633
- const alarmNodeId = (0, node_opcua_1.coerceNodeId)("ns=2;s=1:Colours/EastTank?Green");
634
- yield monitorAlarm(theSubscription, alarmNodeId);
635
- console.log("Starting timer ", timeout);
636
- if (timeout > 0) {
637
- // simulate a connection break at t =timeout/2
638
- // new Promise((resolve) => {
639
- setTimeout(() => {
640
- console.log(chalk_1.default.red(" -------------------------------------------------------------------- "));
641
- console.log(chalk_1.default.red(" -- SIMULATE CONNECTION BREAK -- "));
642
- console.log(chalk_1.default.red(" -------------------------------------------------------------------- "));
643
- const socket = client._secureChannel._transport._socket;
644
- socket.end();
645
- socket.emit("error", new Error("ECONNRESET"));
646
- }, timeout / 2.0);
647
- // });
648
- yield new Promise((resolve) => {
649
- setTimeout(() => __awaiter(this, void 0, void 0, function* () {
650
- console.log("time out => shutting down ");
651
- if (!theSubscription) {
652
- return resolve();
653
- }
654
- if (theSubscription) {
655
- const s = theSubscription;
656
- theSubscription = null;
657
- yield s.terminate();
658
- yield the_session.close();
659
- yield client.disconnect();
660
- console.log(" Done ");
661
- process.exit(0);
662
- }
663
- }), timeout);
664
- });
478
+ }
479
+ // ----------------------------------------------------------------------------------
480
+ // create subscription
481
+ // ----------------------------------------------------------------------------------
482
+ console.log(" ---------------------------------------------------------- Create Subscription ");
483
+ const parameters = {
484
+ maxNotificationsPerPublish: 10,
485
+ priority: 10,
486
+ publishingEnabled: true,
487
+ requestedLifetimeCount: 1000,
488
+ requestedMaxKeepAliveCount: 12,
489
+ requestedPublishingInterval: 2000
490
+ };
491
+ theSubscription = await the_session.createSubscription2(parameters);
492
+ let t = getTick();
493
+ console.log("started subscription :", theSubscription.subscriptionId);
494
+ console.log(" revised parameters ");
495
+ console.log(" revised maxKeepAliveCount ", theSubscription.maxKeepAliveCount, " ( requested ", parameters.requestedMaxKeepAliveCount + ")");
496
+ console.log(" revised lifetimeCount ", theSubscription.lifetimeCount, " ( requested ", parameters.requestedLifetimeCount + ")");
497
+ console.log(" revised publishingInterval ", theSubscription.publishingInterval, " ( requested ", parameters.requestedPublishingInterval + ")");
498
+ theSubscription
499
+ .on("internal_error", (err) => {
500
+ console.log(" received internal error", err.message);
501
+ })
502
+ .on("keepalive", () => {
503
+ const t4 = getTick();
504
+ const span = t4 - t;
505
+ t = t4;
506
+ console.log("keepalive ", span / 1000, "sec", " pending request on server = ", theSubscription.getPublishEngine().nbPendingPublishRequests);
507
+ })
508
+ .on("terminated", () => {
509
+ /* */
510
+ });
511
+ try {
512
+ const results1 = await theSubscription.getMonitoredItems();
513
+ console.log("MonitoredItems clientHandles", results1.clientHandles);
514
+ console.log("MonitoredItems serverHandles", results1.serverHandles);
515
+ }
516
+ catch (err) {
517
+ if (util_1.types.isNativeError(err)) {
518
+ console.log("Server doesn't seems to implement getMonitoredItems method ", err.message);
665
519
  }
666
- console.log(" closing session");
667
- yield the_session.close();
668
- console.log(" session closed");
669
- console.log(" Calling disconnect");
670
- yield client.disconnect();
671
- console.log(chalk_1.default.cyan(" disconnected"));
672
- console.log("success !! ");
520
+ }
521
+ // get_monitored_item
522
+ // monitor_a_variable_node_value
523
+ console.log("Monitoring monitor_a_variable_node_value");
524
+ // ---------------------------------------------------------------
525
+ // monitor a variable node value
526
+ // ---------------------------------------------------------------
527
+ console.log(" Monitoring node ", monitored_node.toString());
528
+ const monitoredItem = node_opcua_1.ClientMonitoredItem.create(theSubscription, {
529
+ attributeId: node_opcua_1.AttributeIds.Value,
530
+ nodeId: monitored_node
531
+ }, {
532
+ discardOldest: true,
533
+ queueSize: 10000,
534
+ samplingInterval: 1000
535
+ // xx filter: { parameterTypeId: "ns=0;i=0", encodingMask: 0 },
536
+ });
537
+ monitoredItem.on("initialized", () => {
538
+ console.log("monitoredItem initialized");
539
+ });
540
+ monitoredItem.on("changed", (dataValue1) => {
541
+ console.log(monitoredItem.itemToMonitor.nodeId.toString(), " value has changed to " + dataValue1.value.toString());
542
+ });
543
+ monitoredItem.on("err", (err_message) => {
544
+ console.log(monitoredItem.itemToMonitor.nodeId.toString(), chalk_1.default.red(" ERROR"), err_message);
545
+ });
546
+ const results = await theSubscription.getMonitoredItems();
547
+ console.log("MonitoredItems clientHandles", results.clientHandles);
548
+ console.log("MonitoredItems serverHandles", results.serverHandles);
549
+ console.log("Monitoring monitor_the_object_events");
550
+ // ---------------------------------------------------------------
551
+ // monitor the object events
552
+ // ---------------------------------------------------------------
553
+ const baseEventTypeId = "i=2041"; // BaseEventType;
554
+ const serverObjectId = "i=2253";
555
+ const fields = [
556
+ "EventId",
557
+ "EventType",
558
+ "SourceNode",
559
+ "SourceName",
560
+ "Time",
561
+ "ReceiveTime",
562
+ "Message",
563
+ "Severity",
564
+ // ConditionType
565
+ "ConditionClassId",
566
+ "ConditionClassName",
567
+ "ConditionName",
568
+ "BranchId",
569
+ "Retain",
570
+ "EnabledState",
571
+ "Quality",
572
+ "LastSeverity",
573
+ "Comment",
574
+ "ClientUserId",
575
+ // AcknowledgeConditionType
576
+ "AckedState",
577
+ "ConfirmedState",
578
+ // AlarmConditionType
579
+ "ActiveState",
580
+ "InputNode",
581
+ "SuppressedState",
582
+ "HighLimit",
583
+ "LowLimit",
584
+ "HighHighLimit",
585
+ "LowLowLimit",
586
+ "Value"
587
+ ];
588
+ const eventFilter = (0, node_opcua_1.constructEventFilter)(fields, (0, node_opcua_1.ofType)("ConditionType"));
589
+ const event_monitoringItem = node_opcua_1.ClientMonitoredItem.create(theSubscription, {
590
+ attributeId: node_opcua_1.AttributeIds.EventNotifier,
591
+ nodeId: serverObjectId
592
+ }, {
593
+ discardOldest: true,
594
+ filter: eventFilter,
595
+ queueSize: 100000
596
+ });
597
+ event_monitoringItem.on("initialized", () => {
598
+ console.log("event_monitoringItem initialized");
599
+ });
600
+ event_monitoringItem.on("changed", (eventFields) => {
601
+ (0, node_opcua_1.dumpEvent)(the_session, fields, eventFields);
673
602
  });
603
+ event_monitoringItem.on("err", (err_message) => {
604
+ console.log(chalk_1.default.red("event_monitoringItem ", baseEventTypeId, " ERROR"), err_message);
605
+ });
606
+ console.log("--------------------------------------------- Monitoring alarms");
607
+ const alarmNodeId = (0, node_opcua_1.coerceNodeId)("ns=2;s=1:Colours/EastTank?Green");
608
+ await monitorAlarm(theSubscription, alarmNodeId);
609
+ console.log("Starting timer ", timeout);
610
+ if (timeout > 0) {
611
+ // simulate a connection break at t =timeout/2
612
+ // new Promise((resolve) => {
613
+ setTimeout(() => {
614
+ console.log(chalk_1.default.red(" -------------------------------------------------------------------- "));
615
+ console.log(chalk_1.default.red(" -- SIMULATE CONNECTION BREAK -- "));
616
+ console.log(chalk_1.default.red(" -------------------------------------------------------------------- "));
617
+ const socket = client._secureChannel._transport._socket;
618
+ socket.end();
619
+ socket.emit("error", new Error("ECONNRESET"));
620
+ }, timeout / 2.0);
621
+ // });
622
+ await new Promise((resolve) => {
623
+ setTimeout(async () => {
624
+ console.log("time out => shutting down ");
625
+ if (!theSubscription) {
626
+ return resolve();
627
+ }
628
+ if (theSubscription) {
629
+ const s = theSubscription;
630
+ theSubscription = null;
631
+ await s.terminate();
632
+ await the_session.close();
633
+ await client.disconnect();
634
+ console.log(" Done ");
635
+ process.exit(0);
636
+ }
637
+ }, timeout);
638
+ });
639
+ }
640
+ console.log(" closing session");
641
+ await the_session.close();
642
+ console.log(" session closed");
643
+ console.log(" Calling disconnect");
644
+ await client.disconnect();
645
+ console.log(chalk_1.default.cyan(" disconnected"));
646
+ console.log("success !! ");
674
647
  }
675
- process.once("SIGINT", () => __awaiter(void 0, void 0, void 0, function* () {
648
+ process.once("SIGINT", async () => {
676
649
  console.log(" user interruption ...");
677
650
  if (theSubscription) {
678
651
  console.log(chalk_1.default.red.bold(" Received client interruption from user "));
679
652
  console.log(chalk_1.default.red.bold(" shutting down ..."));
680
653
  const subscription = theSubscription;
681
654
  theSubscription = null;
682
- yield subscription.terminate();
655
+ await subscription.terminate();
683
656
  }
684
- yield the_session.close();
685
- yield client.disconnect();
657
+ await the_session.close();
658
+ await client.disconnect();
686
659
  process.exit(0);
687
- }));
660
+ });
688
661
  main();
689
662
  //# sourceMappingURL=simple_client_ts.js.map