From f3b81811077dfe09bb4331c7696c80150114a2a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Lov=C3=A9n?= Date: Fri, 29 Jan 2021 21:25:34 +0100 Subject: [PATCH] Publish availability of devices --- plejd/MqttClient.js | 16 ++++++++++++++++ plejd/main.js | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/plejd/MqttClient.js b/plejd/MqttClient.js index 4747d30..5cde2f2 100644 --- a/plejd/MqttClient.js +++ b/plejd/MqttClient.js @@ -15,6 +15,7 @@ const getSubscribePath = () => `${discoveryPrefix}/+/${nodeId}/#`; const getPath = ({ id, type }) => `${discoveryPrefix}/${type}/${nodeId}/${id}`; const getConfigPath = (plug) => `${getPath(plug)}/config`; const getStateTopic = (plug) => `${getPath(plug)}/state`; +const getAvailabilityTopic = plug => `${getPath(plug)}/availability`; const getCommandTopic = (plug) => `${getPath(plug)}/set`; const getSceneEventTopic = () => 'plejd/event/scene'; @@ -24,6 +25,7 @@ const getDiscoveryPayload = (device) => ({ unique_id: `light.plejd.${device.name.toLowerCase().replace(/ /g, '')}`, state_topic: getStateTopic(device), command_topic: getCommandTopic(device), + availability_topic: getAvailabilityTopic(device), optimistic: false, brightness: `${device.dimmable}`, device: { @@ -125,6 +127,16 @@ class MqttClient extends EventEmitter { this.client.reconnect(); } + disconnect(callback) { + this.devices.forEach((device) => { + this.client.publish( + getAvailabilityTopic(device), + "offline" + ); + }); + this.client.end(callback); + } + discover(devices) { this.devices = devices; @@ -142,6 +154,9 @@ class MqttClient extends EventEmitter { self.deviceMap[device.id] = payload.unique_id; self.client.publish(getConfigPath(device), JSON.stringify(payload)); + setTimeout(() => { + self.client.publish(getAvailabilityTopic(device), "online"); + }, 2000); }); } @@ -178,6 +193,7 @@ class MqttClient extends EventEmitter { } this.client.publish(getStateTopic(device), payload); + this.client.publish(getAvailabilityTopic(device), "online"); } sceneTriggered(scene) { diff --git a/plejd/main.js b/plejd/main.js index ae77952..de3accd 100644 --- a/plejd/main.js +++ b/plejd/main.js @@ -27,6 +27,12 @@ async function main() { ); const client = new MqttClient(config.mqttBroker, config.mqttUsername, config.mqttPassword); + ['SIGINT', 'SIGHUP', 'SIGTERM'].forEach(signal => { + process.on(signal, () => { + client.disconnect(() => process.exit(0)); + }); + }); + plejdApi.login().then(() => { // load all sites and find the one that we want (from config) plejdApi.getSites().then((site) => {