-
Notifications
You must be signed in to change notification settings - Fork 0
/
opcua-subscription.js
70 lines (54 loc) · 2.33 KB
/
opcua-subscription.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// See example https://github.com/node-opcua/node-opcua/blob/af235f19e9e353fa748c11009b1300f76026fb28/packages/playground/client_with_simple_subscription.js#L83
module.exports = function (RED) {
var core = require('./core');
var opcua = require('node-opcua');
function opcUaSubscriptionNode(args) {
RED.nodes.createNode(this, args);
const opcuaclientnode = RED.nodes.getNode(args.client);
let node = this;
node.nodeId = args.nodeid;
node.samplinginterval = args.samplinginterval;
node.on('close', onNodeClosed);
let monitoredItem = new opcua.ClientMonitoredItem();
core.eventEmitter.on('subscription_created', onSubscriptionCreated);
function onSubscriptionCreated(connectionId) {
const existingClient = core.opcClients[connectionId];
let subscription = existingClient.session.subscription;
if (monitoredItem?.monitoredItemId) return;
monitorItem(subscription);
}
async function onNodeClosed(done) {
core.eventEmitter.removeListener('subscription_created', onSubscriptionCreated);
if (monitoredItem?.monitoredItemId) {
monitoredItem.removeListener("changed", onMonitoredItemDataChanged);
monitoredItem.terminate();
monitoredItem = null;
}
done();
}
function monitorItem(subscription) {
const itemToMonitor = {
nodeId: node.nodeId,
attributeId: opcua.AttributeIds.Value
};
const parameters = {
samplingInterval: node.samplinginterval,
discardOldest: true,
queueSize: 10
};
monitoredItem = opcua.ClientMonitoredItem.create(
subscription,
itemToMonitor,
parameters,
opcua.TimestampsToReturn.Both
);
monitoredItem.on("changed", onMonitoredItemDataChanged);
}
function onMonitoredItemDataChanged(dataValue){
const dataValueString = JSON.stringify(dataValue);
const dataValueObj = JSON.parse(dataValueString);
node.send({ payload: dataValueObj });
}
}
RED.nodes.registerType("opcua-subscription", opcUaSubscriptionNode);
}