Skip to content

Instantly share code, notes, and snippets.

@danielpeintner
Created June 15, 2023 11:35
Show Gist options
  • Save danielpeintner/3cc9fb61f894a069a92038cad22f7ae9 to your computer and use it in GitHub Desktop.
Save danielpeintner/3cc9fb61f894a069a92038cad22f7ae9 to your computer and use it in GitHub Desktop.
mashup-opcua-counter-v1
npm install @node-wot/core
npm install @node-wot/binding-opcua
npm install @node-wot/binding-http
# Demo
## 1. Open counter website
Open http://plugfest.thingweb.io/examples/counter.html and listen on change events.
Note: Doing so the counter value will be updated in the UI once "someone" changes the value
## 2. Start OPCUA demo
node opcua-mashup-counter.js
Note: it reads the pumpvalue every X seconds and
* increments the counter IF the pumpspeed is greater than 200
* decrements the counter IF the pumpspeed is equal/lower than 200
// OPCUA Mashup
Servient = require("@node-wot/core").Servient;
OPCUAClientFactory = require("@node-wot/binding-opcua").OPCUAClientFactory;
HttpClientFactory = require("@node-wot/binding-http").HttpClientFactory;
Helpers = require("@node-wot/core").Helpers;
const thingDescriptionOPCUA = {
"@context": "https://www.w3.org/2019/wot/td/v1",
"@type": ["Thing"],
securityDefinitions: { nosec_sc: { scheme: "nosec" } },
security: "nosec_sc",
title: "servient",
description: "Demo OPCUA Server",
properties: {
pumpSpeed: {
description: "the pump speed",
type: "number",
forms: [
{
href: "opc.tcp://opcuademo.sterfive.com:26543", // endpoint
op: ["readproperty", "observeproperty"],
"opcua:nodeId": "ns=1;s=PumpSpeed",
},
],
},
},
};
// > 200 increment
// <= 200 decrement
async function updateCounter(thingOPCUA, thingHttpCounter) {
const content = await thingOPCUA.readProperty("pumpSpeed");
const value = await content.value();
if (value != null) {
const json = (value).valueOf();
console.log("OPCUA Pump Speed is", json);
if (json > 200) {
console.log("\t increment HTTP counter");
await thingHttpCounter.invokeAction("increment");
} else {
console.log("\t decrement HTTP counter");
await thingHttpCounter.invokeAction("decrement");
}
}
}
const servient = new Servient();
servient.addClientFactory(new OPCUAClientFactory());
servient.addClientFactory(new HttpClientFactory(null));
let wotHelper = new Helpers(servient);
wotHelper
.fetch("http://plugfest.thingweb.io:8083/counter")
.then(async (thingDescriptionCounter) => {
try {
const wot = await servient.start();
// OPCUA
const thingOPCUA = await wot.consume(thingDescriptionOPCUA);
// HTTP counter
const thingHttpCounter = await wot.consume(thingDescriptionCounter);
// read pumpSpeed every 5 secs and update counter accordingly
setInterval(() => {
updateCounter(thingOPCUA, thingHttpCounter);
}, 5000);
} catch (err) {
console.error("Script error:", err);
}
})
.catch((err) => {
console.error("Fetch error:", err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment