blob: 71ba5537faf3981d14fee43e71759b49608cf1eb (
plain)
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
|
//
// ~~~ 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", (receivedTopic, message) => {
if (receivedTopic !== mqttTopic) return
callback(message)
})
}
|