-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathsimple_client_ts.ts
109 lines (95 loc) · 2.88 KB
/
simple_client_ts.ts
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import {
AttributeIds,
OPCUAClient,
DataValue,
BrowseResult,
ReferenceDescription,
TimestampsToReturn,
StatusCodes,
DataType,
} from "node-opcua";
const endpointUrl = "opc.tcp://opcuademo.sterfive.com:26543";
const nodeId = "ns=7;s=Scalar_Simulation_Double";
async function main() {
try {
const client = OPCUAClient.create({
endpointMustExist: false,
connectionStrategy: {
maxRetry: 2,
initialDelay: 2000,
maxDelay: 10 * 1000,
},
});
client.on("backoff", () => console.log("retrying connection"));
await client.withSessionAsync(endpointUrl, async (session) => {
const browseResult: BrowseResult = (await session.browse(
"RootFolder"
)) as BrowseResult;
console.log(
browseResult.references
.map((r: ReferenceDescription) => r.browseName.toString())
.join("\n")
);
const dataValue = await session.read({
nodeId,
attributeId: AttributeIds.Value,
});
if (dataValue.statusCode !== StatusCodes.Good) {
console.log("Could not read ", nodeId);
}
console.log(` value of ${nodeId.toString()} = ${dataValue.value.toString()}`);
// step 5: install a subscription and monitored item
const subscription = await session.createSubscription2({
requestedPublishingInterval: 1000,
requestedLifetimeCount: 100,
requestedMaxKeepAliveCount: 20,
maxNotificationsPerPublish: 10,
publishingEnabled: true,
priority: 10,
});
subscription
.on("started", () =>
console.log(
"subscription started - subscriptionId=",
subscription.subscriptionId
)
)
.on("keepalive", () => console.log("keepalive"))
.on("terminated", () => console.log("subscription terminated"));
const monitoredItem = await subscription.monitor(
{
nodeId,
attributeId: AttributeIds.Value,
},
{
samplingInterval: 100,
discardOldest: true,
queueSize: 10,
},
TimestampsToReturn.Both
);
monitoredItem.on("changed", (dataValue: DataValue) => {
console.log(` Temperature = ${dataValue.value.value.toString()}`);
});
await new Promise((resolve) => setTimeout(resolve, 10000));
await subscription.terminate();
const statusCode = await session.write({
nodeId: "ns=7;s=Scalar_Static_Double",
attributeId: AttributeIds.Value,
value: {
statusCode: StatusCodes.Good,
sourceTimestamp: new Date(),
value: {
dataType: DataType.Double,
value: 25.0,
},
},
});
console.log("statusCode = ", statusCode.toString());
console.log(" closing session");
});
} catch (err) {
console.log("Error !!!", err);
}
}
main();