hassio-plejd/plejd/PlejdBLEHandler.js

978 lines
33 KiB
JavaScript
Raw Normal View History

2020-01-18 15:50:46 +00:00
const dbus = require('dbus-next');
2020-01-17 14:50:58 +00:00
const crypto = require('crypto');
const xor = require('buffer-xor');
const { EventEmitter } = require('events');
2020-01-17 14:50:58 +00:00
const Configuration = require('./Configuration');
const constants = require('./constants');
const Logger = require('./Logger');
const { COMMANDS } = constants;
const logger = Logger.getLogger('plejd-ble');
2020-01-17 14:50:58 +00:00
// UUIDs
2021-02-08 07:38:31 +01:00
const BLE_UUID_SUFFIX = '6085-4726-be45-040c957391b5';
const PLEJD_SERVICE = `31ba0001-${BLE_UUID_SUFFIX}`;
const DATA_UUID = `31ba0004-${BLE_UUID_SUFFIX}`;
const LAST_DATA_UUID = `31ba0005-${BLE_UUID_SUFFIX}`;
const AUTH_UUID = `31ba0009-${BLE_UUID_SUFFIX}`;
const PING_UUID = `31ba000a-${BLE_UUID_SUFFIX}`;
2020-01-17 14:50:58 +00:00
const BLE_CMD_DIM_CHANGE = 0x00c8;
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_BROADCAST_DEVICE_ID = 0x01;
const BLE_REQUEST_NO_RESPONSE = 0x0110;
const BLE_REQUEST_RESPONSE = 0x0102;
// const BLE_REQUEST_READ_VALUE = 0x0103;
2020-01-17 14:50:58 +00:00
const BLUEZ_SERVICE_NAME = 'org.bluez';
2020-01-18 15:50:46 +00:00
const DBUS_OM_INTERFACE = 'org.freedesktop.DBus.ObjectManager';
const DBUS_PROP_INTERFACE = 'org.freedesktop.DBus.Properties';
2020-01-17 14:50:58 +00:00
const BLUEZ_ADAPTER_ID = 'org.bluez.Adapter1';
const BLUEZ_DEVICE_ID = 'org.bluez.Device1';
const GATT_SERVICE_ID = 'org.bluez.GattService1';
const GATT_CHRC_ID = 'org.bluez.GattCharacteristic1';
const delay = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout));
2021-02-08 07:38:31 +01:00
class PlejBLEHandler extends EventEmitter {
adapter;
adapterProperties;
config;
bleDevices = [];
bus = null;
connectedDevice = null;
2021-02-08 19:54:24 +01:00
consecutiveWriteFails;
consecutiveReconnectAttempts = 0;
/** @type {import('./DeviceRegistry')} */
deviceRegistry;
discoveryTimeout = null;
plejdService = null;
pingRef = null;
requestCurrentPlejdTimeRef = null;
reconnectInProgress = false;
emergencyReconnectTimeout = null;
2021-02-08 07:38:31 +01:00
// Refer to BLE-states.md regarding the internal BLE/bluez state machine of Bluetooth states
// These states refer to the state machine of this file
static STATES = ['MAIN_INIT', 'GET_ADAPTER_PROXY'];
static EVENTS = {
connected: 'connected',
reconnecting: 'reconnecting',
commandReceived: 'commandReceived',
2021-02-20 15:33:06 +01:00
writeFailed: 'writeFailed',
writeSuccess: 'writeSuccess',
};
2021-02-08 19:54:24 +01:00
constructor(deviceRegistry) {
2020-01-17 14:50:58 +00:00
super();
2021-02-08 07:38:31 +01:00
logger.info('Starting Plejd BLE Handler, resetting all device states.');
this.config = Configuration.getOptions();
2021-02-08 07:38:31 +01:00
this.deviceRegistry = deviceRegistry;
2020-01-17 14:50:58 +00:00
// Holds a reference to all characteristics
this.characteristics = {
data: null,
lastData: null,
2020-01-19 20:08:48 +00:00
lastDataProperties: null,
2020-01-17 14:50:58 +00:00
auth: null,
ping: null,
2020-01-17 14:50:58 +00:00
};
this.bus = dbus.systemBus();
2021-02-20 15:33:06 +01:00
}
cleanup() {
logger.verbose('cleanup() - Clearing ping interval and clock update timer');
clearInterval(this.pingRef);
clearTimeout(this.requestCurrentPlejdTimeRef);
logger.verbose('Removing listeners to write events, bus events and objectManager...');
2021-02-20 15:33:06 +01:00
this.removeAllListeners(PlejBLEHandler.EVENTS.writeFailed);
this.removeAllListeners(PlejBLEHandler.EVENTS.writeSuccess);
2020-01-17 14:50:58 +00:00
2021-02-20 15:33:06 +01:00
if (this.bus) {
this.bus.removeAllListeners('error');
this.bus.removeAllListeners('connect');
}
if (this.characteristics.lastDataProperties) {
this.characteristics.lastDataProperties.removeAllListeners('PropertiesChanged');
}
if (this.objectManager) {
this.objectManager.removeAllListeners('InterfacesAdded');
}
}
async init() {
logger.info('init()');
2021-02-20 15:33:06 +01:00
this.on(PlejBLEHandler.EVENTS.writeFailed, (error) => this._onWriteFailed(error));
this.on(PlejBLEHandler.EVENTS.writeSuccess, () => this._onWriteSuccess());
this.bus.on('error', (err) => {
// Uncaught error events will show UnhandledPromiseRejection logs
logger.verbose(`dbus-next error event: ${err.message}`);
});
this.bus.on('connect', () => {
logger.verbose('dbus-next connected');
});
// this.bus also has a 'message' event that gets emitted _very_ frequently
2021-02-08 07:38:31 +01:00
this.adapter = null;
this.adapterProperties = null;
2021-02-08 19:54:24 +01:00
this.consecutiveWriteFails = 0;
2020-01-17 14:50:58 +00:00
this.cryptoKey = Buffer.from(this.deviceRegistry.cryptoKey.replace(/-/g, ''), 'hex');
2020-01-17 14:50:58 +00:00
if (this.objectManager) {
this.objectManager.removeAllListeners();
}
this.bleDevices = [];
this.connectedDevice = null;
this.characteristics = {
data: null,
lastData: null,
lastDataProperties: null,
auth: null,
ping: null,
};
2020-01-27 20:43:52 +00:00
2021-02-08 07:38:31 +01:00
await this._getInterface();
await this._startGetPlejdDevice();
2021-02-08 19:54:24 +01:00
logger.info('BLE init done, waiting for devices.');
2021-02-08 07:38:31 +01:00
}
async sendCommand(command, uniqueOutputId, data) {
let payload;
let brightnessVal;
switch (command) {
case COMMANDS.TURN_ON:
payload = this._createHexPayload(uniqueOutputId, BLE_CMD_STATE_CHANGE, '01');
break;
case COMMANDS.TURN_OFF:
payload = this._createHexPayload(uniqueOutputId, BLE_CMD_STATE_CHANGE, '00');
break;
case COMMANDS.DIM:
// eslint-disable-next-line no-bitwise
brightnessVal = (data << 8) | data;
payload = this._createHexPayload(
uniqueOutputId,
BLE_CMD_DIM2_CHANGE,
`01${brightnessVal.toString(16).padStart(4, '0')}`,
);
break;
default:
logger.error(`Unknown command ${command}`);
throw new Error(`Unknown command ${command}`);
}
await this._write(payload);
}
2021-02-08 07:38:31 +01:00
async _initDiscoveredPlejdDevice(path) {
logger.debug(`initDiscoveredPlejdDevice(). Got ${path} device`);
logger.debug(`Inspecting ${path}`);
try {
const proxyObject = await this.bus.getProxyObject(BLUEZ_SERVICE_NAME, path);
const device = await proxyObject.getInterface(BLUEZ_DEVICE_ID);
const properties = await proxyObject.getInterface(DBUS_PROP_INTERFACE);
const plejd = { path };
plejd.rssi = (await properties.Get(BLUEZ_DEVICE_ID, 'RSSI')).value;
plejd.instance = device;
const segments = plejd.path.split('/');
let plejdSerialNumber = segments[segments.length - 1].replace('dev_', '');
plejdSerialNumber = plejdSerialNumber.replace(/_/g, '');
plejd.device = this.deviceRegistry.getPhysicalDevice(plejdSerialNumber);
2021-02-08 07:38:31 +01:00
if (plejd.device) {
2021-03-23 13:45:12 +01:00
logger.debug(
`Discovered ${plejd.path} with rssi ${plejd.rssi} dBm, name ${plejd.device.name}`,
);
this.bleDevices.push(plejd);
} else {
logger.warn(`Device registry does not contain device with serial ${plejdSerialNumber}`);
}
2021-02-08 07:38:31 +01:00
} catch (err) {
logger.error(`Failed inspecting ${path}. `, err);
}
}
2020-01-20 10:58:03 +00:00
2021-02-08 07:38:31 +01:00
async _inspectDevicesDiscovered() {
try {
if (this.bleDevices.length === 0) {
logger.error('Discovery timeout elapsed, no devices found. Starting reconnect loop...');
throw new Error('Discovery timeout elapsed');
}
2021-02-08 07:38:31 +01:00
logger.info(`Device discovery done, found ${this.bleDevices.length} Plejd devices`);
2021-02-08 07:38:31 +01:00
const sortedDevices = this.bleDevices.sort((a, b) => b.rssi - a.rssi);
2021-02-08 07:38:31 +01:00
// eslint-disable-next-line no-restricted-syntax
for (const plejd of sortedDevices) {
try {
logger.verbose(`Inspecting ${plejd.path}`);
if (plejd.instance) {
logger.info(`Connecting to ${plejd.path}`);
// eslint-disable-next-line no-await-in-loop
await plejd.instance.Connect();
logger.verbose('Connected. Waiting for timeout before reading characteristics...');
// eslint-disable-next-line no-await-in-loop
await delay(this.config.connectionTimeout * 1000);
// eslint-disable-next-line no-await-in-loop
const connectedPlejdDevice = await this._onDeviceConnected(plejd);
if (connectedPlejdDevice) {
break;
}
2021-02-08 07:38:31 +01:00
}
} catch (err) {
logger.warn('Unable to connect. ', err);
2021-02-08 07:38:31 +01:00
}
}
try {
logger.verbose('Stopping discovery...');
await this.adapter.StopDiscovery();
logger.verbose('Stopped BLE discovery');
} catch (err) {
logger.error('Failed to stop discovery.', err);
if (err.message.includes('Operation already in progress')) {
logger.info(
'If you continue to get "operation already in progress" error, you can try power cycling the bluetooth adapter. Get root console access, run "bluetoothctl" => "power off" => "power on" => "exit" => restart addon.',
);
try {
await delay(250);
logger.verbose('Power cycling...');
await this._powerCycleAdapter();
logger.verbose('Trying again...');
await this._startGetPlejdDevice();
} catch (errInner) {
logger.error('Failed to retry internalInit. Starting reconnect loop', errInner);
throw new Error('Failed to retry internalInit');
}
2021-02-08 07:38:31 +01:00
}
logger.error('Failed to start discovery. Make sure no other add-on is currently scanning.');
throw new Error('Failed to start discovery');
}
if (!this.connectedDevice) {
logger.error('Could not connect to any Plejd device. Starting reconnect loop...');
throw new Error('Could not connect to any Plejd device');
2021-02-08 07:38:31 +01:00
}
logger.info(`BLE Connected to ${this.connectedDevice.name}`);
// Connected and authenticated, request current time and start ping
if (this.config.updatePlejdClock) {
this._requestCurrentPlejdTime();
} else {
logger.info('Plejd clock updates disabled in configuration.');
}
this._startPing();
// After we've authenticated, we need to hook up the event listener
// for changes to lastData.
this.characteristics.lastDataProperties.on('PropertiesChanged', (
iface,
properties,
// invalidated (third param),
) => this._onLastDataUpdated(iface, properties));
this.characteristics.lastData.StartNotify();
this.consecutiveReconnectAttempts = 0;
this.emit(PlejBLEHandler.EVENTS.connected);
clearTimeout(this.emergencyReconnectTimeout);
this.emergencyReconnectTimeout = null;
} catch (err) {
// This method is run on a timer, so errors can't e re-thrown.
// Start reconnect loop if errors occur here
logger.debug(`Starting reconnect loop due to ${err.message}`);
2021-02-08 19:54:24 +01:00
this.startReconnectPeriodicallyLoop();
2021-02-08 07:38:31 +01:00
}
}
async _getInterface() {
2020-01-18 15:50:46 +00:00
const bluez = await this.bus.getProxyObject(BLUEZ_SERVICE_NAME, '/');
2021-02-20 15:33:06 +01:00
2020-01-18 15:50:46 +00:00
this.objectManager = await bluez.getInterface(DBUS_OM_INTERFACE);
2020-01-17 14:50:58 +00:00
2020-01-19 20:08:48 +00:00
// We need to find the ble interface which implements the Adapter1 interface
const managedObjects = await this.objectManager.GetManagedObjects();
2021-02-08 07:38:31 +01:00
const managedPaths = Object.keys(managedObjects);
2020-01-17 14:50:58 +00:00
2021-02-08 19:54:24 +01:00
logger.verbose(`Managed paths${JSON.stringify(managedPaths, null, 2)}`);
2020-01-17 14:50:58 +00:00
2021-02-08 07:38:31 +01:00
// eslint-disable-next-line no-restricted-syntax
for (const path of managedPaths) {
const pathInterfaces = Object.keys(managedObjects[path]);
if (pathInterfaces.indexOf(BLUEZ_ADAPTER_ID) > -1) {
logger.debug(`Found BLE interface '${BLUEZ_ADAPTER_ID}' at ${path}`);
try {
// eslint-disable-next-line no-await-in-loop
const adapterObject = await this.bus.getProxyObject(BLUEZ_SERVICE_NAME, path);
// eslint-disable-next-line no-await-in-loop
this.adapterProperties = await adapterObject.getInterface(DBUS_PROP_INTERFACE);
// eslint-disable-next-line no-await-in-loop
await this._powerOnAdapter();
this.adapter = adapterObject.getInterface(BLUEZ_ADAPTER_ID);
// eslint-disable-next-line no-await-in-loop
await this._cleanExistingConnections(managedObjects);
2021-02-08 19:54:24 +01:00
logger.verbose(`Got adapter ${this.adapter.path}`);
2021-02-08 07:38:31 +01:00
return this.adapter;
} catch (err) {
logger.error(`Failed to get interface '${BLUEZ_ADAPTER_ID}'. `, err);
}
}
2020-01-17 14:50:58 +00:00
}
2021-02-08 07:38:31 +01:00
this.adapter = null;
logger.error('Unable to find a bluetooth adapter that is compatible.');
throw new Error('Unable to find a bluetooth adapter that is compatible.');
}
async _powerCycleAdapter() {
logger.verbose('Power cycling BLE adapter');
2021-02-08 07:38:31 +01:00
await this._powerOffAdapter();
await this._powerOnAdapter();
}
async _powerOnAdapter() {
logger.verbose('Powering on BLE adapter and waiting 5 seconds');
2021-02-08 07:38:31 +01:00
await this.adapterProperties.Set(BLUEZ_ADAPTER_ID, 'Powered', new dbus.Variant('b', 1));
await delay(5000);
2021-02-08 07:38:31 +01:00
}
async _powerOffAdapter() {
2021-03-23 13:45:12 +01:00
logger.verbose('Powering off BLE adapter and waiting 30 seconds');
2021-02-08 07:38:31 +01:00
await this.adapterProperties.Set(BLUEZ_ADAPTER_ID, 'Powered', new dbus.Variant('b', 0));
2021-03-23 13:45:12 +01:00
await delay(30000);
2021-02-08 07:38:31 +01:00
}
async _cleanExistingConnections(managedObjects) {
logger.verbose(
`Iterating ${
Object.keys(managedObjects).length
} BLE managedObjects looking for ${BLUEZ_DEVICE_ID}`,
);
// eslint-disable-next-line no-restricted-syntax
for (const path of Object.keys(managedObjects)) {
/* eslint-disable no-await-in-loop */
try {
const interfaces = Object.keys(managedObjects[path]);
if (interfaces.indexOf(BLUEZ_DEVICE_ID) > -1) {
const proxyObject = await this.bus.getProxyObject(BLUEZ_SERVICE_NAME, path);
const device = await proxyObject.getInterface(BLUEZ_DEVICE_ID);
2020-01-17 14:50:58 +00:00
2021-02-08 19:54:24 +01:00
logger.verbose(`Found ${path}`);
2020-01-19 20:08:48 +00:00
const connected = managedObjects[path][BLUEZ_DEVICE_ID].Connected.value;
2020-01-19 20:08:48 +00:00
if (connected) {
logger.info(`disconnecting ${path}. This can take up to 180 seconds`);
await device.Disconnect();
}
logger.verbose(`Removing ${path} from adapter.`);
await this.adapter.RemoveDevice(path);
}
} catch (err) {
logger.error(`Error handling ${path}`, err);
2020-01-19 20:08:48 +00:00
}
/* eslint-enable no-await-in-loop */
2020-01-17 14:50:58 +00:00
}
logger.verbose('All active BLE device connections cleaned up.');
2021-02-08 07:38:31 +01:00
}
2021-02-08 07:38:31 +01:00
async _startGetPlejdDevice() {
logger.verbose('Setting up interfacesAdded subscription and discovery filter');
this.objectManager.on('InterfacesAdded', (path, interfaces) => this._onInterfacesAdded(path, interfaces));
2020-01-19 20:08:48 +00:00
this.adapter.SetDiscoveryFilter({
UUIDs: new dbus.Variant('as', [PLEJD_SERVICE]),
Transport: new dbus.Variant('s', 'le'),
2020-01-19 20:08:48 +00:00
});
2020-01-27 20:43:52 +00:00
try {
logger.verbose('Starting BLE discovery... This can take up to 180 seconds.');
2021-02-08 07:38:31 +01:00
this._scheduleInternalInit();
2020-01-27 20:43:52 +00:00
await this.adapter.StartDiscovery();
logger.verbose('Started BLE discovery');
2020-06-12 11:15:00 +02:00
} catch (err) {
logger.error('Failed to start discovery.', err);
if (err.message.includes('Operation already in progress')) {
logger.info(
'If you continue to get "operation already in progress" error, you can try power cycling the bluetooth adapter. Get root console access, run "bluetoothctl" => "power off" => "power on" => "exit" => restart addon.',
);
}
throw new Error(
'Failed to start discovery. Make sure no other add-on is currently scanning.',
);
}
2020-01-19 20:08:48 +00:00
}
2020-01-17 14:50:58 +00:00
2021-02-08 07:38:31 +01:00
_scheduleInternalInit() {
clearTimeout(this.discoveryTimeout);
this.discoveryTimeout = setTimeout(
() => this._inspectDevicesDiscovered(),
this.config.connectionTimeout * 1000,
);
2020-01-19 20:08:48 +00:00
}
2020-01-17 14:50:58 +00:00
async _onInterfacesAdded(path, interfaces) {
logger.silly(`Interface added ${path}, inspecting...`);
2020-01-19 20:08:48 +00:00
const interfaceKeys = Object.keys(interfaces);
if (interfaceKeys.indexOf(BLUEZ_DEVICE_ID) > -1) {
if (interfaces[BLUEZ_DEVICE_ID].UUIDs.value.indexOf(PLEJD_SERVICE) > -1) {
logger.debug(`Found Plejd service on ${path}`);
2021-02-20 15:33:06 +01:00
this.objectManager.removeAllListeners('InterfacesAdded');
2021-02-08 07:38:31 +01:00
await this._initDiscoveredPlejdDevice(path);
2020-01-19 20:08:48 +00:00
} else {
logger.error('Uh oh, no Plejd device!');
2020-01-17 14:50:58 +00:00
}
} else {
logger.silly('Not the right device id');
2020-01-17 14:50:58 +00:00
}
}
async _authenticate() {
logger.info('authenticate()');
2020-01-17 14:50:58 +00:00
2020-01-19 20:08:48 +00:00
try {
logger.debug('Sending challenge to device');
2020-01-19 20:08:48 +00:00
await this.characteristics.auth.WriteValue([0], {});
logger.debug('Reading response from device');
2020-01-19 20:08:48 +00:00
const challenge = await this.characteristics.auth.ReadValue({});
2020-01-20 21:32:46 +00:00
const response = this._createChallengeResponse(this.cryptoKey, Buffer.from(challenge));
logger.debug('Responding to authenticate');
2020-01-19 20:08:48 +00:00
await this.characteristics.auth.WriteValue([...response], {});
2020-06-12 11:15:00 +02:00
} catch (err) {
logger.error('Failed to authenticate: ', err);
2021-02-08 07:38:31 +01:00
throw new Error('Failed to authenticate');
2020-01-19 20:08:48 +00:00
}
2020-01-17 14:50:58 +00:00
}
2021-02-08 19:54:24 +01:00
async startReconnectPeriodicallyLoop() {
logger.info('Starting reconnect loop...');
clearTimeout(this.emergencyReconnectTimeout);
this.emergencyReconnectTimeout = null;
await this._startReconnectPeriodicallyLoopInternal();
}
async _startReconnectPeriodicallyLoopInternal() {
logger.verbose('Starting internal reconnect loop...');
if (this.reconnectInProgress && !this.emergencyReconnectTimeout) {
logger.debug('Reconnect already in progress. Skipping this call.');
2021-02-08 19:54:24 +01:00
return;
}
if (this.emergencyReconnectTimeout) {
logger.warn(
'Restarting reconnect loop due to emergency reconnect timer elapsed. This should very rarely happen!',
);
}
2021-02-08 19:54:24 +01:00
this.reconnectInProgress = true;
/* eslint-disable no-await-in-loop */
// eslint-disable-next-line no-constant-condition
while (true) {
try {
logger.verbose('Reconnect: Clean up, emit reconnect event, wait 5s and the re-init...');
2021-02-20 15:33:06 +01:00
this.cleanup();
this.consecutiveReconnectAttempts++;
2021-03-23 13:45:12 +01:00
if (this.consecutiveReconnectAttempts % 100 === 0) {
logger.error('Failed reconnecting 100 times. Creating a new dbus instance...');
this.bus = dbus.systemBus();
}
if (this.consecutiveReconnectAttempts % 10 === 0) {
logger.warn(
2021-03-23 13:45:12 +01:00
`Tried reconnecting ${this.consecutiveReconnectAttempts} times. Will power cycle the BLE adapter now...`,
);
await this._powerCycleAdapter();
} else {
logger.verbose(
`Reconnect attempt ${this.consecutiveReconnectAttempts} in a row. Will power cycle every 10th time.`,
);
}
this.emit(PlejBLEHandler.EVENTS.reconnecting);
// Emergency 2 minute timer if reconnect silently fails somewhere
clearTimeout(this.emergencyReconnectTimeout);
this.emergencyReconnectTimeout = setTimeout(
() => this._startReconnectPeriodicallyLoopInternal(),
120 * 1000,
);
await delay(5000);
2021-02-08 19:54:24 +01:00
logger.info('Reconnecting BLE...');
await this.init();
break;
} catch (err) {
logger.warn('Failed reconnecting.', err);
2021-02-08 19:54:24 +01:00
}
}
/* eslint-enable no-await-in-loop */
this.reconnectInProgress = false;
}
async _write(payload) {
if (!payload || !this.plejdService || !this.characteristics.data) {
logger.debug('data, plejdService or characteristics not available. Cannot write()');
throw new Error('data, plejdService or characteristics not available. Cannot write()');
2020-01-24 10:20:39 +01:00
}
2020-01-19 20:08:48 +00:00
try {
logger.verbose(
`Sending ${payload.length} byte(s) of data to Plejd. ${payload.toString('hex')}`,
);
const encryptedData = this._encryptDecrypt(this.cryptoKey, this.plejdService.addr, payload);
2020-01-19 20:08:48 +00:00
await this.characteristics.data.WriteValue([...encryptedData], {});
await this._onWriteSuccess();
2020-06-12 11:15:00 +02:00
} catch (err) {
await this._onWriteFailed(err);
2020-03-03 15:59:10 +01:00
if (err.message === 'In Progress') {
logger.debug("Write failed due to 'In progress' ", err);
throw new Error("Write failed due to 'In progress'");
2020-03-03 15:59:10 +01:00
}
logger.debug('Write failed ', err);
throw new Error(`Write failed due to ${err.message}`);
2020-01-19 20:08:48 +00:00
}
2020-01-17 14:50:58 +00:00
}
_startPing() {
logger.info('startPing()');
2020-01-17 14:50:58 +00:00
clearInterval(this.pingRef);
this.pingRef = setInterval(async () => {
logger.silly('ping');
await this._ping();
2020-01-20 21:32:46 +00:00
}, 3000);
2020-01-17 14:50:58 +00:00
}
// eslint-disable-next-line class-methods-use-this
_onWriteSuccess() {
2021-02-08 19:54:24 +01:00
this.consecutiveWriteFails = 0;
2020-01-17 14:50:58 +00:00
}
async _onWriteFailed(error) {
2021-02-08 19:54:24 +01:00
this.consecutiveWriteFails++;
logger.debug(`onWriteFailed #${this.consecutiveWriteFails} in a row.`, error);
logger.verbose(`Error message: ${error.message}`);
2021-02-08 19:54:24 +01:00
let errorIndicatesDisconnected = false;
if (error.message.includes('error: 0x0e')) {
logger.error("'Unlikely error' (0x0e) writing to Plejd. Will retry.", error);
} else if (error.message.includes('Not connected')) {
logger.error("'Not connected' writing to Plejd. Plejd device is probably disconnected.");
2021-02-08 19:54:24 +01:00
errorIndicatesDisconnected = true;
} else if (error.message.includes('Method "WriteValue" with signature')) {
2021-02-08 19:54:24 +01:00
logger.error("'Method \"WriteValue\" doesn't exist'. Plejd device is probably disconnected.");
errorIndicatesDisconnected = true;
}
2020-01-17 14:50:58 +00:00
if (errorIndicatesDisconnected || this.consecutiveWriteFails >= 5) {
logger.warn(
`Write error indicates BLE is disconnected. Retry count ${this.consecutiveWriteFails}. Reconnecting...`,
);
this.startReconnectPeriodicallyLoop();
2021-02-08 19:54:24 +01:00
}
2020-01-17 14:50:58 +00:00
}
async _ping() {
logger.silly('ping()');
2020-01-17 14:50:58 +00:00
const ping = crypto.randomBytes(1);
2020-01-19 20:08:48 +00:00
let pong = null;
try {
await this.characteristics.ping.WriteValue([...ping], {});
pong = await this.characteristics.ping.ReadValue({});
2020-06-12 11:15:00 +02:00
} catch (err) {
logger.verbose(`Error pinging Plejd, calling onWriteFailed... ${err.message}`);
await this._onWriteFailed(err);
2020-01-17 14:50:58 +00:00
return;
}
// eslint-disable-next-line no-bitwise
2020-01-19 20:08:48 +00:00
if (((ping[0] + 1) & 0xff) !== pong[0]) {
logger.verbose('Plejd ping failed, pong contains wrong data. Calling onWriteFailed...');
await this._onWriteFailed(new Error(`plejd ping failed ${ping[0]} - ${pong[0]}`));
2020-01-19 20:08:48 +00:00
return;
}
2020-01-17 14:50:58 +00:00
2021-02-08 19:54:24 +01:00
logger.silly(`pong: ${pong[0]}`);
await this._onWriteSuccess();
2020-01-17 14:50:58 +00:00
}
async _requestCurrentPlejdTime() {
if (!this.connectedDevice) {
logger.warn('Cannot request current Plejd time, not connected.');
return;
}
logger.info('Requesting current Plejd time...');
const payload = this._createHexPayload(
this.connectedDevice.id,
BLE_CMD_TIME_UPDATE,
'',
BLE_REQUEST_RESPONSE,
);
try {
this._write(payload);
} catch (error) {
logger.warn('Failed requesting time update from Plejd');
2020-03-03 15:59:10 +01:00
}
clearTimeout(this.requestCurrentPlejdTimeRef);
this.requestCurrentPlejdTimeRef = setTimeout(
() => this._requestCurrentPlejdTime(),
1000 * 3600,
); // Once per hour
}
2020-01-19 20:08:48 +00:00
async _processPlejdService(path, characteristics) {
const proxyObject = await this.bus.getProxyObject(BLUEZ_SERVICE_NAME, path);
const properties = await proxyObject.getInterface(DBUS_PROP_INTERFACE);
2020-01-17 14:50:58 +00:00
2020-01-19 20:08:48 +00:00
const uuid = (await properties.Get(GATT_SERVICE_ID, 'UUID')).value;
if (uuid !== PLEJD_SERVICE) {
logger.error('not a Plejd device.');
2020-01-19 20:08:48 +00:00
return null;
}
2020-01-17 14:50:58 +00:00
2020-01-19 20:08:48 +00:00
const dev = (await properties.Get(GATT_SERVICE_ID, 'Device')).value;
const regex = /dev_([0-9A-F_]+)$/;
const dirtyAddr = regex.exec(dev);
const addr = this._reverseBuffer(
Buffer.from(
String(dirtyAddr[1]).replace(/-/g, '').replace(/_/g, '').replace(/:/g, ''),
'hex',
),
2020-01-19 20:08:48 +00:00
);
// eslint-disable-next-line no-restricted-syntax
2020-01-19 20:08:48 +00:00
for (const chPath of characteristics) {
/* eslint-disable no-await-in-loop */
2020-01-19 20:08:48 +00:00
const chProxyObject = await this.bus.getProxyObject(BLUEZ_SERVICE_NAME, chPath);
const ch = await chProxyObject.getInterface(GATT_CHRC_ID);
const prop = await chProxyObject.getInterface(DBUS_PROP_INTERFACE);
const chUuid = (await prop.Get(GATT_CHRC_ID, 'UUID')).value;
if (chUuid === DATA_UUID) {
2021-02-08 19:54:24 +01:00
logger.verbose('found DATA characteristic.');
2020-01-19 20:08:48 +00:00
this.characteristics.data = ch;
2020-06-12 11:15:00 +02:00
} else if (chUuid === LAST_DATA_UUID) {
2021-02-08 19:54:24 +01:00
logger.verbose('found LAST_DATA characteristic.');
2020-01-19 20:08:48 +00:00
this.characteristics.lastData = ch;
this.characteristics.lastDataProperties = prop;
2020-06-12 11:15:00 +02:00
} else if (chUuid === AUTH_UUID) {
2021-02-08 19:54:24 +01:00
logger.verbose('found AUTH characteristic.');
2020-01-19 20:08:48 +00:00
this.characteristics.auth = ch;
2020-06-12 11:15:00 +02:00
} else if (chUuid === PING_UUID) {
2021-02-08 19:54:24 +01:00
logger.verbose('found PING characteristic.');
2020-01-19 20:08:48 +00:00
this.characteristics.ping = ch;
}
/* eslint-eslint no-await-in-loop */
2020-01-19 20:08:48 +00:00
}
return {
addr,
2020-01-19 20:08:48 +00:00
};
2020-01-17 14:50:58 +00:00
}
2021-02-08 07:38:31 +01:00
async _onDeviceConnected(device) {
this.connectedDevice = null;
logger.info('onDeviceConnected()');
2021-02-08 19:54:24 +01:00
logger.debug(`Device ${device.path}, ${JSON.stringify(device.device)}`);
2020-01-19 20:08:48 +00:00
const objects = await this.objectManager.GetManagedObjects();
2020-01-24 17:30:17 +00:00
const paths = Object.keys(objects);
const characteristics = [];
2020-01-19 20:08:48 +00:00
2021-02-08 19:54:24 +01:00
logger.verbose(`Iterating connected devices looking for ${GATT_CHRC_ID}`);
// eslint-disable-next-line no-restricted-syntax
2020-01-24 17:30:17 +00:00
for (const path of paths) {
2020-01-19 20:08:48 +00:00
const interfaces = Object.keys(objects[path]);
2021-02-08 19:54:24 +01:00
logger.verbose(`Interfaces ${path}: ${JSON.stringify(interfaces)}`);
2020-01-19 20:08:48 +00:00
if (interfaces.indexOf(GATT_CHRC_ID) > -1) {
characteristics.push(path);
}
2020-01-17 14:50:58 +00:00
}
2021-02-08 19:54:24 +01:00
logger.verbose(`Characteristics found: ${JSON.stringify(characteristics)}`);
// eslint-disable-next-line no-restricted-syntax
2020-01-24 17:30:17 +00:00
for (const path of paths) {
2020-01-19 20:08:48 +00:00
const interfaces = Object.keys(objects[path]);
if (interfaces.indexOf(GATT_SERVICE_ID) > -1) {
const chPaths = [];
// eslint-disable-next-line no-restricted-syntax
2020-01-19 20:08:48 +00:00
for (const c of characteristics) {
if (c.startsWith(`${path}/`)) {
2020-01-19 20:08:48 +00:00
chPaths.push(c);
}
}
2021-02-08 19:54:24 +01:00
logger.verbose(`Trying ${chPaths.length} characteristics on ${path}...`);
2020-01-17 14:50:58 +00:00
2020-01-19 20:08:48 +00:00
this.plejdService = await this._processPlejdService(path, chPaths);
if (this.plejdService) {
break;
}
}
}
if (!this.plejdService) {
2021-02-08 07:38:31 +01:00
logger.warn("Wasn't able to connect to Plejd, will retry.");
return null;
2020-01-17 14:50:58 +00:00
}
2020-01-24 10:20:39 +01:00
if (!this.characteristics.auth) {
logger.error('unable to enumerate characteristics.');
2021-02-08 07:38:31 +01:00
return null;
2020-01-24 10:20:39 +01:00
}
2021-02-08 19:54:24 +01:00
logger.info('Connected device is a Plejd device with the right characteristics.');
this.connectedDevice = device.device;
await this._authenticate();
2021-02-08 07:38:31 +01:00
return this.connectedDevice;
2020-01-17 14:50:58 +00:00
}
// eslint-disable-next-line no-unused-vars
async _onLastDataUpdated(iface, properties) {
if (iface !== GATT_CHRC_ID) {
return;
}
2020-01-20 10:58:03 +00:00
const changedKeys = Object.keys(properties);
if (changedKeys.length === 0) {
return;
}
const value = await properties.Value;
2020-01-20 10:58:03 +00:00
if (!value) {
return;
}
const encryptedData = value.value;
const decoded = this._encryptDecrypt(this.cryptoKey, this.plejdService.addr, encryptedData);
2020-01-17 14:50:58 +00:00
if (decoded.length < 5) {
if (Logger.shouldLog('debug')) {
// decoded.toString() could potentially be expensive
2021-02-08 19:54:24 +01:00
logger.verbose(`Too short raw event ignored: ${decoded.toString('hex')}`);
}
2020-01-17 14:50:58 +00:00
// ignore the notification since too small
return;
}
const bleOutputAddress = decoded.readUInt8(0);
// Bytes 2-3 is Command/Request
const cmd = decoded.readUInt16BE(3);
const state = decoded.length > 5 ? decoded.readUInt8(5) : 0;
const dim = decoded.length > 7 ? decoded.readUInt8(7) : 0;
if (Logger.shouldLog('silly')) {
// Full dim level is 2 bytes, we could potentially use this
const dimFull = decoded.length > 7 ? decoded.readUInt16LE(6) : 0;
logger.silly(`Dim: ${dim.toString(16)}, full precision: ${dimFull.toString(16)}`);
}
const device = this.deviceRegistry.getOutputDeviceByBleOutputAddress(bleOutputAddress);
const deviceName = device ? device.name : 'Unknown';
const outputUniqueId = device ? device.uniqueId : null;
if (Logger.shouldLog('verbose')) {
// decoded.toString() could potentially be expensive
2021-02-08 19:54:24 +01:00
logger.verbose(`Raw event received: ${decoded.toString('hex')}`);
logger.verbose(
`Decoded: Device ${outputUniqueId}, cmd ${cmd.toString(16)}, state ${state}, dim ${dim}`,
2021-02-08 19:54:24 +01:00
);
}
2020-01-17 14:50:58 +00:00
let command;
let data = {};
2020-01-17 14:50:58 +00:00
if (cmd === BLE_CMD_DIM_CHANGE || cmd === BLE_CMD_DIM2_CHANGE) {
logger.debug(
`${deviceName} (${outputUniqueId}) got state+dim update. S: ${state}, D: ${dim}`,
);
2020-06-12 11:15:00 +02:00
command = COMMANDS.DIM;
data = { state, dim };
this.emit(PlejBLEHandler.EVENTS.commandReceived, outputUniqueId, command, data);
2020-06-12 11:15:00 +02:00
} else if (cmd === BLE_CMD_STATE_CHANGE) {
logger.debug(`${deviceName} (${outputUniqueId}) got state update. S: ${state}`);
command = state ? COMMANDS.TURN_ON : COMMANDS.TURN_OFF;
this.emit(PlejBLEHandler.EVENTS.commandReceived, outputUniqueId, command, data);
2020-06-12 11:15:00 +02:00
} else if (cmd === BLE_CMD_SCENE_TRIG) {
const sceneId = state;
2021-02-08 07:38:31 +01:00
const sceneName = this.deviceRegistry.getSceneName(sceneId);
2020-01-17 14:50:58 +00:00
logger.debug(`${sceneName} (${sceneId}) scene triggered (device id ${outputUniqueId}).`);
command = COMMANDS.TRIGGER_SCENE;
data = { sceneId };
this.emit(PlejBLEHandler.EVENTS.commandReceived, outputUniqueId, command, data);
} else if (cmd === BLE_CMD_TIME_UPDATE) {
const now = new Date();
// Guess Plejd timezone based on HA time zone
const offsetSecondsGuess = now.getTimezoneOffset() * 60 + 250; // Todo: 4 min off
// Plejd reports local unix timestamp adjust to local time zone
const plejdTimestampUTC = (decoded.readInt32LE(5) + offsetSecondsGuess) * 1000;
const diffSeconds = Math.round((plejdTimestampUTC - now.getTime()) / 1000);
if (
bleOutputAddress !== BLE_BROADCAST_DEVICE_ID
|| Logger.shouldLog('verbose')
|| Math.abs(diffSeconds) > 60
) {
const plejdTime = new Date(plejdTimestampUTC);
logger.debug(
`Plejd clock time update ${plejdTime.toString()}, diff ${diffSeconds} seconds`,
);
if (this.config.updatePlejdClock && Math.abs(diffSeconds) > 60) {
logger.warn(
`Plejd clock time off by more than 1 minute. Reported time: ${plejdTime.toString()}, diff ${diffSeconds} seconds. Time will be set hourly.`,
);
if (this.connectedDevice && bleOutputAddress === this.connectedDevice.id) {
// Requested time sync by us
const newLocalTimestamp = now.getTime() / 1000 - offsetSecondsGuess;
logger.info(`Setting time to ${now.toString()}`);
const payload = this._createPayload(
this.connectedDevice.id,
BLE_CMD_TIME_UPDATE,
10,
(pl) => pl.writeInt32LE(Math.trunc(newLocalTimestamp), 5),
);
try {
this._write(payload);
} catch (err) {
2021-02-20 10:49:00 +01:00
logger.error(
'Failed writing new time to Plejd. Will try again in one hour or at restart.',
);
}
}
} else if (bleOutputAddress !== BLE_BROADCAST_DEVICE_ID) {
logger.info('Got time response. Plejd clock time in sync with Home Assistant time');
}
}
} else {
logger.verbose(
`Command ${cmd.toString(16)} unknown. ${decoded.toString(
'hex',
)}. Device ${deviceName} (${bleOutputAddress}: ${outputUniqueId})`,
);
}
2020-01-17 14:50:58 +00:00
}
_createHexPayload(
bleOutputAddress,
command,
hexDataString,
requestResponseCommand = BLE_REQUEST_NO_RESPONSE,
) {
return this._createPayload(
bleOutputAddress,
command,
5 + Math.ceil(hexDataString.length / 2),
(payload) => payload.write(hexDataString, 5, 'hex'),
requestResponseCommand,
);
}
// eslint-disable-next-line class-methods-use-this
_createPayload(
bleOutputAddress,
command,
bufferLength,
payloadBufferAddDataFunc,
requestResponseCommand = BLE_REQUEST_NO_RESPONSE,
) {
const payload = Buffer.alloc(bufferLength);
payload.writeUInt8(bleOutputAddress);
payload.writeUInt16BE(requestResponseCommand, 1);
payload.writeUInt16BE(command, 3);
payloadBufferAddDataFunc(payload);
return payload;
}
// eslint-disable-next-line class-methods-use-this
2020-01-17 14:50:58 +00:00
_createChallengeResponse(key, challenge) {
const intermediate = crypto.createHash('sha256').update(xor(key, challenge)).digest();
const part1 = intermediate.subarray(0, 16);
const part2 = intermediate.subarray(16);
const resp = xor(part1, part2);
return resp;
}
// eslint-disable-next-line class-methods-use-this
2020-01-17 14:50:58 +00:00
_encryptDecrypt(key, addr, data) {
const buf = Buffer.concat([addr, addr, addr.subarray(0, 4)]);
2020-01-17 14:50:58 +00:00
const cipher = crypto.createCipheriv('aes-128-ecb', key, '');
2020-01-17 14:50:58 +00:00
cipher.setAutoPadding(false);
let ct = cipher.update(buf).toString('hex');
2020-01-17 14:50:58 +00:00
ct += cipher.final().toString('hex');
const ctBuf = Buffer.from(ct, 'hex');
2020-01-17 14:50:58 +00:00
let output = '';
for (let i = 0, { length } = data; i < length; i++) {
// eslint-disable-next-line no-bitwise
output += String.fromCharCode(data[i] ^ ctBuf[i % 16]);
2020-01-17 14:50:58 +00:00
}
return Buffer.from(output, 'ascii');
}
// eslint-disable-next-line class-methods-use-this
2020-01-17 14:50:58 +00:00
_reverseBuffer(src) {
const buffer = Buffer.allocUnsafe(src.length);
2020-01-17 14:50:58 +00:00
for (let i = 0, j = src.length - 1; i <= j; ++i, --j) {
buffer[i] = src[j];
buffer[j] = src[i];
2020-01-17 14:50:58 +00:00
}
return buffer;
2020-01-17 14:50:58 +00:00
}
}
2021-02-08 07:38:31 +01:00
module.exports = PlejBLEHandler;