Added device emit option for debugging purposes

This commit is contained in:
watsonb8 2020-01-01 23:29:44 -05:00
parent 588205e507
commit 020a2fc240
10 changed files with 132 additions and 90 deletions

View File

@ -1,5 +1,5 @@
import { IActivity } from '../Models/Activity'; import { IActivity } from '../Models/Config/IActivity';
import { IMatrix } from '../Models/Matrix'; import { IMatrix } from '../Models/Config/IMatrix';
import { IAccessory } from './IAccessory'; import { IAccessory } from './IAccessory';
import callbackify from '../Util/Callbackify'; import callbackify from '../Util/Callbackify';
import HarmonyDataProvider from '../DataProviders/HarmonyDataProvider'; import HarmonyDataProvider from '../DataProviders/HarmonyDataProvider';

View File

@ -1,14 +1,16 @@
import HarmonyDataProvider from "../DataProviders/HarmonyDataProvider"; import HarmonyDataProvider from "../DataProviders/HarmonyDataProvider";
import { IDeviceButton } from "../Models/DeviceButton"; import { IDeviceButton } from "../Models/Config/IDeviceButton";
import { IAccessory } from "./IAccessory"; import { IAccessory } from "./IAccessory";
import { sleep } from "../Util/Sleep"; import { sleep } from "../Util/Sleep";
import { ICommand } from "../Models/IDevice";
let Service: HAPNodeJS.Service; let Service: HAPNodeJS.Service;
let Characteristic: HAPNodeJS.Characteristic; let Characteristic: HAPNodeJS.Characteristic;
export interface IDeviceButtonProps { export interface IDeviceButtonProps {
dataProvider: HarmonyDataProvider, dataProvider: HarmonyDataProvider,
name: string, buttonName: string,
displayName: string,
deviceInfo: IDeviceButton, deviceInfo: IDeviceButton,
api: any, api: any,
log: any, log: any,
@ -28,10 +30,12 @@ export class DeviceButton implements IAccessory {
private _dataProvider: HarmonyDataProvider; private _dataProvider: HarmonyDataProvider;
private _deviceCommand: string = ""; private _deviceCommand?: ICommand;
private _buttonState: boolean; private _buttonState: boolean;
private _buttonName: string;
constructor(props: IDeviceButtonProps) { constructor(props: IDeviceButtonProps) {
//Assign class variables //Assign class variables
@ -39,7 +43,8 @@ export class DeviceButton implements IAccessory {
this._api = props.api; this._api = props.api;
Service = props.api.hap.Service; Service = props.api.hap.Service;
Characteristic = props.api.hap.Characteristic; Characteristic = props.api.hap.Characteristic;
this.name = props.name; this._buttonName = props.buttonName;
this.name = props.displayName;
this._homebridge = props.homebridge; this._homebridge = props.homebridge;
this._buttonInfo = props.deviceInfo; this._buttonInfo = props.deviceInfo;
@ -93,7 +98,10 @@ export class DeviceButton implements IAccessory {
//Get device command if we don't have it //Get device command if we don't have it
if (!this._deviceCommand) { if (!this._deviceCommand) {
this._deviceCommand = this._dataProvider.getCommand(this._buttonInfo.ButtonName, this._buttonInfo.DeviceName); let cmd = this._dataProvider.getCommand(this._buttonInfo.ButtonName, this._buttonInfo.DeviceName);
if (cmd) {
this._deviceCommand = cmd;
}
} }
//Execute command //Execute command

View File

@ -1,20 +1,14 @@
import { IActivity } from "../Models/Activity"; import { IActivity } from "../Models/Config/IActivity";
import { IDeviceSetupItem } from "../Models/DeviceSetupItem"; import { IDeviceSetupItem } from "../Models/Config/IDeviceSetupItem";
import { IInput, IMatrix, IOutput } from "../Models/Matrix"; import { IInput, IMatrix, IOutput } from "../Models/Config/IMatrix";
import { RemoteKey } from '../Accessories/ControlUnit'; import { RemoteKey } from '../Accessories/ControlUnit';
import { sleep } from '../Util/Sleep'; import { sleep } from '../Util/Sleep';
import { EventEmitter } from "events";
import { IDevice, ICommand } from '../Models/IDevice';
let Characteristic: HAPNodeJS.Characteristic; let Characteristic: HAPNodeJS.Characteristic;
const Harmony = require("harmony-websocket"); 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 { interface IActivityState {
currentActivity: IActivity currentActivity: IActivity
@ -26,41 +20,46 @@ interface IHarmonyDataProviderProps {
matrix: IMatrix matrix: IMatrix
} }
class HarmonyDataProvider { class HarmonyDataProvider extends EventEmitter {
private harmony: any; private _harmony: any;
private log: any; private _log: any;
private hubAddress: string = ""; private _hubAddress: string = "";
private connected: boolean = false; private _connected: boolean = false;
private devices: { [name: string]: IDevice; } = {}; private _devices: { [name: string]: IDevice; } = {};
private states: { [controlUnitName: string]: (IActivityState | undefined) } = {}; private _states: { [controlUnitName: string]: (IActivityState | undefined) } = {};
private matrix: IMatrix; private _matrix: IMatrix;
constructor(props: IHarmonyDataProviderProps) { constructor(props: IHarmonyDataProviderProps) {
this.log = props.log; super();
this.hubAddress = props.hubAddress; this._log = props.log;
this.matrix = props.matrix; this._hubAddress = props.hubAddress;
this._matrix = props.matrix;
this.harmony = new Harmony(); this._harmony = new Harmony();
//Listeners //Listeners
this.harmony.on('open', () => { this._harmony.on('open', () => {
this.connected = true; this._connected = true;
}); });
this.harmony.on('close', () => { this._harmony.on('close', () => {
this.connected = false; this._connected = false;
}); });
this.connect(); this.connect();
} }
public get devices(): { [name: string]: IDevice; } {
return this._devices;
}
/** /**
* Power on all devices in an activity. * Power on all devices in an activity.
*/ */
public powerOn = async (controlUnitName: string, activity: IActivity) => { public powerOn = async (controlUnitName: string, activity: IActivity) => {
//Only power on if not alread on //Only power on if not alread on
let currentActivity = this.states[controlUnitName] ? this.states[controlUnitName]!.currentActivity : undefined; let currentActivity = this._states[controlUnitName] ? this._states[controlUnitName]!.currentActivity : undefined;
if (!currentActivity) { if (!currentActivity) {
await this.startActivity(controlUnitName, activity); await this.startActivity(controlUnitName, activity);
} }
@ -70,11 +69,11 @@ class HarmonyDataProvider {
* Power off all devices in an activity that aren't being used. * Power off all devices in an activity that aren't being used.
*/ */
public powerOff = async (controlUnitName: string) => { public powerOff = async (controlUnitName: string) => {
if (!this.states[controlUnitName]) { if (!this._states[controlUnitName]) {
return; return;
} }
//Build potential list of devices to turn off //Build potential list of devices to turn off
let devicesToTurnOff: Array<IDevice> = this.states[controlUnitName]!.currentActivity.DeviceSetupList let devicesToTurnOff: Array<IDevice> = this._states[controlUnitName]!.currentActivity.DeviceSetupList
.map((value: IDeviceSetupItem): IDevice => { .map((value: IDeviceSetupItem): IDevice => {
return this.getDeviceFromName(value.DeviceName); return this.getDeviceFromName(value.DeviceName);
}); });
@ -87,17 +86,17 @@ class HarmonyDataProvider {
this.powerOffDevice(device); this.powerOffDevice(device);
}); });
this.states[controlUnitName] = undefined; this._states[controlUnitName] = undefined;
} }
/** /**
* Start an activity * Start an activity
*/ */
public startActivity = async (controlUnitName: string, activity: IActivity) => { public startActivity = async (controlUnitName: string, activity: IActivity) => {
this.log(`Starting activity ${activity.DisplayName} for controlUnit: ${controlUnitName}`) this._log(`Starting activity ${activity.DisplayName} for controlUnit: ${controlUnitName}`)
let lastActivity: IActivity | undefined = undefined; let lastActivity: IActivity | undefined = undefined;
if (this.states[controlUnitName]) { if (this._states[controlUnitName]) {
lastActivity = this.states[controlUnitName]!.currentActivity; lastActivity = this._states[controlUnitName]!.currentActivity;
} }
//Build potential list of devices to to turn on //Build potential list of devices to to turn on
@ -110,9 +109,9 @@ class HarmonyDataProvider {
//Turn on devices //Turn on devices
await Promise.all(devicesToTurnOn.map(async (device: IDevice) => { await Promise.all(devicesToTurnOn.map(async (device: IDevice) => {
if (device && device.name && this.devices[device.name]) { if (device && device.name && this._devices[device.name]) {
if (!device.on) { if (!device.on) {
this.log(`Turning on device ${device.name}`) this._log(`Turning on device ${device.name}`)
await this.powerOnDevice(device); await this.powerOnDevice(device);
} }
} }
@ -124,7 +123,7 @@ class HarmonyDataProvider {
let device: IDevice = this.getDeviceFromName(value.DeviceName); let device: IDevice = this.getDeviceFromName(value.DeviceName);
if (device && device.supportsCommand(`Input${value.Input}`)) { if (device && device.supportsCommand(`Input${value.Input}`)) {
let command: string = device.getCommand(`Input${value.Input}`); let command: ICommand = device.getCommand(`Input${value.Input}`);
await this.sendCommand(command); await this.sendCommand(command);
} }
}) })
@ -132,13 +131,13 @@ class HarmonyDataProvider {
if (activity.UseMatrix) { if (activity.UseMatrix) {
//get input and output //get input and output
let input: IInput = this.matrix.Inputs.filter(e => e.InputDevice === activity.ControlDevice)[0]; let input: IInput = this._matrix.Inputs.filter(e => e.InputDevice === activity.ControlDevice)[0];
let output: IOutput = this.matrix.Outputs.filter(e => e.OutputDevice === activity.OutputDevice)[0]; let output: IOutput = this._matrix.Outputs.filter(e => e.OutputDevice === activity.OutputDevice)[0];
let inputCommandName: string = `In ${input.InputNumber}`; let inputCommandName: string = `In ${input.InputNumber}`;
let outputCommandName: string = `Out ${output.OutputLetter}`; let outputCommandName: string = `Out ${output.OutputLetter}`;
let matrixDevice: IDevice = this.getDeviceFromName(this.matrix.DeviceName); let matrixDevice: IDevice = this.getDeviceFromName(this._matrix.DeviceName);
//Route hdmi //Route hdmi
if (matrixDevice.supportsCommand(inputCommandName) && matrixDevice.supportsCommand(outputCommandName)) { if (matrixDevice.supportsCommand(inputCommandName) && matrixDevice.supportsCommand(outputCommandName)) {
@ -168,14 +167,14 @@ class HarmonyDataProvider {
//Resolve device conflicts with other controlUnits //Resolve device conflicts with other controlUnits
devicesToTurnOff = this.sanitizeDeviceList(devicesToTurnOff, controlUnitName); devicesToTurnOff = this.sanitizeDeviceList(devicesToTurnOff, controlUnitName);
this.log(`Sanatized devices to turn off: ${JSON.stringify(devicesToTurnOff.map(e => e ? e.name : ""))}`); this._log(`Sanatized devices to turn off: ${JSON.stringify(devicesToTurnOff.map(e => e ? e.name : ""))}`);
await Promise.all( await Promise.all(
//Turn off devices //Turn off devices
devicesToTurnOff.map(async (device: IDevice) => { devicesToTurnOff.map(async (device: IDevice) => {
if (device) { if (device) {
if (device.on) { if (device.on) {
this.log(`Turning off device ${device.name}`) this._log(`Turning off device ${device.name}`)
await this.powerOffDevice(device); await this.powerOffDevice(device);
} }
} }
@ -185,7 +184,7 @@ class HarmonyDataProvider {
} }
//Assign current activity //Assign current activity
this.states[controlUnitName] = { currentActivity: activity }; this._states[controlUnitName] = { currentActivity: activity };
} }
/** /**
@ -193,8 +192,8 @@ class HarmonyDataProvider {
*/ */
public volumeUp = async (controlUnitName: string) => { public volumeUp = async (controlUnitName: string) => {
let volumeUpCommand: string = "Volume Up" let volumeUpCommand: string = "Volume Up"
if (this.states[controlUnitName]) { if (this._states[controlUnitName]) {
let volumeDevice: IDevice = this.getDeviceFromName(this.states[controlUnitName]!.currentActivity.VolumeDevice); let volumeDevice: IDevice = this.getDeviceFromName(this._states[controlUnitName]!.currentActivity.VolumeDevice);
if (volumeDevice.supportsCommand(volumeUpCommand)) { if (volumeDevice.supportsCommand(volumeUpCommand)) {
this.sendCommand(volumeDevice.getCommand(volumeUpCommand)); this.sendCommand(volumeDevice.getCommand(volumeUpCommand));
} }
@ -206,8 +205,8 @@ class HarmonyDataProvider {
*/ */
public volumeDown = async (controlUnitName: string) => { public volumeDown = async (controlUnitName: string) => {
let volumeDownCommand: string = "Volume Down" let volumeDownCommand: string = "Volume Down"
if (this.states[controlUnitName]) { if (this._states[controlUnitName]) {
let volumeDevice: IDevice = this.getDeviceFromName(this.states[controlUnitName]!.currentActivity.VolumeDevice); let volumeDevice: IDevice = this.getDeviceFromName(this._states[controlUnitName]!.currentActivity.VolumeDevice);
if (volumeDevice.supportsCommand(volumeDownCommand)) { if (volumeDevice.supportsCommand(volumeDownCommand)) {
this.sendCommand(volumeDevice.getCommand(volumeDownCommand)); this.sendCommand(volumeDevice.getCommand(volumeDownCommand));
} }
@ -221,10 +220,10 @@ class HarmonyDataProvider {
* @param key The key to send. * @param key The key to send.
*/ */
public sendKeyPress = async (controlUnitName: string, key: any) => { public sendKeyPress = async (controlUnitName: string, key: any) => {
if (this.states[controlUnitName]) { if (this._states[controlUnitName]) {
let commandName: string = ""; let commandName: string = "";
let device: IDevice = this.getDeviceFromName(this.states[controlUnitName]!.currentActivity.ControlDevice); let device: IDevice = this.getDeviceFromName(this._states[controlUnitName]!.currentActivity.ControlDevice);
switch (key) { switch (key) {
case RemoteKey.ARROW_UP: { case RemoteKey.ARROW_UP: {
commandName = "Direction Up"; commandName = "Direction Up";
@ -275,7 +274,7 @@ class HarmonyDataProvider {
* @param controlUnitName * @param controlUnitName
*/ */
public getIsActive(controlUnitName: string): IActivity | undefined { public getIsActive(controlUnitName: string): IActivity | undefined {
return this.states[controlUnitName] ? this.states[controlUnitName]!.currentActivity : undefined; return this._states[controlUnitName] ? this._states[controlUnitName]!.currentActivity : undefined;
} }
/** /**
@ -283,12 +282,12 @@ class HarmonyDataProvider {
* @param deviceCommandName The device command name * @param deviceCommandName The device command name
* @param deviceName The device name * @param deviceName The device name
*/ */
public getCommand(deviceCommandName: string, deviceName: string): string { public getCommand(deviceCommandName: string, deviceName: string): ICommand | undefined {
const device: IDevice = this.getDeviceFromName(deviceName); const device: IDevice = this.getDeviceFromName(deviceName);
if (device && device.supportsCommand(deviceCommandName)) { if (device && device.supportsCommand(deviceCommandName)) {
return device.getCommand(deviceCommandName); return device.getCommand(deviceCommandName);
} else { } else {
return ""; return undefined;
} }
} }
@ -296,15 +295,15 @@ class HarmonyDataProvider {
* Send a command to the harmony hub. * Send a command to the harmony hub.
* @param command The command to send. * @param command The command to send.
*/ */
public sendCommand = async (command: string) => { public sendCommand = async (command: ICommand) => {
try { try {
//Execute command //Execute command
let response = await this.harmony.sendCommand(JSON.stringify(command)); let response = await this._harmony.sendCommand(JSON.stringify(command));
//Sleep //Sleep
await sleep(800); await sleep(800);
} catch (err) { } catch (err) {
this.log(`ERROR - error sending command to harmony: ${err}`); this._log(`ERROR - error sending command to harmony: ${err}`);
} }
} }
@ -313,23 +312,23 @@ class HarmonyDataProvider {
* Connect to harmony and receive device info * Connect to harmony and receive device info
*/ */
private connect = async () => { private connect = async () => {
await this.harmony.connect(this.hubAddress); await this._harmony.connect(this._hubAddress);
let self = this; let self = this;
setTimeout(async function () { setTimeout(async function () {
if (self.connected) { if (self._connected) {
let devices: any = await self.harmony.getDevices(); let devices: any = await self._harmony.getDevices();
try { try {
await Promise.all( await Promise.all(
//Add each to dictionary //Add each to dictionary
devices.map(async (dev: any) => { devices.map(async (dev: any) => {
//get commands //get commands
let commands: { [name: string]: string } = {}; let commands: { [name: string]: ICommand } = {};
let deviceCommands: any = await self.harmony.getDeviceCommands(dev.id); let deviceCommands: any = await self._harmony.getDeviceCommands(dev.id);
deviceCommands.forEach((command: any) => { deviceCommands.forEach((command: any) => {
commands[command.label] = command.action; commands[command.label] = command.action;
}); });
self.devices[dev.label] = { self._devices[dev.label] = {
id: dev.id, id: dev.id,
name: dev.label, name: dev.label,
commands: commands, commands: commands,
@ -339,15 +338,16 @@ class HarmonyDataProvider {
let command = commands[commandName]; let command = commands[commandName];
return (command) ? true : false; return (command) ? true : false;
}, },
getCommand(commandName: string): string { getCommand(commandName: string): ICommand {
return commands[commandName]; return commands[commandName];
} }
} }
})); }));
self.log(`Harmony data provider ready`); self._log(`Harmony data provider ready`);
self.emit("Ready");
} catch (err) { } catch (err) {
self.log(`ERROR - error connecting to harmony: ${err}`); self._log(`ERROR - error connecting to harmony: ${err}`);
} }
} }
}, 1000); }, 1000);
@ -388,7 +388,7 @@ class HarmonyDataProvider {
* @param deviceName The device to retrieve. * @param deviceName The device to retrieve.
*/ */
private getDeviceFromName(deviceName: string): IDevice { private getDeviceFromName(deviceName: string): IDevice {
return this.devices[deviceName]; return this._devices[deviceName];
} }
/** /**
@ -397,12 +397,12 @@ class HarmonyDataProvider {
* @param controlUnitName The name of the control unit in question. * @param controlUnitName The name of the control unit in question.
*/ */
private sanitizeDeviceList(devicesToTurnOn: Array<IDevice>, controlUnitName: string): Array<IDevice> { private sanitizeDeviceList(devicesToTurnOn: Array<IDevice>, controlUnitName: string): Array<IDevice> {
for (let controlUnitKey in this.states) { for (let controlUnitKey in this._states) {
//Skip self //Skip self
if (controlUnitKey === controlUnitName) { if (controlUnitKey === controlUnitName) {
continue; continue;
} }
let currentOtherState: IActivityState = this.states[controlUnitKey]!; let currentOtherState: IActivityState = this._states[controlUnitKey]!;
if (currentOtherState) { if (currentOtherState) {
currentOtherState.currentActivity.DeviceSetupList.forEach((value: IDeviceSetupItem) => { currentOtherState.currentActivity.DeviceSetupList.forEach((value: IDeviceSetupItem) => {

View File

@ -1,4 +1,4 @@
import { IDeviceSetupItem } from './DeviceSetupItem'; import { IDeviceSetupItem } from './IDeviceSetupItem';
export interface IActivity { export interface IActivity {
OutputDevice: string; OutputDevice: string;

View File

@ -1,6 +1,6 @@
import { IMatrix } from "./Matrix"; import { IMatrix } from "./IMatrix";
import { IActivity } from "./Activity"; import { IActivity } from "./IActivity";
import { IDeviceButton } from "./DeviceButton"; import { IDeviceButton } from "./IDeviceButton";
export interface IControlUnit { export interface IControlUnit {
DisplayName: string; DisplayName: string;
@ -9,6 +9,7 @@ export interface IControlUnit {
export interface IConfig { export interface IConfig {
hubIp: string; hubIp: string;
EmitDevicesOnStartup: boolean,
Matrix: IMatrix Matrix: IMatrix
ControlUnits: Array<IControlUnit> ControlUnits: Array<IControlUnit>
DeviceButtons: Array<IDeviceButton> DeviceButtons: Array<IDeviceButton>

View File

@ -1,5 +1,6 @@
export interface IDeviceButton { export interface IDeviceButton {
DeviceName: string; DeviceName: string;
ButtonName: string; ButtonName: string;
DisplayName: string;
IsStateful: boolean; IsStateful: boolean;
} }

14
src/Models/IDevice.ts Normal file
View File

@ -0,0 +1,14 @@
export interface ICommand {
command?: string,
deviceId?: string,
type?: string
}
export interface IDevice {
id: string,
name: string,
supportsCommand(commandName: string): boolean,
getCommand(commandName: string): ICommand,
commands: { [name: string]: ICommand };
on: boolean;
}

View File

@ -1,12 +1,13 @@
import { ControlUnit } from "./Accessories/ControlUnit"; import { ControlUnit } from "./Accessories/ControlUnit";
import { DeviceButton } from './Accessories/DeviceButton'; import { DeviceButton } from './Accessories/DeviceButton';
import { IActivity } from "./Models/Activity"; import { IActivity } from "./Models/Config/IActivity";
import { IDeviceSetupItem } from "./Models/DeviceSetupItem"; import { IDeviceSetupItem } from "./Models/Config/IDeviceSetupItem";
import { IInput, IOutput, IMatrix } from "./Models/Matrix"; import { IInput, IOutput, IMatrix } from "./Models/Config/IMatrix";
import HarmonyDataProvider from "./DataProviders/HarmonyDataProvider"; import HarmonyDataProvider from "./DataProviders/HarmonyDataProvider";
import { IConfig, IControlUnit } from "./Models/IConfig"; import { IConfig, IControlUnit } from "./Models/Config/IConfig";
import { IDeviceButton } from "./Models/DeviceButton"; import { IDeviceButton } from "./Models/Config/IDeviceButton";
import { IAccessory } from "./Accessories/IAccessory"; import { IAccessory } from "./Accessories/IAccessory";
import { IDevice, ICommand } from "./Models/IDevice";
let Accessory: any; let Accessory: any;
let Homebridge: any; let Homebridge: any;
@ -41,6 +42,28 @@ class HarmonyMatrixPlatform {
this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this)); this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this));
this.dataProvider = null; this.dataProvider = null;
if (this.config) {
//construct data provider
this.dataProvider = new HarmonyDataProvider({
hubAddress: this.config.hubIp,
matrix: this.config.Matrix,
log: this.log
});
//Emit devices if requested
if (this.config.EmitDevicesOnStartup) {
this.dataProvider.on("Ready", () => {
const devices: { [name: string]: IDevice } = this.dataProvider!.devices;
Object.values(devices).forEach((device: IDevice) => {
this.log(`${device.name} : ${device.id}`);
Object.keys(device.commands).forEach((command: string) => {
this.log(` ${command}`);
});
});
});
}
}
} }
/** /**
@ -63,12 +86,6 @@ class HarmonyMatrixPlatform {
* @param callback * @param callback
*/ */
accessories(callback: (accessories: Array<IAccessory>) => void) { accessories(callback: (accessories: Array<IAccessory>) => void) {
//construct data provider
this.dataProvider = new HarmonyDataProvider({
hubAddress: this.config.hubIp,
matrix: this.config.Matrix,
log: this.log
});
//Add control units //Add control units
this.config.ControlUnits.forEach((unit: IControlUnit) => { this.config.ControlUnits.forEach((unit: IControlUnit) => {
@ -86,7 +103,8 @@ class HarmonyMatrixPlatform {
this.config.DeviceButtons.forEach((button: IDeviceButton) => { this.config.DeviceButtons.forEach((button: IDeviceButton) => {
this.accessoryList.push(new DeviceButton({ this.accessoryList.push(new DeviceButton({
dataProvider: this.dataProvider!, dataProvider: this.dataProvider!,
name: button.ButtonName, buttonName: button.ButtonName,
displayName: button.DisplayName,
deviceInfo: button, deviceInfo: button,
api: this.api, api: this.api,
log: this.log, log: this.log,