From a41bfb6fb701fa0068b62a2066d880604001a39c Mon Sep 17 00:00:00 2001 From: Kevin Van den Abeele Date: Sat, 8 Jan 2022 07:42:48 +0100 Subject: [PATCH] Better nullchecking for mqtt, should fix #98 --- package.json | 2 +- src/utils/mqtt.ts | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 722fbd6..30111c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "homebridge-unifi-protect-camera-motion", - "version": "0.4.7", + "version": "0.4.8", "description": "Unifi Protect cameras & motion sensors for Homebridge. AI enabled Motion detection for Unifi Protect cameras.", "main": "src/index.js", "scripts": { diff --git a/src/utils/mqtt.ts b/src/utils/mqtt.ts index b897eab..ea017d2 100644 --- a/src/utils/mqtt.ts +++ b/src/utils/mqtt.ts @@ -27,16 +27,16 @@ export class Mqtt { } this.client = mqtt.connect(config.broker, options); - this.client.on('connect', () => { + this.client?.on('connect', () => { this.log.debug('Connected to MQTT broker'); }); - this.client.on('error', (error: Error) => { + 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) { + if (this.client?.connected) { this.client.publish(this.config.topicPrefix + '/' + topic, message); } } @@ -44,7 +44,7 @@ export class Mqtt { private onConnection(): Promise { return new Promise((resolve, reject) => { let interval = setInterval(() => { - if (this.client && this.client.connected) { + if (this.client?.connected) { clearInterval(interval); resolve(); } @@ -55,11 +55,11 @@ export class Mqtt { 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) => { + 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) => { + this.client?.on('message', (messageTopic, messagePayload, packet) => { if (messageTopic === this.config.topicPrefix + '/' + topic) { callback(JSON.parse(messagePayload.toString()) as any); }