Skip to content

Commit

Permalink
Refactor to async/await
Browse files Browse the repository at this point in the history
  • Loading branch information
Herlix committed Jun 22, 2024
1 parent a753fc7 commit 1ed25c7
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 273 deletions.
67 changes: 14 additions & 53 deletions src/PlejdHbAccessory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ export class PlejdHbAccessory {
private readonly accessory: PlatformAccessory,
public readonly device: Device,
) {
platform.log.debug(
`Adding handler for a ${this.device.model} with id ${this.device.identifier}`,
);

this.state = {
brightness: accessory.context.brightness ?? 100,
isOn: accessory.context.isOn ?? false,
Expand Down Expand Up @@ -74,71 +70,36 @@ export class PlejdHbAccessory {
}

updateState = (isOn: boolean, brightness?: number) => {
this.platform.log.info(`Got trigger on ${this.device.name} | to ${isOn ? 'On' : 'off'} | brightness: ${brightness}`);
this.platform.log.debug(`Updating Homekit state from ${this.device.name} device state`);
this.state.isOn = isOn;
this.platform.log.debug('updateState | Sending isOn', isOn);

this.service
.getCharacteristic(this.platform.Characteristic.On)
.updateValue(isOn);

if (brightness) {
this.state.brightness = Math.round(brightness);
this.platform.log.debug(
'update state | Sending brightness',
this.state.brightness,
);
this.service
.getCharacteristic(this.platform.Characteristic.Brightness)
.updateValue(this.state.brightness);
}

this.accessory.context = this.state;
this.platform.log.debug(`State updated | ${JSON.stringify(this.state)}`);
};

private setOn = async (value: CharacteristicValue) => {
const newVal = value as boolean;
this.platform.log.info(
`Updating state | ${this.device.name} | to ${
newVal ? 'On' : 'off'
} | from ${this.state.isOn ? 'On' : 'Off'}`,
);
this.updateState(newVal, this.state.brightness);
this.platform.plejdService?.updateState(
this.device.identifier,
newVal,
null,
);
};
private setOn = (value: CharacteristicValue) => this.platform.plejdService?.updateState(
this.device.identifier,
value as boolean,
null,
);

private getOn = async (): Promise<CharacteristicValue> => {
this.platform.log.debug(
'Get Characteristic On',
this.device.name,
this.state.isOn,
);
return this.state.isOn;
};
private getOn = (): CharacteristicValue => this.state.isOn;

private setBrightness = async (value: CharacteristicValue) => {
const newVal = value as number; // Number between 1-100
this.platform.log.debug(
`Updating brightness | ${this.device.name} | to ${newVal} | from ${this.state.brightness}`,
);
this.updateState(this.state.isOn, newVal);
this.platform.plejdService?.updateState(
this.device.identifier,
this.state.isOn,
newVal,
);
};
private setBrightness = (value: CharacteristicValue) => this.platform.plejdService?.updateState(
this.device.identifier,
this.state.isOn,
value as number,
);

private getBrightness = async (): Promise<CharacteristicValue> => {
this.platform.log.debug(
'Get Characteristic Brightness',
this.device.name,
this.state.brightness,
);
return this.state.brightness;
};
private getBrightness = (): CharacteristicValue => this.state.brightness;
}
39 changes: 13 additions & 26 deletions src/PlejdHbPlatform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,37 +31,32 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
// this is used to track restored cached accessories
public readonly accessories: PlatformAccessory[] = [];

public readonly plejdHandlers: PlejdHbAccessory[] = [];
public readonly plejdHbAccessories: PlejdHbAccessory[] = [];

constructor(
public readonly log: Logger,
public readonly config: PlatformConfig,
public readonly homebridgeApi: API,
) {
this.log.debug('Finished initializing platform:', this.config.platform);

homebridgeApi.on('didFinishLaunching', this.configurePlejd);
this.Characteristic = homebridgeApi.hap.Characteristic;
this.Service = homebridgeApi.hap.Service;
}

configurePlejd = () => {
configurePlejd = async () => {
if (this.config.password && this.config.site && this.config.username) {
this.log.info('Using login information to fetch devices & crypto key');
this.log.info(
'Any devices added manually will update the downloaded devices',
);
'Using login information to fetch devices & crypto key\n' +
'Any devices added manually will override the remote site information');
const pApi = new PlejdRemoteApi(
this.log,
this.config.site,
this.config.username,
this.config.password,
true,
);
pApi
.getPlejdRemoteSite()
.then((site) => this.configureDevices(this.log, this.config, site))
.catch((e) => this.log.error(`Plejd remote access error: ${e}`));
const site = await pApi.getPlejdRemoteSite();
this.configureDevices(this.log, this.config, site);
} else if (
this.config.crypto_key &&
this.config.devices &&
Expand All @@ -80,7 +75,6 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
const devices = (config.devices as Device[]) || [];

if (site) {
this.log.info('Using remote site information for:', site.site.title);
config.crypto_key = site.plejdMesh.cryptoKey;
const items: Device[] = [];
// Extract devices
Expand Down Expand Up @@ -159,8 +153,8 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
cryptoKey: cryptoKey,
};

log.info('Plejd Crypto Key:', config.crypto_key);
log.info(
log.debug('Plejd Crypto Key:', config.crypto_key);
log.debug(
'Plejd Devices connected to HomeKit:',
this.userInputConfig.devices,
);
Expand All @@ -179,7 +173,6 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
* It should be used to setup event handlers for characteristics and update respective values.
*/
configureAccessory = (accessory: PlatformAccessory) => {
this.log.info('Loading accessory from cache | ', accessory.displayName);
this.accessories.push(accessory);
};

Expand All @@ -206,7 +199,7 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
);

if (existingAccessory) {
this.plejdHandlers.push(
this.plejdHbAccessories.push(
new PlejdHbAccessory(this, existingAccessory, device),
);
} else {
Expand All @@ -217,7 +210,6 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {

addNewDevice = (device: Device) => {
let name = device.name;
this.log.info('Adding new accessory |', name);
if (device.room) {
name = device.room + ' - ' + name;
}
Expand All @@ -228,7 +220,7 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
);
accessory.context.device = device;
// See above.
this.plejdHandlers.push(
this.plejdHbAccessories.push(
new PlejdHbAccessory(this, accessory, device),
);

Expand Down Expand Up @@ -256,10 +248,10 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
const device = this.userInputConfig!.devices.find(
(dev) => dev.identifier === identifier,
);
const plejdHandler = this.plejdHandlers.find(
const plejdHbAccessory = this.plejdHbAccessories.find(
(dev) => dev.device.identifier === identifier,
);
if (existingAccessory && device && plejdHandler) {
if (existingAccessory && device && plejdHbAccessory) {
if (device.isDimmer) {
const ser = existingAccessory.getService(this.Service.Lightbulb);

Expand Down Expand Up @@ -287,16 +279,11 @@ export class PlejdHbPlatform implements DynamicPlatformPlugin {
?.updateValue(isOn);
}

plejdHandler.updateState(isOn, brightness);
plejdHbAccessory.updateState(isOn, brightness);
} else {
if (device) {
this.addNewDevice(device);
this.onPlejdUpdates(identifier, isOn, brightness);
} else {
this.log.info(
'Unable find HomKit device associated with incoming Plejd update |',
device,
);
}
}
};
Expand Down
10 changes: 1 addition & 9 deletions src/plejdApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,6 @@ export default class PlejdRemoteApi {
}

const data = await response.json();
this.log.debug('plejd-api: got session token response');

if (!data.sessionToken) {
throw new Error('no session token received.');
}
Expand All @@ -90,8 +88,6 @@ export default class PlejdRemoteApi {
}

private async getSites(token: string): Promise<SiteDto> {
this.log.debug('Sending POST to ' + API_BASE_URL + API_SITE_LIST_URL);

const response = await fetch(API_BASE_URL + API_SITE_LIST_URL, {
method: 'POST',
headers: {
Expand All @@ -106,9 +102,8 @@ export default class PlejdRemoteApi {
}

const data = await response.json();
this.log.debug('plejd-api: got detailed sites response');
const site = data.result.find(
(x: any) => x.site.title === this.siteName,
(x: SiteDto) => x.site.title === this.siteName,
);

if (!site) {
Expand All @@ -119,8 +114,6 @@ export default class PlejdRemoteApi {
}

private async getSite(site: SiteDto, token: string): Promise<Site> {
this.log.debug('Sending POST to ' + API_BASE_URL + API_SITE_DETAILS_URL);

const response = await fetch(API_BASE_URL + API_SITE_DETAILS_URL, {
method: 'POST',
headers: {
Expand All @@ -136,7 +129,6 @@ export default class PlejdRemoteApi {
}

const data = await response.json();
this.log.debug('plejd-api: got site details response');
if (data.result.length === 0) {
throw new Error('No devices found');
}
Expand Down
Loading

0 comments on commit 1ed25c7

Please sign in to comment.