From b5bd9c4590d4a705ec1de4a437c45fbe9e1d54c8 Mon Sep 17 00:00:00 2001 From: Octavian Ruda Date: Mon, 4 Oct 2021 20:14:00 +0300 Subject: [PATCH] Respond to power state change action in maximum set time #382 --- lib/options/switch.js | 2 +- lib/remote.js | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/options/switch.js b/lib/options/switch.js index 0ba5294..86d824f 100644 --- a/lib/options/switch.js +++ b/lib/options/switch.js @@ -27,7 +27,7 @@ module.exports = function(service, accessory) { await Remote.setPower(true); MainAccessory.services.main.updateValue(true); - await new Promise(resolve => setTimeout(resolve, 1500)); + await new Promise(resolve => setTimeout(resolve, 1000)); } }, diff --git a/lib/remote.js b/lib/remote.js index 519ba31..5bb3d74 100644 --- a/lib/remote.js +++ b/lib/remote.js @@ -20,6 +20,7 @@ const { GetApplicationsFailedError } = require('./errors'); +const RACE_TIMEOUT = 1500; const TURNING_TIMEOUT = 1000 * 5; const STANDBY_TIMEOUT = 1000 * 17; @@ -120,7 +121,7 @@ module.exports = class Remote { } async setPower(value) { - return value ? await this._turnOn() : await this._turnOff(); + return await this._race(value ? this._turnOn() : this._turnOff()); } async getArtPower() { @@ -392,4 +393,16 @@ module.exports = class Remote { this.device.log.debug(error.stack); }); } + + /** + * Promise with a timeout + * @param {Promise} promise + * @param {number} timeout + * @return {Promise} + */ + _race(promise, timeout = RACE_TIMEOUT) { + const race = new Promise((resolve) => setTimeout(resolve, timeout, true)); + + return Promise.race([promise, race]); + } } \ No newline at end of file