@vitormnm/node-red-simple-opcua 1.0.2 → 1.1.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.
@@ -0,0 +1,291 @@
1
+ "use strict";
2
+
3
+ const {
4
+ AttributeIds,
5
+ BrowseDirection,
6
+ DataType,
7
+ NodeClass,
8
+ coerceNodeId,
9
+ makeNodeId
10
+ } = require("node-opcua");
11
+
12
+ async function browseNode(session, root) {
13
+ const nodeID = normalizeNodeId(root.nodeID || root.nodeId || ROOT_NODE_ID);
14
+ const result = {
15
+ name: root.name || await readBrowseName(session, nodeID, "RootFolder"),
16
+ nodeID,
17
+ browse: []
18
+ };
19
+
20
+ const browseResult = await session.browse({
21
+ nodeId: nodeID,
22
+ browseDirection: BrowseDirection.Forward,
23
+ includeSubtypes: true,
24
+ resultMask: 63
25
+ });
26
+
27
+ const references = browseResult && Array.isArray(browseResult.references)
28
+ ? browseResult.references
29
+ : [];
30
+
31
+ for (const reference of references) {
32
+ result.browse.push(await mapReference(session, reference));
33
+ }
34
+
35
+ return result;
36
+ }
37
+
38
+ function normalizeBrowseRoots(payload) {
39
+ if (payload === undefined || payload === null) {
40
+ return [{ name: "RootFolder", nodeID: ROOT_NODE_ID }];
41
+ }
42
+
43
+ if (!Array.isArray(payload)) {
44
+ throw new Error("OPC UA browse expects msg.payload as an array");
45
+ }
46
+
47
+ if (!payload.length) {
48
+ return [{ name: "RootFolder", nodeID: ROOT_NODE_ID }];
49
+ }
50
+
51
+ return payload.map((item) => {
52
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
53
+ throw new Error("Each browse item must be an object");
54
+ }
55
+
56
+ return {
57
+ name: typeof item.name === "string" && item.name.trim() ? item.name.trim() : "",
58
+ nodeID: normalizeNodeId(item.nodeID || item.nodeId)
59
+ };
60
+ });
61
+ }
62
+
63
+ async function mapReference(session, reference) {
64
+ const childNodeId = normalizeNodeId(reference.nodeId);
65
+ const nodeClass = resolveNodeClassName(reference.nodeClass);
66
+ const browseName = extractBrowseName(reference.browseName, childNodeId);
67
+ const item = {
68
+ nodeID: childNodeId,
69
+ nodeClass,
70
+ browseName,
71
+ displayName: extractDisplayName(reference.displayName, browseName),
72
+ description: await readDescription(session, childNodeId)
73
+ };
74
+
75
+ const hasTypeDefinition = await readHasTypeDefinition(session, childNodeId);
76
+ if (hasTypeDefinition) {
77
+ item.hasTypeDefinition = hasTypeDefinition;
78
+ }
79
+
80
+ if (nodeClass === "Variable") {
81
+ item.value = await readValue(session, childNodeId);
82
+ item.dataType = await readDataType(session, childNodeId);
83
+ return item;
84
+ }
85
+
86
+ if (nodeClass === "Method") {
87
+ const definition = await readMethodArguments(session, childNodeId);
88
+ item.inputArguments = definition.inputArguments;
89
+ item.outputArguments = definition.outputArguments;
90
+ return item;
91
+ }
92
+
93
+ return item;
94
+ }
95
+
96
+ async function readHasTypeDefinition(session, nodeId) {
97
+ try {
98
+ const browseResult = await session.browse({
99
+ nodeId,
100
+ browseDirection: BrowseDirection.Forward,
101
+ referenceTypeId: makeNodeId(40, 0), // HasTypeDefinition
102
+ includeSubtypes: false,
103
+ resultMask: 63
104
+ });
105
+ const references = browseResult && Array.isArray(browseResult.references)
106
+ ? browseResult.references
107
+ : [];
108
+ if (!references.length) {
109
+ return null;
110
+ }
111
+
112
+ const reference = references[0];
113
+ const typeNodeId = normalizeNodeId(reference.nodeId);
114
+ return {
115
+ nodeID: typeNodeId,
116
+ browseName: extractBrowseName(reference.browseName, typeNodeId),
117
+ displayName: extractDisplayName(reference.displayName, typeNodeId)
118
+ };
119
+ } catch (error) {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ async function readBrowseName(session, nodeId, fallback) {
125
+ try {
126
+ const dataValue = await session.read({
127
+ nodeId,
128
+ attributeId: AttributeIds.BrowseName
129
+ });
130
+ const value = dataValue && dataValue.value ? dataValue.value.value : null;
131
+ if (value && value.name) {
132
+ return String(value.name);
133
+ }
134
+ } catch (error) {
135
+ // Use fallback below.
136
+ }
137
+
138
+ return String(fallback || nodeId);
139
+ }
140
+
141
+ async function readDescription(session, nodeId) {
142
+ try {
143
+ const dataValue = await session.read({
144
+ nodeId,
145
+ attributeId: AttributeIds.Description
146
+ });
147
+ const value = dataValue && dataValue.value ? dataValue.value.value : null;
148
+
149
+ if (typeof value === "string") {
150
+ return value;
151
+ }
152
+
153
+ if (value && typeof value.text === "string") {
154
+ return value.text;
155
+ }
156
+ } catch (error) {
157
+ // Return empty description when unavailable.
158
+ }
159
+
160
+ return "";
161
+ }
162
+
163
+ async function readValue(session, nodeId) {
164
+ try {
165
+ const dataValue = await session.read({
166
+ nodeId,
167
+ attributeId: AttributeIds.Value
168
+ });
169
+
170
+ if (!dataValue || !dataValue.value) {
171
+ return "";
172
+ }
173
+
174
+ const value = dataValue.value.value;
175
+ return value === undefined || value === null ? "" : value;
176
+ } catch (error) {
177
+ return "";
178
+ }
179
+ }
180
+
181
+ async function readDataType(session, nodeId) {
182
+ try {
183
+ const dataValue = await session.read({
184
+ nodeId,
185
+ attributeId: AttributeIds.DataType
186
+ });
187
+
188
+ const value = dataValue && dataValue.value ? dataValue.value.value : null;
189
+ if (!value) {
190
+ return "";
191
+ }
192
+
193
+ if (value.namespace === 0 && typeof value.value === "number") {
194
+ return DataType[value.value] || value.toString();
195
+ }
196
+
197
+ return value.toString();
198
+ } catch (error) {
199
+ return "";
200
+ }
201
+ }
202
+
203
+ async function readMethodArguments(session, nodeId) {
204
+ try {
205
+ const definition = await session.getArgumentDefinition(nodeId);
206
+ return {
207
+ inputArguments: normalizeMethodArguments(definition && definition.inputArguments),
208
+ outputArguments: normalizeMethodArguments(definition && definition.outputArguments)
209
+ };
210
+ } catch (error) {
211
+ return {
212
+ inputArguments: [],
213
+ outputArguments: []
214
+ };
215
+ }
216
+ }
217
+
218
+ function normalizeNodeId(nodeId) {
219
+ return coerceNodeId(nodeId).toString();
220
+ }
221
+
222
+ function resolveNodeClassName(nodeClass) {
223
+ if (!nodeClass && nodeClass !== 0) {
224
+ return "";
225
+ }
226
+
227
+ if (typeof nodeClass === "object" && typeof nodeClass.key === "string") {
228
+ return nodeClass.key;
229
+ }
230
+
231
+ if (typeof nodeClass === "string") {
232
+ return nodeClass;
233
+ }
234
+
235
+ return NodeClass[nodeClass] || String(nodeClass);
236
+ }
237
+
238
+ function extractBrowseName(browseName, fallback) {
239
+ if (browseName && typeof browseName.name === "string" && browseName.name) {
240
+ return browseName.name;
241
+ }
242
+
243
+ return String(fallback || "");
244
+ }
245
+
246
+ function extractDisplayName(displayName, fallback) {
247
+ if (displayName && typeof displayName.text === "string" && displayName.text) {
248
+ return displayName.text;
249
+ }
250
+
251
+ if (typeof displayName === "string" && displayName) {
252
+ return displayName;
253
+ }
254
+
255
+ return String(fallback || "");
256
+ }
257
+
258
+ function normalizeMethodArguments(argumentsList) {
259
+ if (!Array.isArray(argumentsList)) {
260
+ return [];
261
+ }
262
+
263
+ return argumentsList.map((argument, index) => ({
264
+ name: argument && argument.name ? String(argument.name) : "arg" + (index + 1),
265
+ dataType: resolveArgumentDataType(argument && argument.dataType),
266
+ description: argument && argument.description && typeof argument.description.text === "string"
267
+ ? argument.description.text
268
+ : ""
269
+ }));
270
+ }
271
+
272
+ function resolveArgumentDataType(dataType) {
273
+ if (!dataType) {
274
+ return "";
275
+ }
276
+
277
+ if (dataType.namespace === 0 && typeof dataType.value === "number") {
278
+ return DataType[dataType.value] || dataType.toString();
279
+ }
280
+
281
+ return dataType.toString();
282
+ }
283
+
284
+ const ROOT_NODE_ID = "i=84";
285
+
286
+ module.exports = {
287
+ browseNode,
288
+ normalizeBrowseRoots,
289
+ normalizeNodeId,
290
+ ROOT_NODE_ID
291
+ };
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ const { dataValueToItemResult, resolveNodeId } = require("../opcua-client-utils");
4
+
5
+ class OpcUaClientReadService {
6
+ async execute(node, msg, session, itemsResolver) {
7
+ const items = itemsResolver.ensureClientItems(node, msg, "OPC UA read");
8
+ const nodeIds = items.map((item) => resolveNodeId(item));
9
+ const values = await session.readVariableValue(nodeIds);
10
+ return values.map((dataValue, index) => dataValueToItemResult(items[index], dataValue));
11
+ }
12
+ }
13
+
14
+ module.exports = {
15
+ OpcUaClientReadService
16
+ };
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+
3
+ const { ClientSubscription } = require("node-opcua");
4
+
5
+ class OpcUaClientSubscriptionIdService {
6
+ async execute(node) {
7
+ const session = await node.connection.getSession();
8
+ const subscription = ClientSubscription.create(session, {
9
+ requestedPublishingInterval: 1000,
10
+ requestedLifetimeCount: 100,
11
+ requestedMaxKeepAliveCount: 10,
12
+ maxNotificationsPerPublish: 100,
13
+ publishingEnabled: true,
14
+ priority: 10
15
+ });
16
+
17
+ const subscriptionId = subscription.subscriptionId;
18
+ await subscription.terminate();
19
+ return subscriptionId;
20
+ }
21
+ }
22
+
23
+ module.exports = {
24
+ OpcUaClientSubscriptionIdService
25
+ };
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ClientMonitoredItem,
5
+ ClientSubscription,
6
+ TimestampsToReturn,
7
+ AttributeIds,
8
+ constructEventFilter
9
+ } = require("node-opcua");
10
+
11
+ const {
12
+ dataValueToItemResult,
13
+ dataValueToItemResultEvent,
14
+ resolveName,
15
+ resolveNodeId,
16
+ statusCodeToString
17
+ } = require("../opcua-client-utils");
18
+
19
+ class OpcUaClientSubscriptionService {
20
+ async startDataSubscription(node, msg, itemsResolver) {
21
+ const items = itemsResolver.ensureClientItems(node, msg, "OPC UA subscription");
22
+ await this.stop(node);
23
+
24
+ const session = await node.connection.getSession();
25
+ const subscription = ClientSubscription.create(session, {
26
+ requestedPublishingInterval: node.publishingInterval,
27
+ requestedLifetimeCount: 60,
28
+ requestedMaxKeepAliveCount: 10,
29
+ maxNotificationsPerPublish: 100,
30
+ publishingEnabled: true,
31
+ priority: 1
32
+ });
33
+
34
+ subscription.on("error", (error) => {
35
+ node.status({ fill: "red", shape: "ring", text: "subscription error" });
36
+ node.error(error);
37
+ });
38
+
39
+ node.subscription = subscription;
40
+ node.monitoredItems = items.map((item) => {
41
+ const monitoredItem = ClientMonitoredItem.create(
42
+ subscription,
43
+ { nodeId: resolveNodeId(item) },
44
+ {
45
+ samplingInterval: node.samplingInterval,
46
+ discardOldest: true,
47
+ queueSize: 1
48
+ },
49
+ TimestampsToReturn.Both
50
+ );
51
+
52
+ monitoredItem.on("changed", (dataValue) => {
53
+ const payload = dataValueToItemResult(item, dataValue);
54
+ node.status({
55
+ fill: "blue",
56
+ shape: "dot",
57
+ text: resolveName(item, payload.nodeID) + " changed"
58
+ });
59
+ node.send({
60
+ topic: payload.name,
61
+ payload,
62
+ opcua: {
63
+ mode: "subscription",
64
+ nodeID: payload.nodeID,
65
+ status: payload.status
66
+ }
67
+ });
68
+ });
69
+
70
+ monitoredItem.on("err", (message) => {
71
+ node.status({ fill: "red", shape: "ring", text: statusCodeToString(message) });
72
+ });
73
+
74
+ return monitoredItem;
75
+ });
76
+
77
+ return items;
78
+ }
79
+
80
+ async startEventSubscription(node, msg, itemsResolver) {
81
+ const items = itemsResolver.ensureClientItems(node, msg, "OPC UA subscription");
82
+ await this.stop(node);
83
+
84
+ const session = await node.connection.getSession();
85
+ const subscription = ClientSubscription.create(session, {
86
+ requestedPublishingInterval: node.publishingInterval,
87
+ requestedLifetimeCount: 60,
88
+ requestedMaxKeepAliveCount: 10,
89
+ maxNotificationsPerPublish: 100,
90
+ publishingEnabled: true,
91
+ priority: 2
92
+ });
93
+
94
+ subscription.on("error", (error) => {
95
+ node.status({ fill: "red", shape: "ring", text: "subscription error" });
96
+ node.error(error);
97
+ });
98
+
99
+ node.subscription = subscription;
100
+
101
+ const eventFilter = constructEventFilter([
102
+ "EventId",
103
+ "EventType",
104
+ "SourceName",
105
+ "SourceNode",
106
+ "Message",
107
+ "Severity",
108
+ "ActiveState",
109
+ "AckedState",
110
+ "ConfirmedState",
111
+ "Time"
112
+ ]);
113
+
114
+ node.monitoredItems = items.map((item) => {
115
+ const monitoredItem = ClientMonitoredItem.create(
116
+ subscription,
117
+ {
118
+ nodeId: resolveNodeId(item),
119
+ attributeId: AttributeIds.EventNotifier
120
+ },
121
+ {
122
+ samplingInterval: 0,
123
+ queueSize: 100,
124
+ discardOldest: true,
125
+ filter: eventFilter
126
+ },
127
+ TimestampsToReturn.Both
128
+ );
129
+
130
+ monitoredItem.on("changed", async (eventFields) => {
131
+ const payload = await dataValueToItemResultEvent(item, eventFields, session);
132
+ node.status({
133
+ fill: "blue",
134
+ shape: "dot",
135
+ text: resolveName(item, payload.nodeID) + " changed"
136
+ });
137
+ node.send({
138
+ topic: payload.name,
139
+ payload,
140
+ opcua: {
141
+ mode: "subscription",
142
+ nodeID: payload.nodeID,
143
+ status: payload.status
144
+ }
145
+ });
146
+ });
147
+
148
+ monitoredItem.on("err", (message) => {
149
+ node.status({ fill: "red", shape: "ring", text: statusCodeToString(message) });
150
+ });
151
+
152
+ return monitoredItem;
153
+ });
154
+
155
+ return items;
156
+ }
157
+
158
+ async stop(node) {
159
+ const subscription = node.subscription;
160
+ node.monitoredItems = [];
161
+ node.subscription = null;
162
+
163
+ if (subscription) {
164
+ await subscription.terminate();
165
+ }
166
+ }
167
+ }
168
+
169
+ module.exports = {
170
+ OpcUaClientSubscriptionService
171
+ };
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+
3
+ const { DataType, coerceNodeId } = require("node-opcua");
4
+ const {
5
+ buildVariantFromItem,
6
+ dataValueToItemResult,
7
+ normalizeTypeName,
8
+ resolveNodeId,
9
+ statusCodeToString
10
+ } = require("../opcua-client-utils");
11
+
12
+ class OpcUaClientWriteService {
13
+ async execute(node, msg, session, itemsResolver) {
14
+ const items = itemsResolver.ensureWriteItems(node, msg);
15
+ const results = [];
16
+
17
+ for (const item of items) {
18
+ const nodeId = resolveNodeId(item);
19
+
20
+ try {
21
+ const explicitType = normalizeTypeName(item.type);
22
+ const builtInType = await session.getBuiltInDataType(coerceNodeId(nodeId));
23
+ const typeName = explicitType || DataType[builtInType];
24
+ const variant = buildVariantFromItem(item, typeName);
25
+ const statusCode = await session.writeSingleNode(nodeId, variant);
26
+ const dataValue = await session.readVariableValue(nodeId);
27
+ const result = dataValueToItemResult(item, dataValue);
28
+
29
+ if (statusCode && statusCode.name && statusCode.name !== "Good") {
30
+ result.status = statusCodeToString(statusCode);
31
+ }
32
+
33
+ results.push(result);
34
+ } catch (itemError) {
35
+ results.push({
36
+ name: item.name || nodeId,
37
+ nodeID: nodeId,
38
+ value: item.value,
39
+ type: normalizeTypeName(item.type) || null,
40
+ status: itemError.message,
41
+ sourceTimestamp: null,
42
+ serverTimestamp: null
43
+ });
44
+ }
45
+ }
46
+
47
+ return results;
48
+ }
49
+ }
50
+
51
+ module.exports = {
52
+ OpcUaClientWriteService
53
+ };
@@ -0,0 +1,80 @@
1
+ <script type="text/javascript">
2
+ (function () {
3
+ function toggleCredentials() {
4
+ var authType = $("#node-config-input-authType").val();
5
+ $(".opcua-client-auth-row").toggle(authType === "username");
6
+ }
7
+
8
+ RED.nodes.registerType("opcua-client-config", {
9
+ category: "config",
10
+ defaults: {
11
+ name: { value: "" },
12
+ endpoint: { value: "opc.tcp://localhost:4840", required: true },
13
+ securityPolicy: { value: "None", required: true },
14
+ securityMode: { value: "None", required: true },
15
+ authType: { value: "anonymous", required: true }
16
+ },
17
+ credentials: {
18
+ username: { type: "text" },
19
+ password: { type: "password" }
20
+ },
21
+ label: function () {
22
+ return this.name || this.endpoint || "opcua-client-config";
23
+ },
24
+ oneditprepare: function () {
25
+ $("#node-config-input-authType").on("change", toggleCredentials);
26
+ toggleCredentials();
27
+ }
28
+ });
29
+ })();
30
+ </script>
31
+
32
+ <script type="text/html" data-template-name="opcua-client-config">
33
+ <div class="form-row">
34
+ <label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
35
+ <input type="text" id="node-config-input-name" placeholder="OPC UA Client">
36
+ </div>
37
+ <div class="form-row">
38
+ <label for="node-config-input-endpoint"><i class="fa fa-plug"></i> Endpoint</label>
39
+ <input type="text" id="node-config-input-endpoint" placeholder="opc.tcp://localhost:4840">
40
+ </div>
41
+ <div class="form-row">
42
+ <label for="node-config-input-securityPolicy"><i class="fa fa-lock"></i> Security Policy</label>
43
+ <select id="node-config-input-securityPolicy">
44
+ <option value="None">None</option>
45
+ <option value="Basic128Rsa15">Basic128Rsa15</option>
46
+ <option value="Basic256">Basic256</option>
47
+ <option value="Basic256Sha256">Basic256Sha256</option>
48
+ <option value="Aes128_Sha256_RsaOaep">Aes128_Sha256_RsaOaep</option>
49
+ <option value="Aes256_Sha256_RsaPss">Aes256_Sha256_RsaPss</option>
50
+ </select>
51
+ </div>
52
+ <div class="form-row">
53
+ <label for="node-config-input-securityMode"><i class="fa fa-shield"></i> Security Mode</label>
54
+ <select id="node-config-input-securityMode">
55
+ <option value="None">None</option>
56
+ <option value="Sign">Sign</option>
57
+ <option value="SignAndEncrypt">SignAndEncrypt</option>
58
+ </select>
59
+ </div>
60
+ <div class="form-row">
61
+ <label for="node-config-input-authType"><i class="fa fa-user"></i> Auth</label>
62
+ <select id="node-config-input-authType">
63
+ <option value="anonymous">Anonymous</option>
64
+ <option value="username">Username/Password</option>
65
+ </select>
66
+ </div>
67
+ <div class="form-row opcua-client-auth-row">
68
+ <label for="node-config-input-username"><i class="fa fa-user-circle"></i> Username</label>
69
+ <input type="text" id="node-config-input-username">
70
+ </div>
71
+ <div class="form-row opcua-client-auth-row">
72
+ <label for="node-config-input-password"><i class="fa fa-key"></i> Password</label>
73
+ <input type="password" id="node-config-input-password">
74
+ </div>
75
+ </script>
76
+
77
+ <script type="text/html" data-help-name="opcua-client-config">
78
+ <p>Shared OPC UA client connection for read, write and method nodes.</p>
79
+ <p>This is a Node-RED configuration node, using <code>category: "config"</code> and the <code>node-config-input-*</code> field pattern described in the official docs.</p>
80
+ </script>