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"; const main = () => { console.log("Start") // Create an mqtt client for broker localhost:1883 with a random client id const client = connect(broker, { clientId: 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", testparam1.toString()); } const testoperation2 = (input) => { console.log(`This is a result of testoperation 2 with input ${input}`); testparam1--; client.publish("testasset/testparam1", testparam1.toString()); } const testoperation3 = (input) => { client.publish("testasset/testoperation3/result", JSON.stringify({message: "Wuh", input, error: false})); } // Asset listeners client.on("message", (topic, message) => { switch (topic) { case "testasset/testparam2/write": testparam2 = /(true|1)/i.test(message.toString()); client.publish("testasset/testparam2", testparam2.toString()); 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/#"); setInterval(() => { client.publish("testasset/testparam1", testparam1.toString()); client.publish("testasset/testparam2", 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();