From 56ccdf34d5a820fbdabb3674b2392b9d1e2b1ecf Mon Sep 17 00:00:00 2001 From: Autumn Date: Mon, 11 May 2026 21:31:22 +0100 Subject: [app] added basic MQTT support --- src/lib/mqtt.ts | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/lib/mqtt.ts (limited to 'src/lib') diff --git a/src/lib/mqtt.ts b/src/lib/mqtt.ts new file mode 100644 index 0000000..f7dd82c --- /dev/null +++ b/src/lib/mqtt.ts @@ -0,0 +1,53 @@ +// +// ~~~ mqtt connector +// + +// imports +import mqtt from "mqtt" +import loadDotenv from "./dotenv.ts" + +const dotenv = loadDotenv() + +// client connector +function _client() { + let client + + if (global.mqttClient) { + + client = global.mqttClient + + } else { + + client = mqtt.connect(dotenv?.MQTT_HOST) + global.mqttClient = client + + } + + return client +} + +// send message +export async function sendMessage(topic, message) { + + const client = _client() + const mqttTopic = `zigbee2mqtt/${topic}` // todo: don't hard-code zigbee2mqtt + + const messageResponse = await client.publishAsync(mqttTopic, message) + + return messageResponse +} + +// add listener +export async function addListener(topic, callback) { + + const client = _client() + const mqttTopic = `zigbee2mqtt/${topic}` // todo: don't hard-code zigbee2mqtt + + await client.subscribeAsync(mqttTopic) + + // todo: error handling + + client.on("message", (_, message) => { + callback(message) + }) +} -- cgit v1.3