forked from homebridge/homebridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogitechHarmony.js
267 lines (226 loc) · 8.28 KB
/
LogitechHarmony.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
'use strict';
// Logitech Harmony Remote Platform Shim for HomeBridge
// Based on the Domoticz Platform Shim for HomeBridge by Joep Verhaeg (http://www.joepverhaeg.nl)
// Wriiten by John Wells (https://github.com/madmod)
//
// Remember to add platform to config.json. Example:
// "platforms": [
// {
// "platform": "LogitechHarmony",
// "name": "Logitech Harmony"
// }
// ],
//
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//
var types = require('hap-nodejs/accessories/types.js');
var harmonyDiscover = require('harmonyhubjs-discover');
var harmony = require('harmonyhubjs-client');
var _harmonyHubPort = 61991;
var Service = require("hap-nodejs").Service;
var Characteristic = require("hap-nodejs").Characteristic;
var Accessory = require("hap-nodejs").Accessory;
var uuid = require("hap-nodejs").uuid;
var inherits = require('util').inherits;
var queue = require('queue');
function sortByKey (array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
};
function LogitechHarmonyPlatform (log, config) {
this.log = log;
this.ip_address = config['ip_address'];
};
LogitechHarmonyPlatform.prototype = {
accessories: function (callback) {
var plat = this;
var foundAccessories = [];
var activityAccessories = [];
var hub = null;
var hubIP = null;
var hubQueue = queue();
hubQueue.concurrency = 1;
// Get the first hub
locateHub(function (err, client, clientIP) {
if (err) throw err;
plat.log("Fetching Logitech Harmony devices and activites...");
hub = client;
hubIP = clientIP;
//getDevices(hub);
getActivities();
});
// Find one Harmony remote hub (only support one for now)
function locateHub(callback) {
// Use the ip address in configuration if available
if (plat.ip_address) {
console.log("Using Logitech Harmony hub ip address from configuration");
return createClient(plat.ip_address, callback)
}
plat.log("Searching for Logitech Harmony remote hubs...");
// Discover the harmony hub with bonjour
var discover = new harmonyDiscover(_harmonyHubPort);
// TODO: Support update event with some way to add accessories
// TODO: Have some kind of timeout with an error message. Right now this searches forever until it finds one hub.
discover.on('online', function (hubInfo) {
plat.log("Found Logitech Harmony remote hub: " + hubInfo.ip);
// Stop looking for hubs once we find the first one
// TODO: Support multiple hubs
discover.stop();
createClient(hubInfo.ip, callback);
});
// Start looking for hubs
discover.start();
}
// Connect to a Harmony hub
function createClient(ipAddress, callback) {
plat.log("Connecting to Logitech Harmony remote hub...");
harmony(ipAddress)
.then(function (client) {
plat.log("Connected to Logitech Harmony remote hub");
callback(null, client, ipAddress);
});
}
// Get Harmony Activities
function getActivities() {
plat.log("Fetching Logitech Harmony activities...");
hub.getActivities()
.then(function (activities) {
plat.log("Found activities: \n" + activities.map(function (a) { return "\t" + a.label; }).join("\n"));
hub.getCurrentActivity().then(function (currentActivity) {
var actAccessories = [];
var sArray = sortByKey(activities, "label");
sArray.map(function(s) {
var accessory = createActivityAccessory(s);
if (accessory.id > 0) {
accessory.updateActivityState(currentActivity);
actAccessories.push(accessory);
foundAccessories.push(accessory);
}
});
activityAccessories = actAccessories;
keepAliveRefreshLoop();
callback(foundAccessories);
}).catch(function (err) {
plat.log('Unable to get current activity with error', err);
throw err;
});
});
}
function createActivityAccessory(activity) {
var accessory = new LogitechHarmonyActivityAccessory(plat.log, activity, changeCurrentActivity.bind(plat), -1);
return accessory;
}
var isChangingActivity = false;
function changeCurrentActivity(nextActivity, callback) {
if (!nextActivity) {
nextActivity = -1;
}
plat.log('Queue activity to ' + nextActivity);
executeOnHub(function(h, cb) {
plat.log('Set activity to ' + nextActivity);
h.startActivity(nextActivity)
.then(function () {
cb();
isChangingActivity = false;
plat.log('Finished setting activity to ' + nextActivity);
updateCurrentActivity(nextActivity);
if (callback) callback(null, nextActivity);
})
.catch(function (err) {
cb();
isChangingActivity = false;
plat.log('Failed setting activity to ' + nextActivity + ' with error ' + err);
if (callback) callback(err);
});
}, function(){
callback(Error("Set activity failed too many times"));
});
}
function updateCurrentActivity(currentActivity) {
var actAccessories = activityAccessories;
if (actAccessories instanceof Array) {
actAccessories.map(function(a) { a.updateActivityState(currentActivity); });
}
}
// prevent connection from closing
function keepAliveRefreshLoop() {
setTimeout(function() {
setInterval(function() {
executeOnHub(function(h, cb) {
plat.log("Refresh Status");
h.getCurrentActivity()
.then(function(currentActivity){
cb();
updateCurrentActivity(currentActivity);
})
.catch(cb);
});
}, 20000);
}, 5000);
}
function executeOnHub(func, funcMaxTimeout)
{
if (!func) return;
hubQueue.push(function(cb) {
var tout = setTimeout(function(){
plat.log("Reconnecting to Hub " + hubIP);
createClient(hubIP, function(err, newHub){
if (err) throw err;
hub = newHub;
if (funcMaxTimeout) {
funcMaxTimeout();
}
cb();
});
}, 30000);
func(hub, function(){
clearTimeout(tout);
cb();
});
});
if (!hubQueue.running){
hubQueue.start();
}
}
}
};
function LogitechHarmonyActivityAccessory (log, details, changeCurrentActivity) {
this.log = log;
this.id = details.id;
this.name = details.label;
this.isOn = false;
this.changeCurrentActivity = changeCurrentActivity;
Accessory.call(this, this.name, uuid.generate(this.id));
var self = this;
this.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, "Logitech")
.setCharacteristic(Characteristic.Model, "Harmony")
// TODO: Add hub unique id to this for people with multiple hubs so that it is really a guid.
.setCharacteristic(Characteristic.SerialNumber, this.id);
this.addService(Service.Switch)
.getCharacteristic(Characteristic.On)
.on('get', function(callback) {
// Refreshed automatically by platform
callback(null, self.isOn);
})
.on('set', this.setPowerState.bind(this));
}
inherits(LogitechHarmonyActivityAccessory, Accessory);
LogitechHarmonyActivityAccessory.prototype.parent = Accessory.prototype;
LogitechHarmonyActivityAccessory.prototype.getServices = function() {
return this.services;
};
LogitechHarmonyActivityAccessory.prototype.updateActivityState = function (currentActivity) {
this.isOn = (currentActivity === this.id);
// Force get to trigger 'change' if needed
this.getService(Service.Switch)
.getCharacteristic(Characteristic.On)
.getValue();
};
LogitechHarmonyActivityAccessory.prototype.setPowerState = function (state, callback) {
this.changeCurrentActivity(state ? this.id : null, callback);
};
module.exports.platform = LogitechHarmonyPlatform;