resolved issue with not connect error msg

This commit is contained in:
Marcus Westin 2019-12-13 13:32:05 +01:00
parent bb1b53d4ff
commit a79f1ca62c
2 changed files with 18 additions and 12 deletions

12
main.js
View file

@ -41,20 +41,20 @@ async function main() {
}); });
// subscribe to changes from HA // subscribe to changes from HA
client.on('stateChanged', (deviceId, state) => { client.on('stateChanged', async (deviceId, state) => {
if (state) { if (state) {
controller.turnOn(deviceId); await controller.turnOn(deviceId);
} }
else { else {
controller.turnOff(deviceId); await controller.turnOff(deviceId);
} }
}); });
client.on('brightnessChanged', (deviceId, brightness) => { client.on('brightnessChanged', async (deviceId, brightness) => {
if (brightness > 0) { if (brightness > 0) {
controller.turnOn(deviceId, brightness); await controller.turnOn(deviceId, brightness);
} }
else { else {
controller.turnOff(deviceId); await controller.turnOff(deviceId);
} }
}); });

View file

@ -254,10 +254,10 @@ class Controller extends EventEmitter {
} }
} }
turnOn(id, brightness) { async turnOn(id, brightness) {
if (!this.isConnected) { if (!this.isConnected) {
console.log('error: not connected'); console.log('warning: not connected, will connect. might take a few seconds.');
return; await this.connect();
} }
logger('turning on ' + id + ' at brightness ' + brightness); logger('turning on ' + id + ' at brightness ' + brightness);
@ -274,10 +274,10 @@ class Controller extends EventEmitter {
this.write(payload); this.write(payload);
} }
turnOff(id) { async turnOff(id) {
if (!this.isConnected) { if (!this.isConnected) {
console.log('error: not connected'); console.log('warning: not connected, will connect. might take a few seconds.');
return; await this.connect();
} }
logger('turning off ' + id); logger('turning off ' + id);
@ -317,6 +317,12 @@ class Controller extends EventEmitter {
var ping = crypto.randomBytes(1); var ping = crypto.randomBytes(1);
try { try {
// make sure we're connected, otherwise, return false and reconnect
if (this.peripheral.state !== 'connected') {
callback(false);
return;
}
this.pingCharacteristic.write(ping, false, (err) => { this.pingCharacteristic.write(ping, false, (err) => {
if (err) { if (err) {
console.log('error: unable to send ping: ' + err); console.log('error: unable to send ping: ' + err);