-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMqttService.ts
69 lines (61 loc) · 1.54 KB
/
MqttService.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
import mqtt, { MqttClient, QoS } from "mqtt";
export class MqttService {
constructor(private mqttClient: MqttClient) {
}
static connect(config: MqttConfig, clientId: string, username: string, password: string): Promise<MqttService> {
return new Promise((resolve, reject) => {
const mqttClient = mqtt.connect(config.brokerUrl, {
clientId: clientId,
username: username,
password: password,
reconnectPeriod: 0
});
let lastError: Error | undefined;
mqttClient.on("connect", () => {
console.log(`Mqtt ${config.brokerUrl} connect, clientId ${clientId}`);
resolve(new MqttService(mqttClient));
});
mqttClient.on("close", () => {
console.log(`Mqtt ${config.brokerUrl} close`);
reject(lastError || new Error(`Failed to connect ${clientId}`))
});
mqttClient.on("offline", () => {
console.log(`Mqtt ${config.brokerUrl} offline`);
});
mqttClient.on("reconnect", () => {
console.log(`Mqtt ${config.brokerUrl} reconnect`);
});
mqttClient.on("error", (err) => {
if (err) {
console.error(err);
lastError = err;
}
});
});
}
publish(topic: string, qos: QoS, payload: Buffer): Promise<void> {
return new Promise((resolve, reject) => {
this.mqttClient.publish(
topic,
payload,
{ qos },
(err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
close() {
return new Promise<void>((resolve) => {
this.mqttClient.end(false, () => {
resolve();
});
});
}
}
export interface MqttConfig {
brokerUrl: string;
}