From 5a2129036453232f53f781045955ab970448b438 Mon Sep 17 00:00:00 2001 From: faanskit Date: Sat, 1 May 2021 19:41:29 +0200 Subject: [PATCH] Added support for WRT-10 as a Device Automation --- plejd/DeviceRegistry.js | 46 +++++++++++++++++++++++ plejd/MqttClient.js | 45 +++++++++++++++++++++++ plejd/PlejdAddon.js | 8 ++++ plejd/PlejdApi.js | 61 ++++++++++++++++++++----------- plejd/PlejdBLEHandler.js | 19 ++++++++++ plejd/PlejdDeviceCommunication.js | 2 + plejd/constants.js | 1 + plejd/types/DeviceRegistry.d.ts | 14 +++++++ 8 files changed, 174 insertions(+), 22 deletions(-) diff --git a/plejd/DeviceRegistry.js b/plejd/DeviceRegistry.js index a031752..bd2e0d8 100644 --- a/plejd/DeviceRegistry.js +++ b/plejd/DeviceRegistry.js @@ -22,12 +22,29 @@ class DeviceRegistry { outputDevices = {}; /** @private @type {import('types/DeviceRegistry').OutputDevices} */ sceneDevices = {}; + /** @private @type {import('types/DeviceRegistry').InputDevices} */ + inputDevices = {}; /** @param device {import('./types/ApiSite').Device} */ addPhysicalDevice(device) { this.devices[device.deviceId] = device; } + /** @param inputDevice {import('types/DeviceRegistry').InputDevice} */ + addInputDevice(inputDevice) { + this.inputDevices = { + ...this.inputDevices, + [inputDevice.uniqueId]: inputDevice, + }; + + logger.verbose( + `Added/updated input device: ${JSON.stringify(inputDevice)}. ${ + Object.keys(this.inputDevices).length + } output devices in total.`, + ); + this.outputUniqueIdByBleOutputAddress[`${inputDevice.bleOutputAddress}_${inputDevice.input}`] = inputDevice.uniqueId; + }; + /** @param outputDevice {import('types/DeviceRegistry').OutputDevice} */ addOutputDevice(outputDevice) { if (outputDevice.hiddenFromIntegrations || outputDevice.hiddenFromRoomList) { @@ -84,6 +101,7 @@ class DeviceRegistry { clearPlejdDevices() { this.devices = {}; this.outputDevices = {}; + this.inputDevices = {}; this.outputDeviceUniqueIdsByRoomId = {}; this.outputUniqueIdByBleOutputAddress = {}; } @@ -100,6 +118,13 @@ class DeviceRegistry { return Object.values(this.outputDevices); } + /** + * @returns {import('./types/DeviceRegistry').InputDevice[]} + */ + getAllInputDevices() { + return Object.values(this.inputDevices); + } + /** * @returns {import('./types/DeviceRegistry').OutputDevice[]} */ @@ -119,11 +144,23 @@ class DeviceRegistry { return this.outputDevices[uniqueOutputId]; } + /** + * @param {string} uniqueInputId + */ + getInputDevice(uniqueInputId) { + return this.inputDevices[uniqueInputId]; + } + /** @returns {import('./types/DeviceRegistry').OutputDevice} */ getOutputDeviceByBleOutputAddress(bleOutputAddress) { return this.outputDevices[this.outputUniqueIdByBleOutputAddress[bleOutputAddress]]; } + /** @returns {import('./types/DeviceRegistry').InputDevice} */ + getInputDeviceByBleOutputAddress(bleInputAddress, inputButton) { + return this.inputDevices[this.outputUniqueIdByBleOutputAddress[`${bleInputAddress}_${inputButton}`]]; + } + /** @returns {string[]} */ getOutputDeviceIdsByRoomId(roomId) { return this.outputDeviceUniqueIdsByRoomId[roomId]; @@ -133,6 +170,10 @@ class DeviceRegistry { return (this.outputDevices[uniqueOutputId] || {}).name; } + getInputDeviceName(uniqueInputId) { + return (this.inputDevices[uniqueInputId] || {}).name; + } + /** * @param {string } deviceId The physical device serial number * @return {import('./types/ApiSite').Device} @@ -171,6 +212,11 @@ class DeviceRegistry { return `${deviceId}_${outputIndex}`; } + // eslint-disable-next-line class-methods-use-this + getUniqueInputId(deviceId, inputIndex) { + return `${deviceId}_${inputIndex}`; + } + /** @param apiSite {import('./types/ApiSite').ApiSite} */ setApiSite(apiSite) { this.apiSite = apiSite; diff --git a/plejd/MqttClient.js b/plejd/MqttClient.js index c316798..4f1fb40 100644 --- a/plejd/MqttClient.js +++ b/plejd/MqttClient.js @@ -1,4 +1,5 @@ const EventEmitter = require('events'); +// @ts-ignore const mqtt = require('mqtt'); const Configuration = require('./Configuration'); @@ -35,6 +36,7 @@ const getTopicName = ( /** @type {'config' | 'state' | 'availability' | 'set'} */ topicType, ) => `${getBaseTopic(plug)}/${topicType}`; +const getButtonEventTopic = (deviceId) => `${getTopicName({ uniqueId: `${deviceId}`, type: 'device_automation' }, 'state')}`; const getSceneEventTopic = (sceneId) => `${getTopicName({ uniqueId: `${sceneId}_trigger`, type: 'device_automation' }, 'state')}`; const getSubscribePath = () => `${discoveryPrefix}/+/${nodeId}/#`; @@ -89,6 +91,28 @@ const getSceneDiscoveryPayload = ( retain: false, }); +const getInputDeviceTriggerDiscoveryPayload = ( + /** @type {import('./types/DeviceRegistry').InputDevice} */ inputDevice, +) => ({ + automation_type: 'trigger', + payload: `${inputDevice.input}`, + '~': getBaseTopic({ + uniqueId: inputDevice.deviceId, + type: 'device_automation', + }), + qos: 1, + topic: `~/${TOPICS.STATE}`, + type: 'button_short_press', + subtype: `button_${inputDevice.input+1}`, + device: { + identifiers: `${inputDevice.deviceId}`, + manufacturer: 'Plejd', + model: inputDevice.typeName, + name: inputDevice.name, + }, +}); + + const getSceneDeviceTriggerhDiscoveryPayload = ( /** @type {import('./types/DeviceRegistry').OutputDevice} */ sceneDevice, ) => ({ @@ -288,6 +312,23 @@ class MqttClient extends EventEmitter { }, 2000); }); + const allInputDevices = this.deviceRegistry.getAllInputDevices(); + logger.info(`Sending discovery for ${allInputDevices.length} Plejd input devices`); + allInputDevices.forEach((inputDevice) => { + logger.debug(`Sending discovery for ${inputDevice.name}`); + const inputInputPayload = getInputDeviceTriggerDiscoveryPayload(inputDevice); + logger.info( + `Discovered ${inputDevice.typeName} (${inputDevice.type}) named ${inputDevice.name} (${inputDevice.bleOutputAddress} : ${inputDevice.uniqueId}).`, + ); + logger.verbose(`Publishing ${getTopicName(inputDevice, 'config')} with payload ${JSON.stringify(inputInputPayload)}`); + + this.client.publish(getTopicName(inputDevice, 'config'), JSON.stringify(inputInputPayload), { + retain: true, + qos: 1, + }); + + }) + const allSceneDevices = this.deviceRegistry.getAllSceneDevices(); logger.info(`Sending discovery for ${allSceneDevices.length} Plejd scene devices`); allSceneDevices.forEach((sceneDevice) => { @@ -373,6 +414,10 @@ class MqttClient extends EventEmitter { }); } + buttonPressed(data) { + logger.verbose(`Button ${data.deviceInput} pressed for deviceId ${data.deviceId}`); + this.client.publish(getButtonEventTopic(data.deviceId), `${data.deviceInput}`, { qos: 1 }); + } /** * @param {string} sceneId */ diff --git a/plejd/PlejdAddon.js b/plejd/PlejdAddon.js index cdb3d60..d78045b 100644 --- a/plejd/PlejdAddon.js +++ b/plejd/PlejdAddon.js @@ -126,6 +126,14 @@ class PlejdAddon extends EventEmitter { }, ); + this.plejdDeviceCommunication.on(PlejdDeviceCommunication.EVENTS.buttonPressed, (data) => { + try { + this.mqttClient.buttonPressed(data); + } catch (err) { + logger.error('Error in PlejdService.sceneTriggered callback', err); + } + }); + this.plejdDeviceCommunication.on(PlejdDeviceCommunication.EVENTS.sceneTriggered, (sceneId) => { try { this.mqttClient.sceneTriggered(sceneId); diff --git a/plejd/PlejdApi.js b/plejd/PlejdApi.js index 8609bbb..b6368c2 100644 --- a/plejd/PlejdApi.js +++ b/plejd/PlejdApi.js @@ -1,3 +1,4 @@ +// @ts-ignore const axios = require('axios').default; const fs = require('fs'); @@ -261,7 +262,7 @@ class PlejdApi { case 5: return { name: 'LED-10', type: 'light', dimmable: true }; case 6: - return { name: 'WPH-01', type: 'switch', dimmable: false }; + return { name: 'WPH-01', type: 'device_automation', dimmable: false }; case 7: return { name: 'REL-01', type: 'switch', dimmable: false }; case 8: @@ -369,30 +370,46 @@ class PlejdApi { this.deviceRegistry.addOutputDevice(outputDevice); } - } + } else { + // The device does not have an output. It can be assumed to be a WPH-01 or a WRT-01 + // Filter inputSettings for available buttons + const inputSettings = this.siteDetails.inputSettings.filter( + (x) => x.deviceId === device.deviceId && (x.buttonType == 'DirectionUp') || (x.buttonType == 'DirectionDown')); - // What should we do with inputs?! - // if (outputDevice.typeName === 'WPH-01') { - // // WPH-01 is special, it has two buttons which needs to be - // // registered separately. - // const inputs = this.siteDetails.inputAddress[deviceId]; - // const first = inputs[0]; - // const second = inputs[1]; + // For each found button, register the device as an inputDevice + inputSettings.forEach((input) => { - // this.deviceRegistry.addPlejdDevice({ - // ...outputDevice, - // id: first, - // name: `${device.title} left`, - // }); + const bleInputAddress = this.siteDetails.deviceAddress[input.deviceId]; + logger.verbose( + `Found input device (${input.deviceId}), with input ${input.input} having BLE address (${bleInputAddress})`, + ); - // this.deviceRegistry.addPlejdDevice({ - // ...outputDevice, - // id: second, - // name: `${device.title} right`, - // }); - // } else { - // this.deviceRegistry.addPlejdDevice(outputDevice); - // } + const plejdDevice = this.siteDetails.plejdDevices.find( + (x) => x.deviceId === device.deviceId, + ); + + const uniqueInputId = this.deviceRegistry.getUniqueInputId( + device.deviceId, + input.input, + ); + + const { name: typeName, type } = this._getDeviceType(plejdDevice); + + /** @type {import('types/DeviceRegistry').InputDevice} */ + const inputDevice = { + bleOutputAddress: bleInputAddress, + deviceId: device.deviceId, + name: device.title, + input: input.input, + roomId: device.roomId, + type, + typeName, + version: plejdDevice.firmware.version, + uniqueId: uniqueInputId, + }; + this.deviceRegistry.addInputDevice(inputDevice); + }); + }; }); } diff --git a/plejd/PlejdBLEHandler.js b/plejd/PlejdBLEHandler.js index 75eeaf0..4d03865 100644 --- a/plejd/PlejdBLEHandler.js +++ b/plejd/PlejdBLEHandler.js @@ -1,3 +1,4 @@ +// @ts-ignore const dbus = require('dbus-next'); const crypto = require('crypto'); const xor = require('buffer-xor'); @@ -23,6 +24,7 @@ const BLE_CMD_DIM2_CHANGE = 0x0098; const BLE_CMD_STATE_CHANGE = 0x0097; const BLE_CMD_SCENE_TRIG = 0x0021; const BLE_CMD_TIME_UPDATE = 0x001b; +const BLE_CMD_REMOTE_CLICK = 0x0016; const BLE_BROADCAST_DEVICE_ID = 0x01; const BLE_REQUEST_NO_RESPONSE = 0x0110; @@ -906,6 +908,23 @@ class PlejBLEHandler extends EventEmitter { logger.info('Got time response. Plejd clock time in sync with Home Assistant time'); } } + } else if (cmd === BLE_CMD_REMOTE_CLICK) { + const inputBleAddress = state; + const inputButton = decoded.length > 7 ? decoded.readUInt8(6) : 0; + + const sourceDevice = this.deviceRegistry.getInputDeviceByBleOutputAddress(inputBleAddress, inputButton); + if (!sourceDevice) { + logger.warn( + `Scene with BLE address ${inputBleAddress} could not be found, can't process message`, + ); + return; + } + logger.verbose( + `WPH-10 button ${inputButton} at BLE address ${inputBleAddress} was pressed. Unique Id is ${sourceDevice.uniqueId}` + ); + command = COMMANDS.BUTTON_CLICK; + data = { deviceId: sourceDevice.deviceId, deviceInput: sourceDevice.input}; + this.emit(PlejBLEHandler.EVENTS.commandReceived, outputUniqueId, command, data); } else { logger.verbose( `Command ${cmd.toString(16)} unknown. ${decoded.toString( diff --git a/plejd/PlejdDeviceCommunication.js b/plejd/PlejdDeviceCommunication.js index 4321f94..9c218a0 100644 --- a/plejd/PlejdDeviceCommunication.js +++ b/plejd/PlejdDeviceCommunication.js @@ -116,6 +116,8 @@ class PlejdDeviceCommunication extends EventEmitter { }); } else if (command === COMMANDS.TRIGGER_SCENE) { this.emit(PlejdDeviceCommunication.EVENTS.sceneTriggered, data.sceneId); + } else if (command === COMMANDS.BUTTON_CLICK) { + this.emit(PlejdDeviceCommunication.EVENTS.buttonPressed, data); } else { logger.warn(`Unknown ble command ${command}`); } diff --git a/plejd/constants.js b/plejd/constants.js index 0b69b3a..1b97f67 100644 --- a/plejd/constants.js +++ b/plejd/constants.js @@ -3,6 +3,7 @@ const COMMANDS = { TURN_OFF: 'Turn off', DIM: 'Dim', TRIGGER_SCENE: 'Trigger scene', + BUTTON_CLICK: 'Button click', }; module.exports = { COMMANDS }; diff --git a/plejd/types/DeviceRegistry.d.ts b/plejd/types/DeviceRegistry.d.ts index b93c509..4da82a4 100644 --- a/plejd/types/DeviceRegistry.d.ts +++ b/plejd/types/DeviceRegistry.d.ts @@ -19,3 +19,17 @@ export interface OutputDevice { version: string; uniqueId: string; } + +export type InputDevices = { [deviceIdAndOutput: string]: InputDevice }; + +export interface InputDevice { + bleOutputAddress: number; + deviceId: string; + name: string; + input: number; + roomId: string; + type: string; + typeName: string; + version: string; + uniqueId: string; +}