2020-05-03 17:31:40 -04:00

75 lines
2.3 KiB
TypeScript

import { HarmonyDevice } from './HarmonyDevice';
const Harmony = require("harmony-websocket");
import { ICommand } from './IDevice';
import { EventEmitter } from 'events';
export class HarmonyHub extends EventEmitter {
private _devices: { [deviceName: string]: HarmonyDevice } = {}
private _ip: string;
private _harmony: any;
private _log: any;
private _name: string;
constructor(hubName: string, ipAddress: string, log: any) {
super();
this._ip = ipAddress;
this._log = log;
this._name = hubName;
}
public get devices(): { [deviceName: string]: HarmonyDevice } {
return this._devices;
}
public get hubName(): string {
return this._name;
}
public getDeviceByName = (deviceName: string): HarmonyDevice => {
return this._devices[deviceName];
}
public initialize = async () => {
this._harmony = new Harmony();
await this._harmony.connect(this._ip);
this._harmony.on('stateDigest', (data: any) => {
console.log(data);
});
this._harmony.on('automationState', (data: any) => {
console.log(data);
});
//Gather devices
let devices: any = await this._harmony.getDevices();
try {
await Promise.all(
//Add each to dictionary
devices.map(async (dev: any) => {
//get commands
let commands: { [name: string]: ICommand } = {};
let deviceCommands: any = await this._harmony.getDeviceCommands(dev.id);
deviceCommands.forEach((command: any) => {
commands[command.label] = command.action;
});
this._devices[dev.label] = new HarmonyDevice({
id: dev.id,
name: dev.label,
commands: commands,
log: this._log,
harmony: this._harmony
});
}));
this.emit("Ready");
} catch (err) {
this._log(`ERROR - error connecting to harmony: ${err}`);
}
}
private connect = async (): Promise<void> => {
await this._harmony.Connect(this._ip);
}
}