node-opcua-samples 2.73.1 → 2.76.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.
@@ -3,19 +3,17 @@
3
3
  const net = require("net");
4
4
 
5
5
  const chalk = require("chalk");
6
-
7
- const argv = require("yargs")
8
- .usage("Usage: $0 --portServer [num] --port [num] --hostname <hostname> -block")
9
- .argv;
6
+ const yargs = require("yargs");
7
+ const argv = yargs.usage("Usage: $0 --portServer [num] --port [num] --hostname <hostname> -block").argv;
10
8
 
11
9
  const opcua = require("node-opcua");
12
10
 
13
- const hexDump = require("node-opcua-utils").hexDump;
14
- const MessageBuilder = require("../lib/misc/message_builder").MessageBuilder;
15
- const BinaryStream = require("../lib/misc/binaryStream").BinaryStream;
11
+ const { hexDump } = require("node-opcua-utils");
12
+ const { MessageBuilder } = require("../lib/misc/message_builder");
13
+ const { BinaryStream } = require("../lib/misc/binaryStream");
16
14
 
17
- const analyseExtensionObject = require("../lib/misc/analyzePacket").analyseExtensionObject;
18
- const messageHeaderToString = require("../lib/misc/message_header").messageHeaderToString;
15
+ const { analyseExtensionObject } = require("../lib/misc/analyzePacket");
16
+ const { messageHeaderToString } = require("../lib/misc/message_header");
19
17
 
20
18
  const s = require("../lib/datamodel/structures");
21
19
 
@@ -24,14 +22,11 @@ const hostname = argv.hostname || "localhost";
24
22
 
25
23
  const my_port = parseInt(argv.portServer, 10) || remote_port + 1;
26
24
 
27
-
28
25
  const TrafficAnalyser = function (id) {
29
26
  this.id = id;
30
27
  };
31
28
 
