94 lines
2.7 KiB
TypeScript

import { ICommand } from "./IDevice";
import { sleep } from "../Util/Sleep";
export interface IHarmonyDeviceProps {
id: string;
name: string;
harmony: any;
log: any;
commands: { [name: string]: ICommand };
}
export class HarmonyDevice {
private _harmony: any;
private _log: any;
private _commands: { [name: string]: ICommand } = {};
private _on: boolean;
constructor(props: IHarmonyDeviceProps) {
this.id = props.id;
this.name = props.name;
this._harmony = props.harmony;
this._on = false;
this._commands = props.commands;
}
public id: string;
public name: string;
public get on(): boolean {
return this._on;
}
public get commands(): { [name: string]: ICommand } {
return this._commands;
}
//Define device methods
public supportsCommand(commandName: string): boolean {
let command = this._commands[commandName];
return (command) ? true : false;
}
public getCommand(commandName: string): ICommand {
return this._commands[commandName];
}
public async powerOn(): Promise<void> {
let powerOnCommand: string = "Power On";
let powerToggleCommand: string = "Power Toggle";
if (this.supportsCommand(powerOnCommand)) {
await this.sendCommand(powerOnCommand);
this._on = true;
} else if (this.supportsCommand(powerToggleCommand)) {
await this.sendCommand(powerToggleCommand);
this._on = true;
}
}
public async powerOff(): Promise<void> {
let powerOffCommand: string = "Power Off";
let powerToggleCommand: string = "Power Toggle";
if (this.supportsCommand(powerOffCommand)) {
await this.sendCommand(powerOffCommand);
this._on = false;
} else if (this.supportsCommand(powerToggleCommand)) {
await this.sendCommand(powerToggleCommand);
this._on = false;
}
}
public async sendCommand(commandName: string): Promise<void> {
let command!: ICommand;
if (this.supportsCommand(commandName)) {
command = this.getCommand(commandName);
}
try {
//Execute command
//HACK to fix Harmon Kardon receiver not turning off
if (command.command === "PowerOff") {
for (let i = 0; i < 2; i++) {
await this._harmony.sendCommand(JSON.stringify(command));
}
}
await this._harmony.sendCommand(JSON.stringify(command));
//Sleep
await sleep(800);
} catch (err) {
this._log(`ERROR - error sending command to harmony: ${err}`);
}
}
}