-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqttx.ts
38 lines (31 loc) · 1.13 KB
/
mqttx.ts
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
import mqtt from 'mqtt';
import { msg } from './index.js';
const mqttHost = "pi4c"
const mqttPort: number = 1883 // 1883 is the default port for MQTT
export function mqttListner(subscribe: string, handler: (payload: object) => void, timeout = 1000 * 60 * 5) {
try {
const seen = new Set<string>();
const client = mqtt.connect(`mqtt://${mqttHost}:${mqttPort}`);
// Subscribe to the device status topic
// client.subscribe('tele/+/LWT'); -- for online/offline we care
client.subscribe(subscribe);
// Handle received MQTT messages
client.on('message', async (topic, message) => {
// Must be a discovery message
if (seen.has(topic)) return;
seen.add(topic);
const payload = JSON.parse(message.toString());
handler(payload);
});
setTimeout(() => {
console.warn(`Timeout ${subscribe}`)
client.unsubscribe(subscribe);
client.end();
}, timeout); // 5 minutes
}
catch (e: any) {
msg('mqttListner', e.message)
debugger;
// throw e;
}
}