Skip to content

Commit

Permalink
Better nullchecking for mqtt, should fix #98
Browse files Browse the repository at this point in the history
  • Loading branch information
beele committed Jan 8, 2022
1 parent b9e34ac commit a41bfb6
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
12 changes: 6 additions & 6 deletions src/utils/mqtt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,24 @@ 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);
}
}

private onConnection(): Promise<void> {
return new Promise<void>((resolve, reject) => {
let interval = setInterval(() => {
if (this.client && this.client.connected) {
if (this.client?.connected) {
clearInterval(interval);
resolve();
}
Expand All @@ -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);
}
Expand Down

0 comments on commit a41bfb6

Please sign in to comment.