Converted existing code to use platform agnostic device definitions.

This commit is contained in:
watsonb8
2019-07-29 12:05:30 -04:00
parent a539287b9e
commit 31c5c5b9e2
7 changed files with 237 additions and 171 deletions

View File

@ -1,58 +1,59 @@
import { Activity } from "../Models/Activity";
import { DeviceSetupItem } from "../Models/DeviceSetupItem";
import { Input, Matrix, Output } from "../Models/Matrix";
import { IDevice } from './IDevice';
import { RemoteKey } from '../Accessories/ControlUnit';
import { sleep } from '../Util/Sleep';
import { hub } from "..";
let Characteristic: HAPNodeJS.Characteristic;
const Harmony = require("harmony-websocket");
interface IDevice {
id: string,
name: string,
supportsCommand(commandName: string): boolean,
getCommand(commandName: string): string,
commands: { [name: string]: string };
on: boolean;
}
interface IActivityState {
currentActivity: Activity
}
interface IHarmonyDataProviderProps {
hubAddress: string,
interface IHubDataProviderProps {
harmonyHubAddress: string,
neeoHubAddress: string,
log: any,
matrix: Matrix
}
class HarmonyDataProvider {
private harmony: any;
class HubDataProvider {
//Harmony Fields
private harmonyHubAddress: string;
private harmonyConnected: boolean = false;
//Neeo Fields
private neeoHubAddress: string;
//Common Fields
private log: any;
private hubAddress: string = "";
private connected: boolean = false;
private devices: { [name: string]: IDevice; } = {};
private states: { [controlUnitName: string]: (IActivityState | undefined) } = {};
private matrix: Matrix;
constructor(props: IHarmonyDataProviderProps) {
constructor(props: IHubDataProviderProps) {
this.log = props.log;
this.hubAddress = props.hubAddress;
this.harmonyHubAddress = props.harmonyHubAddress;
this.neeoHubAddress = props.neeoHubAddress;
this.matrix = props.matrix;
this.harmony = new Harmony();
if (this.harmonyHubAddress) {
try {
this.connectHarmony(this.harmonyHubAddress);
} catch (err) {
this.log(`Error connecting to harmony hub at ${this.harmonyHubAddress}: ${err}`);
}
}
if (this.neeoHubAddress) {
//Listeners
this.harmony.on('open', () => {
this.connected = true;
});
this.harmony.on('close', () => {
this.connected = false;
});
}
this.connect();
}
/**
@ -82,10 +83,13 @@ class HarmonyDataProvider {
//Resolve device conflicts with other controlUnits
devicesToTurnOff = this.sanitizeDeviceList(devicesToTurnOff, controlUnitName);
//Turn off devices
devicesToTurnOff.forEach((device: IDevice) => {
this.powerOffDevice(device);
});
await Promise.all(
//Turn off devices
devicesToTurnOff.map(async (device: IDevice) => {
await device.powerOff();
})
);
this.states[controlUnitName] = undefined;
}
@ -113,7 +117,7 @@ class HarmonyDataProvider {
if (device && device.name && this.devices[device.name]) {
if (!device.on) {
this.log(`Turning on device ${device.name}`)
await this.powerOnDevice(device);
await device.powerOn();
}
}
}));
@ -125,7 +129,7 @@ class HarmonyDataProvider {
if (device && device.supportsCommand(`Input ${value.input}`)) {
let command: string = device.getCommand(`Input ${value.input}`);
await this.sendCommand(command);
await device.sendCommand(command);
}
})
);
@ -142,8 +146,8 @@ class HarmonyDataProvider {
//Route hdmi
if (matrixDevice.supportsCommand(inputCommandName) && matrixDevice.supportsCommand(outputCommandName)) {
await this.sendCommand(matrixDevice.getCommand(inputCommandName));
await this.sendCommand(matrixDevice.getCommand(outputCommandName));
await matrixDevice.sendCommand(matrixDevice.getCommand(inputCommandName));
await matrixDevice.sendCommand(matrixDevice.getCommand(outputCommandName));
}
}
@ -174,7 +178,7 @@ class HarmonyDataProvider {
if (device) {
if (device.on) {
this.log(`Turning off device ${device.name}`)
await this.powerOffDevice(device);
await device.powerOff();
}
}
})
@ -194,7 +198,7 @@ class HarmonyDataProvider {
if (this.states[controlUnitName]) {
let volumeDevice: IDevice = this.getDeviceFromName(this.states[controlUnitName]!.currentActivity.volumeDeviceId);
if (volumeDevice.supportsCommand(volumeUpCommand)) {
this.sendCommand(volumeDevice.getCommand(volumeUpCommand));
volumeDevice.sendCommand(volumeDevice.getCommand(volumeUpCommand));
}
}
}
@ -207,11 +211,46 @@ class HarmonyDataProvider {
if (this.states[controlUnitName]) {
let volumeDevice: IDevice = this.getDeviceFromName(this.states[controlUnitName]!.currentActivity.volumeDeviceId);
if (volumeDevice.supportsCommand(volumeDownCommand)) {
this.sendCommand(volumeDevice.getCommand(volumeDownCommand));
volumeDevice.sendCommand(volumeDevice.getCommand(volumeDownCommand));
}
}
}
/**
* Return if a control unit is active
* @param controlUnitName
*/
public getIsActive(controlUnitName: string): Activity | undefined {
return this.states[controlUnitName] ? this.states[controlUnitName]!.currentActivity : undefined;
}
/**
* Helper function to make sure no control unit depends on device list.
* @param devicesToTurnOn The list of devices to modify.
* @param controlUnitName The name of the control unit in question.
*/
private sanitizeDeviceList(devicesToTurnOn: Array<IDevice>, controlUnitName: string): Array<IDevice> {
for (let controlUnitKey in this.states) {
//Skip self
if (controlUnitKey === controlUnitName) {
continue;
}
let currentOtherState: IActivityState = this.states[controlUnitKey]!;
if (currentOtherState) {
currentOtherState.currentActivity.deviceSetupItems.forEach((value: DeviceSetupItem) => {
//there are devices to remove
if (devicesToTurnOn.some(e => e && e.name === value.deviceName)) {
let deviceToRemove: IDevice = devicesToTurnOn.filter(i => i.name === value.deviceName)[0];
delete devicesToTurnOn[devicesToTurnOn.indexOf(deviceToRemove)];
}
});
}
}
return devicesToTurnOn;
}
/**
* Send key press for current activity.
*
@ -263,93 +302,11 @@ class HarmonyDataProvider {
}
if (device && device.supportsCommand(commandName)) {
this.sendCommand(device.getCommand(commandName));
device.sendCommand(device.getCommand(commandName));
}
}
}
/**
* Return if a control unit is active
* @param controlUnitName
*/
public getIsActive(controlUnitName: string): Activity | undefined {
return this.states[controlUnitName] ? this.states[controlUnitName]!.currentActivity : undefined;
}
/**
* Connect to harmony and receive device info
*/
private connect = async () => {
await this.harmony.connect(this.hubAddress);
let self = this;
setTimeout(async function () {
if (self.connected) {
let devices: any = await self.harmony.getDevices();
try {
await Promise.all(
//Add each to dictionary
devices.map(async (dev: any) => {
//get commands
let commands: { [name: string]: string } = {};
let deviceCommands: any = await self.harmony.getDeviceCommands(dev.id);
deviceCommands.forEach((command: any) => {
commands[command.label] = command.action;
});
self.devices[dev.label] = {
id: dev.id,
name: dev.label,
commands: commands,
on: false,
//Define device methods
supportsCommand(commandName: string): boolean {
let command = commands[commandName];
return (command) ? true : false;
},
getCommand(commandName: string): string {
return commands[commandName];
}
}
}));
self.log(`Harmony data provider ready`);
} catch (err) {
self.log(`ERROR - error connecting to harmony: ${err}`);
}
}
}, 1000);
}
/**
* Power off a device (Power toggle if no power off).
*/
private powerOffDevice = async (device: IDevice) => {
let powerOffCommand: string = "Power Off";
let powerToggleCommand: string = "Power Toggle";
if (device && device.supportsCommand(powerOffCommand)) {
await this.sendCommand(device.getCommand(powerOffCommand));
device.on = false;
} else if (device && device.supportsCommand(powerToggleCommand)) {
await this.sendCommand(device.getCommand(powerToggleCommand));
device.on = false;
}
}
/**
* Power on a device (Power toggle if no power on).
*/
private powerOnDevice = async (device: IDevice) => {
let powerOnCommand: string = "Power On";
let powerToggleCommand: string = "Power Toggle";
if (device && device.supportsCommand(powerOnCommand)) {
await this.sendCommand(device.getCommand(powerOnCommand));
device.on = true;
} else if (device && device.supportsCommand(powerToggleCommand)) {
await this.sendCommand(device.getCommand(powerToggleCommand));
device.on = true;
}
}
/**
* Get the IDevice by name.
* @param deviceName The device to retrieve.
@ -359,48 +316,96 @@ class HarmonyDataProvider {
}
/**
* Helper function to make sure no control unit depends on device list.
* @param devicesToTurnOn The list of devices to modify.
* @param controlUnitName The name of the control unit in question.
* Connect to harmony hub and receive device info.
*/
private sanitizeDeviceList(devicesToTurnOn: Array<IDevice>, controlUnitName: string): Array<IDevice> {
for (let controlUnitKey in this.states) {
//Skip self
if (controlUnitKey === controlUnitName) {
continue;
}
let currentOtherState: IActivityState = this.states[controlUnitKey]!;
private connectHarmony = async (address: string): Promise<void> => {
let harmony: any = new Harmony();
//Listeners
harmony.on('open', () => {
this.harmonyConnected = true;
});
harmony.on('close', () => {
this.harmonyConnected = false;
});
await harmony.connect(address);
let self = this;
if (currentOtherState) {
currentOtherState.currentActivity.deviceSetupItems.forEach((value: DeviceSetupItem) => {
//there are devices to remove
if (devicesToTurnOn.some(e => e && e.name === value.deviceName)) {
let deviceToRemove: IDevice = devicesToTurnOn.filter(i => i.name === value.deviceName)[0];
delete devicesToTurnOn[devicesToTurnOn.indexOf(deviceToRemove)];
}
});
}
}
setTimeout(async function () {
if (self.harmonyConnected) {
let devices: any = await harmony.getDevices();
try {
await Promise.all(
//Add each to dictionary
devices.map(async (dev: any) => {
//get commands
let commands: { [name: string]: string } = {};
let deviceCommands: any = await harmony.getDeviceCommands(dev.id);
deviceCommands.forEach((command: any) => {
commands[command.label] = command.action;
});
self.devices[dev.label] = {
id: dev.id,
name: dev.label,
commands: commands,
harmony: harmony,
hubType: "Harmony",
log: self.log,
on: false,
//Define device methods
supportsCommand(commandName: string): boolean {
let command = commands[commandName];
return (command) ? true : false;
},
getCommand(commandName: string): string {
return commands[commandName];
},
async powerOn(): Promise<void> {
let powerOnCommand: string = "Power On";
let powerToggleCommand: string = "Power Toggle";
if (this.supportsCommand(powerOnCommand)) {
await this.sendCommand(this.getCommand(powerOnCommand));
this.on = true;
} else if (this.supportsCommand(powerToggleCommand)) {
await this.sendCommand(this.getCommand(powerToggleCommand));
this.on = true;
}
},
async powerOff(): Promise<void> {
let powerOffCommand: string = "Power Off";
let powerToggleCommand: string = "Power Toggle";
if (this.supportsCommand(powerOffCommand)) {
await this.sendCommand(this.getCommand(powerOffCommand));
this.on = false;
} else if (this.supportsCommand(powerToggleCommand)) {
await this.sendCommand(this.getCommand(powerToggleCommand));
this.on = false;
}
},
async sendCommand(command: string): Promise<void> {
try {
//Execute command
let response = await this.harmony.sendCommand(JSON.stringify(command));
return devicesToTurnOn;
//Sleep
await sleep(800);
} catch (err) {
this.log(`ERROR - error sending command to harmony: ${err}`);
}
}
}
}));
self.log(`Harmony data provider ready`);
} catch (err) {
self.log(`ERROR - error connecting to harmony: ${err}`);
}
}
}, 1000);
}
/**
* Send a command to the harmony hub.
* @param command The command to send.
*/
private sendCommand = async (command: string) => {
try {
//Execute command
let response = await this.harmony.sendCommand(JSON.stringify(command));
//Sleep
await sleep(800);
} catch (err) {
this.log(`ERROR - error sending command to harmony: ${err}`);
}
private connectNeeo = async (address: string): Promise<void> => {
}
}
export default HarmonyDataProvider;
export default HubDataProvider;

View File

@ -0,0 +1,16 @@
import { hub } from "..";
export interface IDevice {
id: string,
name: string,
harmony: any | undefined,
log: any,
hubType: hub
supportsCommand(commandName: string): boolean,
getCommand(commandName: string): string,
sendCommand(command: string): void,
powerOn(): Promise<void>,
powerOff(): Promise<void>,
commands: { [name: string]: string };
on: boolean;
}