diff --git a/src/Accessories/ControlUnit.ts b/src/Accessories/ControlUnit.ts index bce2a5d..9dba6ac 100644 --- a/src/Accessories/ControlUnit.ts +++ b/src/Accessories/ControlUnit.ts @@ -1,8 +1,11 @@ import { PlatformAccessory, RemoteController, Service } from "homebridge"; -import HarmonyDataProvider from "../DataProviders/HarmonyDataProvider"; +import HarmonyDataProvider from "../DataProviders/harmonyDataProvider"; import { IActivity } from "../Models/Config"; import { Platform } from "../platform"; -import callbackify from "../Util/Callbackify"; +import { ActivityService } from "../Services/activityService"; +import { CommandService } from "../Services/commandService"; +import { VolumeService } from "../Services/volumeService"; +import callbackify from "../Util/callbackify"; /** * Enum describing remote key presses from homebridge. @@ -27,7 +30,9 @@ export class ControlUnit { constructor( private readonly _platform: Platform, private readonly _accessory: PlatformAccessory, - private _dataProvider: HarmonyDataProvider, + private _activityService: ActivityService, + private _commandService: CommandService, + private _volumeService: VolumeService, private _activities: Array ) { this._accessory @@ -129,11 +134,11 @@ export class ControlUnit { private onSetAccessoryActive = async (value: any) => { switch (value) { case 0: - this._dataProvider.powerOff(this._accessory.displayName); + this._activityService.stopCurrentActivity(this._accessory.displayName); break; //Turn on with first activity case 1: - this._dataProvider.powerOn( + this._activityService.startActivity( this._accessory.displayName, this._activities[0] ); @@ -155,14 +160,14 @@ export class ControlUnit { * Event handler for SET remote key */ private onSetRemoteKey = async (key: any) => { - this._dataProvider.sendKeyPress(this._accessory.displayName, key); + this._commandService.sendKeyPress(this._accessory.displayName, key); }; /** * Event handler for SET active identifier characteristic */ private onSetActiveIdentifier = async (identifier: any) => { - this._dataProvider.startActivity( + this._activityService.startActivity( this._accessory.displayName, this._activities[identifier] ); @@ -172,7 +177,7 @@ export class ControlUnit { * Event handler for GET active identifier characteristic */ private onGetActiveIdentifier = async () => { - let currentActivity: IActivity = this._dataProvider.getIsActive( + let currentActivity: IActivity = this._activityService.getIsActive( this._accessory.displayName )!; let identifier: number = 0; @@ -230,10 +235,10 @@ export class ControlUnit { private onSetVolumeSelector = async (value: any) => { switch (value) { case 0: - this._dataProvider.volumeUp(this._accessory.displayName); + this._volumeService.volumeUp(this._accessory.displayName); break; case 1: - this._dataProvider.volumeDown(this._accessory.displayName); + this._volumeService.volumeDown(this._accessory.displayName); break; } }; diff --git a/src/Accessories/DeviceButton.ts b/src/Accessories/DeviceButton.ts index cf02bf4..bbd7171 100644 --- a/src/Accessories/DeviceButton.ts +++ b/src/Accessories/DeviceButton.ts @@ -1,7 +1,7 @@ import { PlatformAccessory, Service } from "homebridge"; -import HarmonyDataProvider from "../DataProviders/HarmonyDataProvider"; +import HarmonyDataProvider from "../DataProviders/harmonyDataProvider"; import { IDeviceButton } from "../Models/Config"; -import { HarmonyDevice } from "../Models/HarmonyDevice"; +import { HarmonyDevice } from "../Models/harmonyDevice"; import { Platform } from "../platform"; export class DeviceButton { diff --git a/src/Accessories/Sequence.ts b/src/Accessories/Sequence.ts index ea6992c..c7b391d 100644 --- a/src/Accessories/Sequence.ts +++ b/src/Accessories/Sequence.ts @@ -5,9 +5,9 @@ import { PlatformAccessory, Service, } from "homebridge"; -import HarmonyDataProvider from "../DataProviders/HarmonyDataProvider"; -import { ISequence } from "../Models/Config/ISequence"; -import { HarmonyDevice } from "../Models/HarmonyDevice"; +import HarmonyDataProvider from "../DataProviders/harmonyDataProvider"; +import { ISequence } from "../Models/Config/sequence"; +import { HarmonyDevice } from "../Models/harmonyDevice"; import { Platform } from "../platform"; import { sleep } from "../Util"; diff --git a/src/Accessories/index.ts b/src/Accessories/index.ts index 4c98bbf..bf68e76 100644 --- a/src/Accessories/index.ts +++ b/src/Accessories/index.ts @@ -1,2 +1,2 @@ -export { ControlUnit } from './ControlUnit'; -export { DeviceButton } from './DeviceButton'; \ No newline at end of file +export { ControlUnit } from "./controlUnit"; +export { DeviceButton } from "./deviceButton"; diff --git a/src/DataProviders/HarmonyDataProvider.ts b/src/DataProviders/HarmonyDataProvider.ts index 1273fdb..2dbdd55 100644 --- a/src/DataProviders/HarmonyDataProvider.ts +++ b/src/DataProviders/HarmonyDataProvider.ts @@ -1,12 +1,12 @@ -import { IActivity } from "../Models/Config/IActivity"; -import { IDeviceSetupItem } from "../Models/Config/IDeviceSetupItem"; -import { IInput, IMatrix, IOutput } from "../Models/Config/IMatrix"; -import { RemoteKey } from "../Accessories/ControlUnit"; +import { IActivity } from "../Models/Config/activity"; +import { IDeviceSetupItem } from "../Models/Config/deviceSetupItem"; +import { IInput, IMatrix, IOutput } from "../Models/Config/matrix"; +import { RemoteKey } from "../Accessories/controlUnit"; import { EventEmitter } from "events"; -import { IHub } from "../Models/Config/IHub"; -import { IDeviceConfig } from "../Models/Config/IDeviceConfig"; -import { HarmonyDevice } from "../Models/HarmonyDevice"; -import { HarmonyHub } from "../Models/HarmonyHub"; +import { IHub } from "../Models/Config/hub"; +import { IDeviceConfig } from "../Models/Config/deviceConfig"; +import { HarmonyDevice } from "../Models/harmonyDevice"; +import { HarmonyHub } from "../Models/harmonyHub"; import { IConfig } from "../Models/Config"; import { inject, injectable } from "tsyringe"; import { Logger, Logging } from "homebridge"; @@ -47,6 +47,7 @@ class HarmonyDataProvider extends EventEmitter { // this._deviceConfigs = props.deviceConfigs; this.connect(_config.Hubs); + this.emitInfo(); } // public get devicesByHub(): { [hubName: string]: { [deviceName: string]: HarmonyDevice } } { @@ -402,6 +403,24 @@ class HarmonyDataProvider extends EventEmitter { return devicesToTurnOn; } + + private emitInfo(): void { + //Emit devices if requested + this._log.info("All hubs connected"); + if (this._config.EmitDevicesOnStartup) { + const hubs = this.hubs; + Object.values(hubs).forEach((hub: HarmonyHub) => { + const deviceDictionary = hub.devices; + this._log.info(`${hub.hubName}`); + Object.values(deviceDictionary).forEach((device: HarmonyDevice) => { + this._log.info(` ${device.name} : ${device.id}`); + Object.keys(device.commands).forEach((command: string) => { + this._log.info(` ${command}`); + }); + }); + }); + } + } } export default HarmonyDataProvider; diff --git a/src/DataProviders/harmonyDataProvider2.ts b/src/DataProviders/harmonyDataProvider2.ts new file mode 100644 index 0000000..5defa49 --- /dev/null +++ b/src/DataProviders/harmonyDataProvider2.ts @@ -0,0 +1,105 @@ +import { Logging } from "homebridge"; +import { inject } from "tsyringe"; +import { IConfig, IMatrix } from "../Models/Config"; +import { IDeviceConfig } from "../Models/Config/deviceConfig"; +import { IHub } from "../Models/Config/hub"; +import { HarmonyDevice } from "../Models/harmonyDevice"; +import { HarmonyHub } from "../Models/harmonyHub"; + +export class HarmonyDataProvider2 { + private _matrix: IMatrix; + private _hubs: { [hubName: string]: HarmonyHub } = {}; + private _hubsByDevice: { [deviceName: string]: string } = {}; + + constructor( + @inject("IConfig") private _config: IConfig, + @inject("log") private _log: Logging + ) { + this._matrix = _config.Matrix; + _config.Devices.forEach((deviceConfig: IDeviceConfig) => { + this._hubsByDevice[deviceConfig.Name] = deviceConfig.Hub; + }); + // this._deviceConfigs = props.deviceConfigs; + + this.connect(_config.Hubs); + this.emitInfo(); + } + + public async turnOnDevices(devices: Array): Promise { + await Promise.all( + devices.map(async (device: HarmonyDevice) => { + if (device && device.name) { + if (!device.on) { + this._log.info(`Turning on device ${device.name}`); + await device.powerOn(); + } + } + }) + ); + } + + public async turnOffDevices(devices: Array) { + await Promise.all( + //Turn off devices + devices.map(async (device: HarmonyDevice) => { + if (device) { + if (device.on) { + this._log.info(`Turning off device ${device.name}`); + await device.powerOff(); + } + } + }) + ); + } + + /** + * Get the IDevice by name. + * @param deviceName The device to retrieve. + */ + public getDeviceFromName(deviceName: string): HarmonyDevice { + let device: HarmonyDevice | undefined; + try { + device = + this._hubs[this._hubsByDevice[deviceName]].getDeviceByName(deviceName); + } catch (err) { + this._log.info(`Error retrieving device from hub: ${err}`); + } + + return device!; + } + + private connect = async (hubs: Array) => { + let readyCount = 0; + await Promise.all( + hubs.map(async (hub: IHub): Promise => { + const newHarmonyHub = new HarmonyHub(hub.Name, hub.Ip, this._log.info); + this._hubs[hub.Name] = newHarmonyHub; + newHarmonyHub.on("Ready", () => { + readyCount++; + if (readyCount === Object.keys(this._hubs).length) { + // this.emit("Ready"); + } + }); + await newHarmonyHub.initialize(); + }) + ); + }; + + private emitInfo(): void { + //Emit devices if requested + this._log.info("All hubs connected"); + if (this._config.EmitDevicesOnStartup) { + const hubs = this._hubs; + Object.values(hubs).forEach((hub: HarmonyHub) => { + const deviceDictionary = hub.devices; + this._log.info(`${hub.hubName}`); + Object.values(deviceDictionary).forEach((device: HarmonyDevice) => { + this._log.info(` ${device.name} : ${device.id}`); + Object.keys(device.commands).forEach((command: string) => { + this._log.info(` ${command}`); + }); + }); + }); + } + } +} diff --git a/src/DataProviders/stateDataProvider.ts b/src/DataProviders/stateDataProvider.ts new file mode 100644 index 0000000..0e9bc13 --- /dev/null +++ b/src/DataProviders/stateDataProvider.ts @@ -0,0 +1,31 @@ +import { inject, injectable } from "tsyringe"; +import { IActivityState } from "../Models/activityState"; +import { IActivity } from "../Models/Config"; + +@injectable() +export class StateDataProvider { + private _states: { + [controlUnitName: string]: IActivityState | undefined; + } = {}; + + public updateState(activity: IActivity, controlUnitName: string): void { + this._states[controlUnitName] = { currentActivity: activity }; + } + + public removeState(controlUnitName: string): void { + this._states[controlUnitName] = undefined; + } + + public getState(controlUnitName: string) { + if (!this._states[controlUnitName]) { + return undefined; + } + return this._states[controlUnitName]!.currentActivity; + } + + public get states(): { + [controlUnitName: string]: IActivityState | undefined; + } { + return this._states; + } +} diff --git a/src/Models/Config/IActivity.ts b/src/Models/Config/IActivity.ts deleted file mode 100644 index a151d25..0000000 --- a/src/Models/Config/IActivity.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { IDeviceSetupItem } from './IDeviceSetupItem'; - -export interface IActivity { - OutputDevice: string; - VolumeDevice: string; - ControlDevice: string; - DisplayName: string; - DeviceSetupList: Array; - UseMatrix: boolean; - -} \ No newline at end of file diff --git a/src/Models/Config/activity.ts b/src/Models/Config/activity.ts new file mode 100644 index 0000000..2dd52c0 --- /dev/null +++ b/src/Models/Config/activity.ts @@ -0,0 +1,10 @@ +import { IDeviceSetupItem } from "./deviceSetupItem"; + +export interface IActivity { + OutputDevice: string; + VolumeDevice: string; + ControlDevice: string; + DisplayName: string; + DeviceSetupList: Array; + UseMatrix: boolean; +} diff --git a/src/Models/Config/IConfig.ts b/src/Models/Config/config.ts similarity index 58% rename from src/Models/Config/IConfig.ts rename to src/Models/Config/config.ts index 95832e8..21094e7 100644 --- a/src/Models/Config/IConfig.ts +++ b/src/Models/Config/config.ts @@ -1,9 +1,9 @@ -import { IMatrix } from "./IMatrix"; -import { IActivity } from "./IActivity"; -import { IDeviceButton } from "./IDeviceButton"; -import { IDeviceConfig } from "./IDeviceConfig"; -import { IHub } from "./IHub"; -import { ISequence } from "./ISequence"; +import { IMatrix } from "./matrix"; +import { IActivity } from "./activity"; +import { IDeviceButton } from "./deviceButton"; +import { IDeviceConfig } from "./deviceConfig"; +import { IHub } from "./hub"; +import { ISequence } from "./sequence"; export interface IControlUnit { DisplayName: string; diff --git a/src/Models/Config/IDeviceButton.ts b/src/Models/Config/deviceButton.ts similarity index 100% rename from src/Models/Config/IDeviceButton.ts rename to src/Models/Config/deviceButton.ts diff --git a/src/Models/Config/IDeviceConfig.ts b/src/Models/Config/deviceConfig.ts similarity index 100% rename from src/Models/Config/IDeviceConfig.ts rename to src/Models/Config/deviceConfig.ts diff --git a/src/Models/Config/IDeviceSetupItem.ts b/src/Models/Config/deviceSetupItem.ts similarity index 100% rename from src/Models/Config/IDeviceSetupItem.ts rename to src/Models/Config/deviceSetupItem.ts diff --git a/src/Models/Config/IHub.ts b/src/Models/Config/hub.ts similarity index 100% rename from src/Models/Config/IHub.ts rename to src/Models/Config/hub.ts diff --git a/src/Models/Config/index.ts b/src/Models/Config/index.ts index 5bd6c00..da105a2 100644 --- a/src/Models/Config/index.ts +++ b/src/Models/Config/index.ts @@ -1,5 +1,5 @@ -export * from './IActivity'; -export * from './IConfig'; -export * from './IDeviceButton'; -export * from './IDeviceSetupItem'; -export * from './IMatrix'; \ No newline at end of file +export * from "./activity"; +export * from "./config"; +export * from "./deviceButton"; +export * from "./deviceSetupItem"; +export * from "./matrix"; diff --git a/src/Models/Config/IMatrix.ts b/src/Models/Config/matrix.ts similarity index 100% rename from src/Models/Config/IMatrix.ts rename to src/Models/Config/matrix.ts diff --git a/src/Models/Config/ISequence.ts b/src/Models/Config/sequence.ts similarity index 100% rename from src/Models/Config/ISequence.ts rename to src/Models/Config/sequence.ts diff --git a/src/Models/HarmonyDevice.ts b/src/Models/HarmonyDevice.ts index cecece4..7fed46d 100644 --- a/src/Models/HarmonyDevice.ts +++ b/src/Models/HarmonyDevice.ts @@ -1,94 +1,93 @@ -import { ICommand } from "./IDevice"; -import { sleep } from "../Util/Sleep"; +import { ICommand } from "./device"; +import { sleep } from "../Util/sleep"; export interface IHarmonyDeviceProps { - id: string; - name: string; - harmony: any; - log: any; - commands: { [name: string]: ICommand }; + 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; + 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; + 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 { + 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 { + 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 { + let command!: ICommand; + if (this.supportsCommand(commandName)) { + command = this.getCommand(commandName); } - 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 { - 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; + 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}`); } - - public async powerOff(): Promise { - 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 { - 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}`); - } - } -} \ No newline at end of file + } +} diff --git a/src/Models/HarmonyHub.ts b/src/Models/HarmonyHub.ts index e390f32..49c8b77 100644 --- a/src/Models/HarmonyHub.ts +++ b/src/Models/HarmonyHub.ts @@ -1,75 +1,75 @@ -import { HarmonyDevice } from './HarmonyDevice'; +import { HarmonyDevice } from "./harmonyDevice"; const Harmony = require("harmony-websocket"); -import { ICommand } from './IDevice'; -import { EventEmitter } from 'events'; - - +import { ICommand } from "./device"; +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; + 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; + 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}`); } + }; - 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 => { - await this._harmony.Connect(this._ip); - } -} \ No newline at end of file + private connect = async (): Promise => { + await this._harmony.Connect(this._ip); + }; +} diff --git a/src/Models/activityState.ts b/src/Models/activityState.ts new file mode 100644 index 0000000..4887ea1 --- /dev/null +++ b/src/Models/activityState.ts @@ -0,0 +1,5 @@ +import { IActivity } from "./Config"; + +export interface IActivityState { + currentActivity: IActivity; +} diff --git a/src/Models/IDevice.ts b/src/Models/device.ts similarity index 100% rename from src/Models/IDevice.ts rename to src/Models/device.ts diff --git a/src/Models/index.ts b/src/Models/index.ts index a37e649..01a9ec2 100644 --- a/src/Models/index.ts +++ b/src/Models/index.ts @@ -1 +1 @@ -export * from './IDevice'; \ No newline at end of file +export * from "./device"; diff --git a/src/Services/activityService.ts b/src/Services/activityService.ts new file mode 100644 index 0000000..afb50ea --- /dev/null +++ b/src/Services/activityService.ts @@ -0,0 +1,209 @@ +import { Logging } from "homebridge"; +import { inject, injectable } from "tsyringe"; +import { HarmonyDataProvider2 } from "../DataProviders/harmonyDataProvider2"; +import { StateDataProvider } from "../DataProviders/stateDataProvider"; +import { IActivityState } from "../Models/activityState"; +import { + IActivity, + IConfig, + IDeviceSetupItem, + IInput, + IOutput, +} from "../Models/Config"; +import { HarmonyDevice } from "../Models/harmonyDevice"; + +@injectable() +export class ActivityService { + constructor( + @inject(HarmonyDataProvider2) + private _harmonyDataProvider: HarmonyDataProvider2, + @inject(StateDataProvider) private _stateDataProvider: StateDataProvider, + @inject("IConfig") private _config: IConfig, + @inject("log") private _log: Logging + ) {} + + public startActivity = async ( + controlUnitName: string, + activity: IActivity + ) => { + this._log.info( + `Starting activity ${activity.DisplayName} for controlUnit: ${controlUnitName}` + ); + let devicesToTurnOn: Array = this.getDevicesToTurnOn( + activity, + controlUnitName + ); + + await this._harmonyDataProvider.turnOnDevices(devicesToTurnOn); + + await this.assignDeviceInput(activity); + + await this.routeInputsToOutputs(activity); + + let lastActivity = this.getCurrentActivity(controlUnitName); + + let devicesToTurnOff: Array = this.getDevicesToTurnOff( + controlUnitName, + lastActivity, + activity + ); + await this._harmonyDataProvider.turnOffDevices(devicesToTurnOff); + + this._stateDataProvider.updateState(activity, controlUnitName); + }; + + public stopCurrentActivity = async ( + controlUnitName: string + ): Promise => { + if (!this.getCurrentActivity(controlUnitName)) { + return; + } + + let lastActivity: IActivity | undefined = + this.getCurrentActivity(controlUnitName); + + let devicesToTurnOff: Array = this.getDevicesToTurnOff( + controlUnitName, + lastActivity + ); + await this._harmonyDataProvider.turnOffDevices(devicesToTurnOff); + + this._stateDataProvider.removeState(controlUnitName); + }; + + public getCurrentActivity(controlUnitName: string): IActivity | undefined { + return this._stateDataProvider.getState(controlUnitName); + } + + /** + * Return if a control unit is active + * @param controlUnitName + */ + public getIsActive(controlUnitName: string): IActivity | undefined { + return this._stateDataProvider.getState(controlUnitName); + } + + /** + * 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, + controlUnitName: string + ): Array { + for (let controlUnitKey in this._stateDataProvider.states) { + //Skip self + if (controlUnitKey === controlUnitName) { + continue; + } + let currentOtherState: IActivityState = + this._stateDataProvider.states[controlUnitKey]!; + + if (currentOtherState) { + currentOtherState.currentActivity.DeviceSetupList.forEach( + (value: IDeviceSetupItem) => { + //there are devices to remove + if (devicesToTurnOn.some((e) => e && e.name === value.DeviceName)) { + let deviceToRemove: HarmonyDevice = devicesToTurnOn.filter( + (i) => i.name === value.DeviceName + )[0]; + delete devicesToTurnOn[devicesToTurnOn.indexOf(deviceToRemove)]; + } + } + ); + } + } + + return devicesToTurnOn; + } + + private getDevicesToTurnOn( + activity: IActivity, + controlUnitName: string + ): Array { + let potentialDevices = this.buildPotentialDeviceList(activity); + return this.sanitizeDeviceList(potentialDevices, controlUnitName); + } + + private getDevicesToTurnOff( + controlUnitName: string, + lastActivity?: IActivity, + nextActivity?: IActivity + ) { + let potentialDevices = lastActivity + ? this.buildPotentialDeviceList(lastActivity) + : []; + + //remove devices that will be used for next activity from list + //delete array[index] is stupid because it just nulls out the index. But now i have to deal with nulls + if (nextActivity) { + potentialDevices.forEach((device: HarmonyDevice, index: number) => { + if ( + device && + device.name && + nextActivity.DeviceSetupList.some((e) => { + return e && e.DeviceName === device.name; + }) + ) { + delete potentialDevices[index]; + } + }); + } + + return this.sanitizeDeviceList(potentialDevices, controlUnitName); + } + + private buildPotentialDeviceList(activity: IActivity): HarmonyDevice[] { + return activity.DeviceSetupList.map( + (value: IDeviceSetupItem): HarmonyDevice => { + return this._harmonyDataProvider.getDeviceFromName(value.DeviceName); + } + ); + } + + private async assignDeviceInput(activity: IActivity): Promise { + await Promise.all( + activity.DeviceSetupList.map(async (value: IDeviceSetupItem) => { + let device: HarmonyDevice = this._harmonyDataProvider.getDeviceFromName( + value.DeviceName + ); + + if (device && device.supportsCommand(`Input${value.Input}`)) { + await device.sendCommand(`Input${value.Input}`); + } + }) + ); + } + + private async routeInputsToOutputs(activity: IActivity) { + if (activity.UseMatrix) { + //get input and output + let input: IInput = this._config.Matrix.Inputs.filter( + (e) => e.InputDevice === activity.ControlDevice + )[0]; + let output: IOutput = this._config.Matrix.Outputs.filter( + (e) => e.OutputDevice === activity.OutputDevice + )[0]; + + let inputCommandName: string = `In ${input.InputNumber}`; + let outputCommandName: string = `Out ${output.OutputLetter}`; + + let matrixDevice: HarmonyDevice = + this._harmonyDataProvider.getDeviceFromName( + this._config.Matrix.DeviceName + ); + + //Route hdmi + if ( + matrixDevice.supportsCommand(inputCommandName) && + matrixDevice.supportsCommand(outputCommandName) + ) { + await matrixDevice.sendCommand(outputCommandName); + await matrixDevice.sendCommand(inputCommandName); + await matrixDevice.sendCommand(outputCommandName); + await matrixDevice.sendCommand(inputCommandName); + } + } + } +} diff --git a/src/Services/commandService.ts b/src/Services/commandService.ts new file mode 100644 index 0000000..183d4f4 --- /dev/null +++ b/src/Services/commandService.ts @@ -0,0 +1,71 @@ +import { inject } from "tsyringe"; +import { RemoteKey } from "../Accessories/controlUnit"; +import { HarmonyDataProvider2 } from "../DataProviders/harmonyDataProvider2"; +import { StateDataProvider } from "../DataProviders/stateDataProvider"; +import { IConfig } from "../Models/Config"; +import { HarmonyDevice } from "../Models/harmonyDevice"; + +export class CommandService { + constructor( + @inject(StateDataProvider) private _stateDataProvider: StateDataProvider, + @inject(HarmonyDataProvider2) + private _harmonyDataProvider: HarmonyDataProvider2 + ) {} + + /** + * Send key press for current activity. + * + * @param controlUnitName The name of the control unit to act on. + * @param key The key to send. + */ + public sendKeyPress = async (controlUnitName: string, key: any) => { + let currentActivity = this._stateDataProvider.getState(controlUnitName); + if (currentActivity) { + let commandName: string = ""; + + let device: HarmonyDevice = this._harmonyDataProvider.getDeviceFromName( + currentActivity.ControlDevice + ); + switch (key) { + case RemoteKey.ARROW_UP: { + commandName = "Direction Up"; + break; + } + case RemoteKey.ARROW_DOWN: { + commandName = "Direction Down"; + break; + } + case RemoteKey.ARROW_LEFT: { + commandName = "Direction Left"; + break; + } + case RemoteKey.ARROW_RIGHT: { + commandName = "Direction Right"; + break; + } + case RemoteKey.SELECT: { + commandName = "Select"; + break; + } + case RemoteKey.PLAY_PAUSE: { + commandName = "Pause"; + break; + } + case RemoteKey.INFORMATION: { + commandName = "Menu"; + break; + } + case RemoteKey.BACK: { + commandName = "Back"; + break; + } + case RemoteKey.EXIT: { + commandName = "Back"; + break; + } + } + + await device.sendCommand(commandName); + } + }; +} diff --git a/src/Services/volumeService.ts b/src/Services/volumeService.ts new file mode 100644 index 0000000..8b66b2f --- /dev/null +++ b/src/Services/volumeService.ts @@ -0,0 +1,44 @@ +import { Logging } from "homebridge"; +import { inject } from "tsyringe"; +import { HarmonyDataProvider2 } from "../DataProviders/harmonyDataProvider2"; +import { StateDataProvider } from "../DataProviders/stateDataProvider"; +import { IConfig } from "../Models/Config"; +import { HarmonyDevice } from "../Models/harmonyDevice"; + +export class VolumeService { + constructor( + @inject(StateDataProvider) private _stateDataProvider: StateDataProvider, + @inject(HarmonyDataProvider2) + private _harmonyDataProvider: HarmonyDataProvider2 + ) {} + + /** + * Turn the volume up for the current running activity. + */ + public volumeUp = async (controlUnitName: string) => { + let volumeUpCommand: string = "Volume Up"; + let currentActivity = this._stateDataProvider.getState(controlUnitName); + if (currentActivity) { + let volumeDevice: HarmonyDevice = + this._harmonyDataProvider.getDeviceFromName( + currentActivity.VolumeDevice + ); + await volumeDevice.sendCommand(volumeUpCommand); + } + }; + + /** + * Volume down for current running activity. + */ + public volumeDown = async (controlUnitName: string) => { + let volumeDownCommand: string = "Volume Down"; + let currentActivity = this._stateDataProvider.getState(controlUnitName); + if (currentActivity) { + let volumeDevice: HarmonyDevice = + this._harmonyDataProvider.getDeviceFromName( + currentActivity.VolumeDevice + ); + await volumeDevice.sendCommand(volumeDownCommand); + } + }; +} diff --git a/src/Util/index.ts b/src/Util/index.ts index 19f0e10..fcebc7c 100644 --- a/src/Util/index.ts +++ b/src/Util/index.ts @@ -1,2 +1,2 @@ -export * from "./Callbackify"; -export * from "./Sleep"; +export * from "./callbackify"; +export * from "./sleep"; diff --git a/src/platform.ts b/src/platform.ts index 552dc7c..a747284 100644 --- a/src/platform.ts +++ b/src/platform.ts @@ -9,12 +9,17 @@ import { Service, } from "homebridge"; import { ControlUnit, DeviceButton } from "./Accessories"; -import { Sequence } from "./Accessories/Sequence"; -import HarmonyDataProvider from "./DataProviders/HarmonyDataProvider"; +import { Sequence } from "./Accessories/sequence"; +import HarmonyDataProvider from "./DataProviders/harmonyDataProvider"; import { IConfig, IControlUnit, IDeviceButton } from "./Models/Config"; -import { ISequence } from "./Models/Config/ISequence"; +import { ISequence } from "./Models/Config/sequence"; import { PLATFORM_NAME, PLUGIN_NAME } from "./settings"; import { container } from "tsyringe"; +import { HarmonyDataProvider2 } from "./DataProviders/harmonyDataProvider2"; +import { StateDataProvider } from "./DataProviders/stateDataProvider"; +import { CommandService } from "./Services/commandService"; +import { ActivityService } from "./Services/activityService"; +import { VolumeService } from "./Services/volumeService"; export class Platform implements DynamicPlatformPlugin { constructor( @@ -26,14 +31,6 @@ export class Platform implements DynamicPlatformPlugin { this.config = config as unknown as IConfig; this.register(); - //construct data provider - // const dataProvider = new HarmonyDataProvider({ - // hubs: this.config.Hubs, - // deviceConfigs: this.config.Devices, - // matrix: this.config.Matrix, - // log: this.log, - // }); - let didFinishLaunching = false; this.api.on("didFinishLaunching", async () => { log.debug("Executed didFinishLaunching callback"); @@ -43,39 +40,6 @@ export class Platform implements DynamicPlatformPlugin { this.pruneAccessories(); didFinishLaunching = true; }); - - // this.dataProvider = null; - - if (this.config) { - //construct data provider - // this.dataProvider = new HarmonyDataProvider({ - // hubs: this.config.Hubs, - // deviceConfigs: this.config.Devices, - // matrix: this.config.Matrix, - // log: this.log, - // }); - //Emit devices if requested - // this.dataProvider.on("Ready", () => { - // this.log.info("All hubs connected"); - // this.discoverControlUnitAccessories(dataProvider); - // this.discoverDeviceButtonAccessories(dataProvider); - // this.discoverSequenceAccessories(dataProvider); - // this.pruneAccessories(); - // if (this.config.EmitDevicesOnStartup) { - // const hubs = this.dataProvider!.hubs; - // Object.values(hubs).forEach((hub: HarmonyHub) => { - // const deviceDictionary = hub.devices; - // this.log.info(`${hub.hubName}`); - // Object.values(deviceDictionary).forEach((device: HarmonyDevice) => { - // this.log.info(` ${device.name} : ${device.id}`); - // Object.keys(device.commands).forEach((command: string) => { - // this.log.info(` ${command}`); - // }); - // }); - // }); - // } - // }); - } } public readonly Service: typeof Service = this.api.hap.Service; @@ -104,7 +68,9 @@ export class Platform implements DynamicPlatformPlugin { new ControlUnit( this, existingAccessory, - container.resolve(HarmonyDataProvider), + container.resolve(ActivityService), + container.resolve(CommandService), + container.resolve(VolumeService), unit.Activities ); @@ -122,7 +88,9 @@ export class Platform implements DynamicPlatformPlugin { new ControlUnit( this, accessory, - container.resolve(HarmonyDataProvider), + container.resolve(ActivityService), + container.resolve(CommandService), + container.resolve(VolumeService), unit.Activities ); @@ -253,6 +221,9 @@ export class Platform implements DynamicPlatformPlugin { container.register(Platform, { useValue: this }); container.register("IConfig", { useValue: this.config }); container.register("log", { useValue: this.log }); + container.registerSingleton(StateDataProvider); + container.registerSingleton(CommandService); container.registerSingleton(HarmonyDataProvider); + container.registerSingleton(HarmonyDataProvider2); } }