81 lines
2.7 KiB
JavaScript
81 lines
2.7 KiB
JavaScript
import { connect } from "mqtt";
|
|
import { v4 } from "uuid";
|
|
|
|
// Is docker?
|
|
const isDocker = process.env.AM_I_IN_A_DOCKER_CONTAINER ?? false;
|
|
const broker = isDocker ? "mqtt://mqttbroker:1883" : "mqtt://localhost:1883";
|
|
|
|
// Start
|
|
const main = () => {
|
|
// Create an mqtt client for broker localhost:1883 with a random client id
|
|
let client = connect(broker, {
|
|
clientId: "testasset-" + v4(),
|
|
});
|
|
|
|
// Asset stuff
|
|
let testparam1 = 5;
|
|
let testparam2 = true;
|
|
const testoperation1 = () => {
|
|
console.log("This is a result of testoperation 1");
|
|
testparam1++;
|
|
client.publish("testasset/testparam1/value", testparam1.toString());
|
|
}
|
|
const testoperation2 = (input) => {
|
|
console.log(`This is a result of testoperation 2 with input ${input}`);
|
|
testparam1--;
|
|
client.publish("testasset/testparam1/value", testparam1.toString());
|
|
|
|
}
|
|
const testoperation3 = (input) => {
|
|
console.log(`This is a result of testoperation 3 with input ${input}`);
|
|
client.publish("testasset/testoperation3/result", JSON.stringify({ message: "Wuh", input, valueFromInput: input.TestInput, error: false }));
|
|
}
|
|
|
|
// Asset listeners
|
|
|
|
client.on("message", (topic, message) => {
|
|
// console.log(`${topic}: ${message.toString()}`);
|
|
switch (topic) {
|
|
case "testasset/testparam2/set":
|
|
const value = /^(true|1)$/i.test(message.toString());
|
|
console.log(`Testparam2 changed to ${value}`);
|
|
testparam2 = value;
|
|
break;
|
|
case "testasset/testoperation1":
|
|
testoperation1();
|
|
break;
|
|
case "testasset/testoperation2":
|
|
testoperation2(JSON.parse(message.toString()).TestInput);
|
|
break;
|
|
case "testasset/testoperation3":
|
|
testoperation3(message.toString());
|
|
break;
|
|
}
|
|
});
|
|
client.on("connect", () => {
|
|
console.log("Connected to broker");
|
|
});
|
|
client.on("error", (error) => {
|
|
console.error(error);
|
|
});
|
|
client.on("close", () => {
|
|
console.log("Connection to broker closed");
|
|
});
|
|
|
|
client.subscribe("testasset/testoperation1");
|
|
client.subscribe("testasset/testoperation2");
|
|
client.subscribe("testasset/testoperation3");
|
|
client.subscribe("testasset/+/set");
|
|
|
|
setInterval(() => {
|
|
client.publish("testasset/testparam1/value", testparam1.toString());
|
|
client.publish("testasset/testparam2/value", testparam2.toString());
|
|
}, 1000);
|
|
|
|
setInterval(() => {
|
|
client.publish("testasset/testevent", "Timer ran down")
|
|
}, 10000);
|
|
client.publish("testasset/hello", "Hello World");
|
|
}
|
|
if (isDocker) setTimeout(main.bind(this), 3000);
|
|
else main(); |