32
-
33
29
  TrafficAnalyser.prototype.add = function (data) {
34
-
35
30
  const stream = new BinaryStream(data);
36
31
  if (argv.block) {
37
32
  console.log(hexDump(data));
@@ -40,7 +35,6 @@ TrafficAnalyser.prototype.add = function (data) {
40
35
  const messageHeader = opcua.readMessageHeader(stream);
41
36
 
42
37
  if (messageHeader.msgType === "ERR") {
43
-
44
38
  const err = new s.TCPErrorMessage();
45
39
  err.decode(stream);
46
40
  console.log(" Error 0x" + err.statusCode.toString() + " reason:" + err.reason);
@@ -49,20 +43,16 @@ TrafficAnalyser.prototype.add = function (data) {
49
43
 
50
44
  const messageBuild = new MessageBuilder();
51
45
  messageBuild.on("full_message_body", function (full_message_body) {
52
-
53
46
  console.log(hexDump(full_message_body));
54
47
 
55
48
  try {
56
49
  analyseExtensionObject(full_message_body);
57
- }
58
- catch (err) {
50
+ } catch (err) {
59
51
  console.log(chalk.red("ERROR : "), err);
60
52
  }
61
53
  });
62
54
 
63
-
64
55
  switch (messageHeader.msgType) {
65
-
66
56
  case "HEL":
67
57
  case "ACK":
68
58
  if (this.id % 2) {
@@ -75,7 +65,7 @@ TrafficAnalyser.prototype.add = function (data) {
75
65
  case "OPN": // open secure channel
76
66
  case "CLO": // close secure channel
77
67
  case "MSG": // message
78
- // decode secure message
68
+ // decode secure message
79
69
  if (this.id % 2) {
80
70
  console.log(chalk.red.bold(messageHeaderToString(data)));
81
71
  } else {
@@ -89,47 +79,44 @@ TrafficAnalyser.prototype.add = function (data) {
89
79
  break;
90
80
  default:
91
81
  break;
92
-
93
82
  }
94
-
95
83
  };
96
84
 
85
+ require("net")
86
+ .createServer(function (socket) {
87
+ console.log("connected");
88
+ const ta_client = new TrafficAnalyser(1);
97
89
 
98
- require("net").createServer(function (socket) {
99
-
100
- console.log("connected");
101
- const ta_client = new TrafficAnalyser(1);
90
+ const ta_server = new TrafficAnalyser(2);
102
91
 
103
- const ta_server = new TrafficAnalyser(2);
92
+ const proxy_client = new net.Socket();
93
+ proxy_client.connect(remote_port, hostname);
104
94
 
105
- const proxy_client = new net.Socket();
106
- proxy_client.connect(remote_port, hostname);
107
-
108
- proxy_client.on("data", function (data) {
109
- console.log(" server -> client : packet length " + data.length);
110
- ta_server.add(data);
111
- try {
112
- socket.write(data);
113
- } catch (err) {
114
- /** */
115
- }
116
- });
117
-
118
- socket.on("data", function (data) {
119
- console.log(" client -> server : packet length " + data.length);
120
- ta_client.add(data);
121
- proxy_client.write(data);
122
- });
123
- socket.on("close", function () {
124
- console.log("server disconnected (CLOSE)");
125
- proxy_client.end();
126
- });
127
-
128
- socket.on("end", function () {
129
- console.log("server disconnected (END)");
130
- });
131
-
132
- }).listen(my_port);
95
+ proxy_client.on("data", function (data) {
96
+ console.log(" server -> client : packet length " + data.length);
97
+ ta_server.add(data);
98
+ try {
99
+ socket.write(data);
100
+ } catch (err) {
101
+ /** */
102
+ }
103
+ });
104
+
105
+ socket.on("data", function (data) {
106
+ console.log(" client -> server : packet length " + data.length);
107
+ ta_client.add(data);
108
+ proxy_client.write(data);
109
+ });
110
+ socket.on("close", function () {
111
+ console.log("server disconnected (CLOSE)");
112
+ proxy_client.end();
113
+ });
114
+
115
+ socket.on("end", function () {
116
+ console.log("server disconnected (END)");
117
+ });
118
+ })
119
+ .listen(my_port);
133
120
 
134
121
  console.log(" registering OPCUA server on port " + my_port);
135
122
  console.log(" +-> redirecting conversation to server port " + remote_port);
@@ -32,6 +32,7 @@ import {
32
32
  NodeCrawler,
33
33
  NodeId,
34
34
  ObjectTypeIds,
35
+ ofType,
35
36
  OPCUAClient,
36
37
  OPCUAClientOptions,
37
38
  QueryFirstRequestOptions,
@@ -751,7 +752,7 @@ async function main() {
751
752
  "Value"
752
753
  ];
753
754
 
754
- const eventFilter = constructEventFilter(fields, [resolveNodeId("ConditionType")]);
755
+ const eventFilter = constructEventFilter(fields, ofType("ConditionType"));
755
756
 
756
757
  const event_monitoringItem = ClientMonitoredItem.create(
757
758
  theSubscription,
@@ -230,8 +230,7 @@ const paths = envPaths(productUri);
230
230
  server_options.alternateHostname = argv.alternateHostname;
231
231
  const server = new OPCUAServer(server_options);
232
232
 
233
- const hostname = require("os").hostname();
234
-
233
+
235
234
  await server.initialize();
236
235
 
237
236
  function post_initialize() {
@@ -525,7 +524,7 @@ const paths = envPaths(productUri);
525
524
  }
526
525
  }
527
526
 
528
- const servicesToTrace = ["CreateSubscription"]; // "Publish", "TransferSubscriptions", "Republish", "CreateSubscription", "CreateMonitoredItems"];
527
+ const servicesToTrace = ["CreateMonitoredItems", "Publish", "ModifyMonitoredItems"]; // "Publish", "TransferSubscriptions", "Republish", "CreateSubscription", "CreateMonitoredItems"];
529
528
  server.on("response", function (response) {
530
529
  if (argv.silent) {
531
530
  return;
@@ -1,2 +1,2 @@
1
- #!/usr/bin/env ts-node
2
- export {};
1
+ #!/usr/bin/env ts-node
2
+ export {};
@@ -1,142 +1,142 @@
1
- #!/usr/bin/env ts-node
2
- "use strict";
3
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
- return new (P || (P = Promise))(function (resolve, reject) {
6
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
- step((generator = generator.apply(thisArg, _arguments || [])).next());
10
- });
11
- };
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- // tslint:disable:no-console
14
- const chalk = require("chalk");
15
- const fs = require("fs");
16
- const path = require("path");
17
- const yargs = require("yargs");
18
- const node_opcua_1 = require("node-opcua");
19
- const node_opcua_crypto_1 = require("node-opcua-crypto");
20
- // tslint:disable:no-var-requires
21
- const Table = require("easy-table");
22
- const treeify = require("treeify");
23
- // eslint-disable-next-line max-statements
24
- function main() {
25
- return __awaiter(this, void 0, void 0, function* () {
26
- // ts-node bin/simple_client.ts --endpoint opc.tcp://localhost:53530/OPCUA/SimulationServer --node "ns=5;s=Sinusoid1"
27
- const argv = yield yargs(process.argv)
28
- .wrap(132)
29
- .option("endpoint", {
30
- alias: "e",
31
- demandOption: true,
32
- describe: "the end point to connect to "
33
- })
34
- .option("securityMode", {
35
- alias: "s",
36
- default: "None",
37
- describe: "the security mode ( None Sign SignAndEncrypt )"
38
- })
39
- .option("securityPolicy", {
40
- alias: "P",
41
- default: "None",
42
- describe: "the policy mode : (" + Object.keys(node_opcua_1.SecurityPolicy).join(" - ") + ")"
43
- })
44
- .option("discovery", {
45
- alias: "D",
46
- describe: "specify the endpoint uri of discovery server (by default same as server endpoint uri)"
47
- })
48
- .example("get_endpoints --endpoint opc.tcp://localhost:49230", "").argv;
49
- const securityMode = (0, node_opcua_1.coerceMessageSecurityMode)(argv.securityMode);
50
- if (securityMode === node_opcua_1.MessageSecurityMode.Invalid) {
51
- throw new Error("Invalid Security mode");
52
- }
53
- const securityPolicy = (0, node_opcua_1.coerceSecurityPolicy)(argv.securityPolicy);
54
- if (securityPolicy === node_opcua_1.SecurityPolicy.Invalid) {
55
- throw new Error("Invalid securityPolicy");
56
- }
57
- console.log(chalk.cyan("securityMode = "), securityMode.toString());
58
- console.log(chalk.cyan("securityPolicy = "), securityPolicy.toString());
59
- const endpointUrl = argv.endpoint;
60
- if (!endpointUrl) {
61
- yargs.showHelp();
62
- process.exit(0);
63
- }
64
- const discoveryUrl = argv.discovery ? argv.discovery : endpointUrl;
65
- const optionsInitial = {
66
- securityMode,
67
- securityPolicy,
68
- endpointMustExist: false,
69
- connectionStrategy: {
70
- initialDelay: 2000,
71
- maxDelay: 10 * 1000,
72
- maxRetry: 10
73
- },
74
- discoveryUrl
75
- };
76
- const client = node_opcua_1.OPCUAClient.create(optionsInitial);
77
- client.on("backoff", (retry, delay) => {
78
- console.log(chalk.bgWhite.yellow("backoff attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
79
- });
80
- console.log(" connecting to ", chalk.cyan.bold(endpointUrl));
81
- console.log(" strategy", client.connectionStrategy);
82
- try {
83
- yield client.connect(endpointUrl);
84
- }
85
- catch (err) {
86
- console.log(chalk.red(" Cannot connect to ") + endpointUrl);
87
- if (err instanceof Error) {
88
- console.log(" Error = ", err.message);
89
- }
90
- return;
91
- }
92
- const endpoints = yield client.getEndpoints();
93
- if (argv.debug) {
94
- fs.writeFileSync("tmp/endpoints.log", JSON.stringify(endpoints, null, " "));
95
- console.log(treeify.asTree(endpoints, true));
96
- }
97
- const table = new Table();
98
- let serverCertificate;
99
- let i = 0;
100
- for (const endpoint of endpoints) {
101
- table.cell("endpoint", endpoint.endpointUrl + "");
102
- table.cell("Application URI", endpoint.server.applicationUri);
103
- table.cell("Product URI", endpoint.server.productUri);
104
- table.cell("Application Name", endpoint.server.applicationName.text);
105
- table.cell("securityLevel", endpoint.securityLevel);
106
- table.cell("Security Mode", chalk.cyan(node_opcua_1.MessageSecurityMode[endpoint.securityMode].toString()));
107
- table.cell("securityPolicyUri", chalk.cyan(endpoint.securityPolicyUri));
108
- table.cell("Type", node_opcua_1.ApplicationType[endpoint.server.applicationType]);
109
- table.cell("certificate", "..." /*endpoint.serverCertificate*/);
110
- endpoint.server.discoveryUrls = endpoint.server.discoveryUrls || [];
111
- table.cell("discoveryUrls", endpoint.server.discoveryUrls.join(" - "));
112
- serverCertificate = endpoint.serverCertificate;
113
- const certificate_filename = path.join(__dirname, "../certificates/PKI/server_certificate" + i + ".pem");
114
- if (serverCertificate) {
115
- fs.writeFile(certificate_filename, (0, node_opcua_crypto_1.toPem)(serverCertificate, "CERTIFICATE"), () => {
116
- /**/
117
- });
118
- }
119
- table.newRow();
120
- i++;
121
- }
122
- console.log(table.toString());
123
- for (const endpoint of endpoints) {
124
- console.log("Identify Token for : Security Mode=", chalk.cyan(node_opcua_1.MessageSecurityMode[endpoint.securityMode].toString()), " Policy=", chalk.cyan(endpoint.securityPolicyUri));
125
- const table2 = new Table();
126
- for (const token of endpoint.userIdentityTokens) {
127
- table2.cell("policyId", token.policyId);
128
- table2.cell("tokenType", node_opcua_1.UserTokenType[token.tokenType]);
129
- table2.cell("issuedTokenType", token.issuedTokenType);
130
- table2.cell("issuerEndpointUrl", token.issuerEndpointUrl);
131
- table2.cell("securityPolicyUri", token.securityPolicyUri);
132
- table2.newRow();
133
- }
134
- console.log(table2.toString());
135
- }
136
- yield client.disconnect();
137
- console.log("success !! ");
138
- process.exit(0);
139
- });
140
- }
141
- main();
1
+ #!/usr/bin/env ts-node
2
+ "use strict";
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ // tslint:disable:no-console
14
+ const chalk = require("chalk");
15
+ const fs = require("fs");
16
+ const path = require("path");
17
+ const yargs = require("yargs");
18
+ const node_opcua_1 = require("node-opcua");
19
+ const node_opcua_crypto_1 = require("node-opcua-crypto");
20
+ // tslint:disable:no-var-requires
21
+ const Table = require("easy-table");
22
+ const treeify = require("treeify");
23
+ // eslint-disable-next-line max-statements
24
+ function main() {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ // ts-node bin/simple_client.ts --endpoint opc.tcp://localhost:53530/OPCUA/SimulationServer --node "ns=5;s=Sinusoid1"
27
+ const argv = yield yargs(process.argv)
28
+ .wrap(132)
29
+ .option("endpoint", {
30
+ alias: "e",
31
+ demandOption: true,
32
+ describe: "the end point to connect to "
33
+ })
34
+ .option("securityMode", {
35
+ alias: "s",
36
+ default: "None",
37
+ describe: "the security mode ( None Sign SignAndEncrypt )"
38
+ })
39
+ .option("securityPolicy", {
40
+ alias: "P",
41
+ default: "None",
42
+ describe: "the policy mode : (" + Object.keys(node_opcua_1.SecurityPolicy).join(" - ") + ")"
43
+ })
44
+ .option("discovery", {
45
+ alias: "D",
46
+ describe: "specify the endpoint uri of discovery server (by default same as server endpoint uri)"
47
+ })
48
+ .example("get_endpoints --endpoint opc.tcp://localhost:49230", "").argv;
49
+ const securityMode = (0, node_opcua_1.coerceMessageSecurityMode)(argv.securityMode);
50
+ if (securityMode === node_opcua_1.MessageSecurityMode.Invalid) {
51
+ throw new Error("Invalid Security mode");
52
+ }
53
+ const securityPolicy = (0, node_opcua_1.coerceSecurityPolicy)(argv.securityPolicy);
54
+ if (securityPolicy === node_opcua_1.SecurityPolicy.Invalid) {
55
+ throw new Error("Invalid securityPolicy");
56
+ }
57
+ console.log(chalk.cyan("securityMode = "), securityMode.toString());
58
+ console.log(chalk.cyan("securityPolicy = "), securityPolicy.toString());
59
+ const endpointUrl = argv.endpoint;
60
+ if (!endpointUrl) {
61
+ yargs.showHelp();
62
+ process.exit(0);
63
+ }
64
+ const discoveryUrl = argv.discovery ? argv.discovery : endpointUrl;
65
+ const optionsInitial = {
66
+ securityMode,
67
+ securityPolicy,
68
+ endpointMustExist: false,
69
+ connectionStrategy: {
70
+ initialDelay: 2000,
71
+ maxDelay: 10 * 1000,
72
+ maxRetry: 10
73
+ },
74
+ discoveryUrl
75
+ };
76
+ const client = node_opcua_1.OPCUAClient.create(optionsInitial);
77
+ client.on("backoff", (retry, delay) => {
78
+ console.log(chalk.bgWhite.yellow("backoff attempt #"), retry, " retrying in ", delay / 1000.0, " seconds");
79
+ });
80
+ console.log(" connecting to ", chalk.cyan.bold(endpointUrl));
81
+ console.log(" strategy", client.connectionStrategy);
82
+ try {
83
+ yield client.connect(endpointUrl);
84
+ }
85
+ catch (err) {
86
+ console.log(chalk.red(" Cannot connect to ") + endpointUrl);
87
+ if (err instanceof Error) {
88
+ console.log(" Error = ", err.message);
89
+ }
90
+ return;
91
+ }
92
+ const endpoints = yield client.getEndpoints();
93
+ if (argv.debug) {
94
+ fs.writeFileSync("tmp/endpoints.log", JSON.stringify(endpoints, null, " "));
95
+ console.log(treeify.asTree(endpoints, true));
96
+ }
97
+ const table = new Table();
98
+ let serverCertificate;
99
+ let i = 0;
100
+ for (const endpoint of endpoints) {
101
+ table.cell("endpoint", endpoint.endpointUrl + "");
102
+ table.cell("Application URI", endpoint.server.applicationUri);
103
+ table.cell("Product URI", endpoint.server.productUri);
104
+ table.cell("Application Name", endpoint.server.applicationName.text);
105
+ table.cell("securityLevel", endpoint.securityLevel);
106
+ table.cell("Security Mode", chalk.cyan(node_opcua_1.MessageSecurityMode[endpoint.securityMode].toString()));
107
+ table.cell("securityPolicyUri", chalk.cyan(endpoint.securityPolicyUri));
108
+ table.cell("Type", node_opcua_1.ApplicationType[endpoint.server.applicationType]);
109
+ table.cell("certificate", "..." /*endpoint.serverCertificate*/);
110
+ endpoint.server.discoveryUrls = endpoint.server.discoveryUrls || [];
111
+ table.cell("discoveryUrls", endpoint.server.discoveryUrls.join(" - "));
112
+ serverCertificate = endpoint.serverCertificate;
113
+ const certificate_filename = path.join(__dirname, "../certificates/PKI/server_certificate" + i + ".pem");
114
+ if (serverCertificate) {
115
+ fs.writeFile(certificate_filename, (0, node_opcua_crypto_1.toPem)(serverCertificate, "CERTIFICATE"), () => {
116
+ /**/
117
+ });
118
+ }
119
+ table.newRow();
120
+ i++;
121
+ }
122
+ console.log(table.toString());
123
+ for (const endpoint of endpoints) {
124
+ console.log("Identify Token for : Security Mode=", chalk.cyan(node_opcua_1.MessageSecurityMode[endpoint.securityMode].toString()), " Policy=", chalk.cyan(endpoint.securityPolicyUri));
125
+ const table2 = new Table();
126
+ for (const token of endpoint.userIdentityTokens) {
127
+ table2.cell("policyId", token.policyId);
128
+ table2.cell("tokenType", node_opcua_1.UserTokenType[token.tokenType]);
129
+ table2.cell("issuedTokenType", token.issuedTokenType);
130
+ table2.cell("issuerEndpointUrl", token.issuerEndpointUrl);
131
+ table2.cell("securityPolicyUri", token.securityPolicyUri);
132
+ table2.newRow();
133
+ }
134
+ console.log(table2.toString());
135
+ }
136
+ yield client.disconnect();
137
+ console.log("success !! ");
138
+ process.exit(0);
139
+ });
140
+ }
141
+ main();
142
142
  //# sourceMappingURL=get_endpoints.js.map
@@ -1 +1 @@
1
- export {};
1
+ export {};