multiple fixes for improved lifecycle and errors

* Init and _internalInit is actually awaitable
* this.bleDevices is reset on init
* check for actual data in write to preven length of undefined
* Throttled re-inits on write-errors.
This commit is contained in:
John Lindahl 2021-01-13 01:47:05 +01:00 committed by GitHub
parent aa46579f7a
commit 126c393cee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -85,6 +85,7 @@ class PlejdService extends EventEmitter {
this.objectManager.removeAllListeners(); this.objectManager.removeAllListeners();
} }
this.bleDevices = [];
this.connectedDevice = null; this.connectedDevice = null;
this.characteristics = { this.characteristics = {
@ -146,10 +147,7 @@ class PlejdService extends EventEmitter {
console.log('plejd-ble: error: failed to start discovery. Make sure no other add-on is currently scanning.'); console.log('plejd-ble: error: failed to start discovery. Make sure no other add-on is currently scanning.');
return; return;
} }
return new Promise(resolve => setTimeout(() => resolve(this._internalInit()), this.connectionTimeout * 1000));
setTimeout(async () => {
await this._internalInit();
}, this.connectionTimeout * 1000);
} }
async _internalInit() { async _internalInit() {
@ -379,8 +377,20 @@ class PlejdService extends EventEmitter {
this.characteristics.lastData.StartNotify(); this.characteristics.lastData.StartNotify();
} }
async throttledInit(delay) {
if(this.delayedInit){
return this.delayedInit;
}
this.delayedInit = new Promise((resolve) => setTimeout(async () => {
const result = await this.init();
this.delayedInit = null;
resolve(result)
}, delay))
return this.delayedInit;
}
async write(data, retry = true) { async write(data, retry = true) {
if (!this.plejdService || !this.characteristics.data) { if (!data || !this.plejdService || !this.characteristics.data) {
return; return;
} }
@ -393,16 +403,13 @@ class PlejdService extends EventEmitter {
setTimeout(() => this.write(data, retry), 1000); setTimeout(() => this.write(data, retry), 1000);
return; return;
} }
console.log('plejd-ble: write failed ' + err); console.log('plejd-ble: write failed ' + err);
setTimeout(async () => { await this.throttledInit(this.connectionTimeout * 1000);
await this.init();
if (retry) { if(retry){
logger('reconnected and retrying to write'); logger('reconnected and retrying to write');
await this.write(data, false); await this.write(data, false);
} }
}, this.connectionTimeout * 1000);
} }
} }