-
Notifications
You must be signed in to change notification settings - Fork 12
/
mqtt.ts
79 lines (67 loc) · 2.46 KB
/
mqtt.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import {MqttClient} from "mqtt/types/lib/client";
import {Logging} from "homebridge";
const mqtt = require('mqtt');
export class Mqtt {
private readonly log: Logging;
private readonly config: MqttConfig;
private readonly client: MqttClient;
constructor(config: MqttConfig, log: Logging) {
this.log = log;
this.config = config;
if (!config || !config.broker) {
return;
}
const options: {username?: string, password?: string} = {};
if (config.username) {
options.username = config.username;
if (config.password) {
options.password = config.password;
}
}
this.client = mqtt.connect(config.broker, options);
this.client.on('connect', () => {
this.log.debug('Connected to MQTT broker');
});
this.client.on('error', (error: Error) => {
this.log.error('MQTT error: ' + error.message);
});
}
public sendMessageOnTopic(message: string, topic: string): void {
if (this.client && this.client.connected) {
this.client.publish(this.config.topicPrefix + '/' + topic, message);
}
}
private onConnection(): Promise<void> {
return new Promise<void>((resolve, reject) => {
let interval = setInterval(() => {
if (this.client.connected) {
clearInterval(interval);
resolve();
}
}, 10);
});
}
public subscribeToTopic(topic: string, callback: (payload: {enabled: boolean}) => void): void {
this.onConnection().then(() => {
this.log.debug('Subscribing to: ' + this.config.topicPrefix + '/' + topic);
this.client.subscribe(this.config.topicPrefix + '/' + topic, (err, granted) => {
console.log(granted);
if (!err) {
if (granted && granted.length === 1) {
this.client.on('message', (messageTopic, messagePayload, packet) => {
if (messageTopic === this.config.topicPrefix + '/' + topic) {
callback(JSON.parse(messagePayload.toString()) as any);
}
});
}
}
});
});
}
}
export interface MqttConfig {
broker: string;
username: string;
password: string;
topicPrefix: string;
}