-
Notifications
You must be signed in to change notification settings - Fork 115
/
app.js
executable file
·568 lines (459 loc) · 17 KB
/
app.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
var fs = require('fs')
var path = require('path')
var util = require('util')
var mqtt = require('mqtt');
var express = require('express')
var morgan = require('morgan')
var bodyParser = require('body-parser')
var parameterize = require('parameterize')
var config_dir = process.env.CONFIG_DIR || './config'
var config = require(config_dir + '/config.json');
var harmonyHubDiscover = require('harmonyhubjs-discover')
var harmony = require('harmonyhubjs-client')
var harmonyHubClients = {}
var harmonyActivitiesCache = {}
var harmonyActivityUpdateInterval = 1*60*1000 // 1 minute
var harmonyActivityUpdateTimers = {}
var harmonyHubStates = {}
var harmonyStateUpdateInterval = 5*1000 // 5 seconds
var harmonyStateUpdateTimers = {}
var harmonyDevicesCache = {}
var harmonyDeviceUpdateInterval = 1*60*1000 // 1 minute
var harmonyDeviceUpdateTimers = {}
var mqttClient = config.hasOwnProperty("mqtt_options") ?
mqtt.connect(config.mqtt_host, config.mqtt_options) :
mqtt.connect(config.mqtt_host);
var TOPIC_NAMESPACE = config.topic_namespace || "harmony-api";
var enableHTTPserver = config.hasOwnProperty("enableHTTPserver") ?
config.enableHTTPserver : true;
var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')));
var logFormat = "'[:date[iso]] - :remote-addr - :method :url :status :response-time ms - :res[content-length]b'"
app.use(morgan(logFormat))
// Middleware
// Check to make sure we have a harmonyHubClient to connect to
var hasHarmonyHubClient = function(req, res, next) {
if (Object.keys(harmonyHubClients).length > 0) {
next()
}else{
res.status(500).json({message: "No hubs available."})
}
}
app.use(hasHarmonyHubClient)
var discover = new harmonyHubDiscover(61991)
discover.on('online', function(hubInfo) {
// Triggered when a new hub was found
console.log('Hub discovered: ' + hubInfo.friendlyName + ' at ' + hubInfo.ip + '.')
if (hubInfo.ip) {
harmony(hubInfo.ip).then(function(client){
startProcessing(parameterize(hubInfo.friendlyName), client)
})
}
})
discover.on('offline', function(hubInfo) {
// Triggered when a hub disappeared
console.log('Hub lost: ' + hubInfo.friendlyName + ' at ' + hubInfo.ip + '.')
if (!hubInfo.friendlyName) { return }
hubSlug = parameterize(hubInfo.friendlyName)
clearInterval(harmonyStateUpdateTimers[hubSlug])
clearInterval(harmonyActivityUpdateTimers[hubSlug])
delete(harmonyHubClients[hubSlug])
delete(harmonyActivitiesCache[hubSlug])
delete(harmonyHubStates[hubSlug])
})
// Look for hubs:
console.log('Starting discovery.')
discover.start()
// mqtt api
mqttClient.on('connect', function () {
mqttClient.subscribe(TOPIC_NAMESPACE + '/hubs/+/activities/+/command')
mqttClient.subscribe(TOPIC_NAMESPACE + '/hubs/+/devices/+/command')
mqttClient.subscribe(TOPIC_NAMESPACE + '/hubs/+/command')
});
mqttClient.on('message', function (topic, message) {
var activityCommandPattern = new RegExp(/hubs\/(.*)\/activities\/(.*)\/command/);
var deviceCommandPattern = new RegExp(/hubs\/(.*)\/devices\/(.*)\/command/);
var currentActivityCommandPattern = new RegExp(/hubs\/(.*)\/command/);
var activityCommandMatches = topic.match(activityCommandPattern);
var deviceCommandMatches = topic.match(deviceCommandPattern);
var currentActivityCommandMatches = topic.match(currentActivityCommandPattern);
if (activityCommandMatches) {
var hubSlug = activityCommandMatches[1]
var activitySlug = activityCommandMatches[2]
var state = message.toString()
activity = activityBySlugs(hubSlug, activitySlug)
if (!activity) { return }
if (state === 'on') {
startActivity(hubSlug, activity.id)
}else if (state === 'off'){
off(hubSlug)
}
} else if (deviceCommandMatches) {
var hubSlug = deviceCommandMatches[1]
var deviceSlug = deviceCommandMatches[2]
var messageComponents = message.toString().split(':')
var command = messageComponents[0]
var repeat = messageComponents[1]
command = commandBySlugs(hubSlug, deviceSlug, command)
if (!command) { return }
sendAction(hubSlug, command.action, repeat)
} else if (currentActivityCommandMatches) {
var hubSlug = currentActivityCommandMatches[1]
var messageComponents = message.toString().split(':')
var commandSlug = messageComponents[0]
var repeat = messageComponents[1]
hubState = harmonyHubStates[hubSlug]
if (!hubState) { return }
activity = activityBySlugs(hubSlug, hubState.current_activity.slug)
if (!activity) { return }
command = activity.commands[commandSlug]
if (!command) { return }
sendAction(hubSlug, command.action, repeat)
}
});
function startProcessing(hubSlug, harmonyClient){
harmonyHubClients[hubSlug] = harmonyClient
// update the list of activities
updateActivities(hubSlug)
// then do it on the set interval
clearInterval(harmonyActivityUpdateTimers[hubSlug])
harmonyActivityUpdateTimers[hubSlug] = setInterval(function(){ updateActivities(hubSlug) }, harmonyActivityUpdateInterval)
// update the state
updateState(hubSlug)
// update the list of activities on the set interval
clearInterval(harmonyStateUpdateTimers[hubSlug])
harmonyStateUpdateTimers[hubSlug] = setInterval(function(){ updateState(hubSlug) }, harmonyStateUpdateInterval)
// update devices
updateDevices(hubSlug)
// update the list of devices on the set interval
clearInterval(harmonyDeviceUpdateTimers[hubSlug])
harmonyDeviceUpdateTimers[hubSlug] = setInterval(function(){ updateDevices(hubSlug) }, harmonyDeviceUpdateInterval)
}
function updateActivities(hubSlug){
harmonyHubClient = harmonyHubClients[hubSlug]
if (!harmonyHubClient) { return }
console.log('Updating activities for ' + hubSlug + '.')
try {
harmonyHubClient.getActivities().then(function(activities){
foundActivities = {}
activities.some(function(activity) {
foundActivities[activity.id] = {id: activity.id, slug: parameterize(activity.label), label:activity.label, isAVActivity: activity.isAVActivity}
Object.defineProperty(foundActivities[activity.id], "commands", {
enumerable: false,
writeable: true,
value: getCommandsFromControlGroup(activity.controlGroup)
});
})
harmonyActivitiesCache[hubSlug] = foundActivities
})
} catch(err) {
console.log("ERROR: " + err.message);
}
}
function updateState(hubSlug){
harmonyHubClient = harmonyHubClients[hubSlug]
if (!harmonyHubClient) { return }
console.log('Updating state for ' + hubSlug + '.')
// save for comparing later after we get the true current state
var previousActivity = currentActivity(hubSlug)
try {
harmonyHubClient.getCurrentActivity().then(function(activityId){
data = {off: true}
activity = harmonyActivitiesCache[hubSlug][activityId]
commands = Object.keys(activity.commands).map(function(commandSlug){
return activity.commands[commandSlug]
})
if (activityId != -1 && activity) {
data = {off: false, current_activity: activity, activity_commands: commands}
}else{
data = {off: true, current_activity: activity, activity_commands: commands}
}
// cache state for later
harmonyHubStates[hubSlug] = data
if (!previousActivity || (activity.id != previousActivity.id)) {
publish('hubs/' + hubSlug + '/' + 'current_activity', activity.slug, {retain: true})
publish('hubs/' + hubSlug + '/' + 'state', activity.id == -1 ? 'off' : 'on' , {retain: true})
for (var i = 0; i < cachedHarmonyActivities(hubSlug).length; i++) {
activities = cachedHarmonyActivities(hubSlug)
cachedActivity = activities[i]
if (activity == cachedActivity) {
publish('hubs/' + hubSlug + '/' + 'activities/' + cachedActivity.slug + '/state', 'on', {retain: true})
}else{
publish('hubs/' + hubSlug + '/' + 'activities/' + cachedActivity.slug + '/state', 'off', {retain: true})
}
}
}
})
} catch(err) {
console.log("ERROR: " + err.message);
}
}
function updateDevices(hubSlug){
harmonyHubClient = harmonyHubClients[hubSlug]
if (!harmonyHubClient) { return }
console.log('Updating devices for ' + hubSlug + '.')
try {
harmonyHubClient.getAvailableCommands().then(function(commands) {
foundDevices = {}
commands.device.some(function(device) {
deviceCommands = getCommandsFromControlGroup(device.controlGroup)
foundDevices[device.id] = {id: device.id, slug: parameterize(device.label), label:device.label}
Object.defineProperty(foundDevices[device.id], "commands", {
enumerable: false,
writeable: true,
value: deviceCommands
});
})
harmonyDevicesCache[hubSlug] = foundDevices
})
} catch(err) {
console.log("Devices ERROR: " + err.message);
}
}
function getCommandsFromControlGroup(controlGroup){
deviceCommands = {}
controlGroup.some(function(group) {
group.function.some(function(func) {
slug = parameterize(func.label)
deviceCommands[slug] = {name: func.name, slug: slug, label: func.label}
Object.defineProperty(deviceCommands[slug], "action", {
enumerable: false,
writeable: true,
value: func.action.replace(/\:/g, '::')
});
})
})
return deviceCommands
}
function cachedHarmonyActivities(hubSlug){
activities = harmonyActivitiesCache[hubSlug]
if (!activities) { return [] }
return Object.keys(harmonyActivitiesCache[hubSlug]).map(function(key) {
return harmonyActivitiesCache[hubSlug][key]
})
}
function currentActivity(hubSlug){
harmonyHubClient = harmonyHubClients[hubSlug]
harmonyHubState = harmonyHubStates[hubSlug]
if (!harmonyHubClient || !harmonyHubState) { return null}
return harmonyHubState.current_activity
}
function activityBySlugs(hubSlug, activitySlug){
var activity
cachedHarmonyActivities(hubSlug).some(function(a) {
if(a.slug === activitySlug) {
activity = a
return true
}
})
return activity
}
function activityCommandsBySlugs(hubSlug, activitySlug){
activity = activityBySlugs(hubSlug, activitySlug)
if (activity) {
return Object.keys(activity.commands).map(function(commandSlug){
return activity.commands[commandSlug]
})
}
}
function cachedHarmonyDevices(hubSlug){
devices = harmonyDevicesCache[hubSlug]
if (!devices) { return [] }
return Object.keys(harmonyDevicesCache[hubSlug]).map(function(key) {
return harmonyDevicesCache[hubSlug][key]
})
}
function deviceBySlugs(hubSlug, deviceSlug){
var device
cachedHarmonyDevices(hubSlug).some(function(d) {
if(d.slug === deviceSlug) {
device = d
return true
}
})
return device
}
function commandBySlugs(hubSlug, deviceSlug, commandSlug){
var command
device = deviceBySlugs(hubSlug, deviceSlug)
if (device){
if (commandSlug in device.commands){
command = device.commands[commandSlug]
}
}
return command
}
function off(hubSlug){
harmonyHubClient = harmonyHubClients[hubSlug]
if (!harmonyHubClient) { return }
harmonyHubClient.turnOff().then(function(){
updateState(hubSlug)
})
}
function startActivity(hubSlug, activityId){
harmonyHubClient = harmonyHubClients[hubSlug]
if (!harmonyHubClient) { return }
harmonyHubClient.startActivity(activityId).then(function(){
updateState(hubSlug)
})
}
function sendAction(hubSlug, action, repeat){
repeat = Number.parseInt(repeat) || 1;
harmonyHubClient = harmonyHubClients[hubSlug]
if (!harmonyHubClient) { return }
var pressAction = 'action=' + action + ':status=press:timestamp=0';
var releaseAction = 'action=' + action + ':status=release:timestamp=55';
for (var i = 0; i < repeat; i++) {
harmonyHubClient.send('holdAction', pressAction).then(function (){
harmonyHubClient.send('holdAction', releaseAction)
})
}
}
function publish(topic, message, options){
topic = TOPIC_NAMESPACE + "/" + topic
mqttClient.publish(topic, message, options);
}
app.get('/_ping', function(req, res){
res.send('OK');
})
app.get('/', function(req, res){
res.sendfile('index.html');
})
app.get('/hubs', function(req, res){
res.json({hubs: Object.keys(harmonyHubClients)})
})
app.get('/hubs/:hubSlug/activities', function(req, res){
hubSlug = req.params.hubSlug
harmonyHubClient = harmonyHubClients[hubSlug]
if (harmonyHubClient) {
res.json({activities: cachedHarmonyActivities(hubSlug)})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.get('/hubs/:hubSlug/activities/:activitySlug/commands', function(req, res){
hubSlug = req.params.hubSlug
activitySlug = req.params.activitySlug
commands = activityCommandsBySlugs(req.params.hubSlug, req.params.activitySlug);
if (commands) {
res.json({commands: commands})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.get('/hubs/:hubSlug/devices', function(req, res){
hubSlug = req.params.hubSlug
harmonyHubClient = harmonyHubClients[hubSlug]
if (harmonyHubClient) {
res.json({devices: cachedHarmonyDevices(hubSlug)})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.get('/hubs/:hubSlug/devices/:deviceSlug/commands', function(req, res){
hubSlug = req.params.hubSlug
deviceSlug = req.params.deviceSlug
device = deviceBySlugs(hubSlug, deviceSlug)
if (device) {
commands = Object.keys(device.commands).map(function(commandSlug){
return device.commands[commandSlug]
})
res.json({commands: commands})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.get('/hubs/:hubSlug/status', function(req, res){
hubSlug = req.params.hubSlug
harmonyHubClient = harmonyHubClients[hubSlug]
if (harmonyHubClient) {
res.json(harmonyHubStates[hubSlug])
}else{
res.status(404).json({message: "Not Found"})
}
})
app.get('/hubs/:hubSlug/commands', function(req, res){
hubSlug = req.params.hubSlug
activitySlug = harmonyHubStates[hubSlug].current_activity.slug
commands = activityCommandsBySlugs(hubSlug, activitySlug);
if (commands) {
res.json({commands: commands})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.post('/hubs/:hubSlug/commands/:commandSlug', function(req, res){
hubSlug = req.params.hubSlug
activitySlug = harmonyHubStates[hubSlug].current_activity.slug
var commandSlug = req.params.commandSlug
activity = activityBySlugs(hubSlug, activitySlug)
if (activity && commandSlug in activity.commands)
{
sendAction(hubSlug, activity.commands[commandSlug].action, req.query.repeat)
res.json({message: "ok"})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.put('/hubs/:hubSlug/off', function(req, res){
hubSlug = req.params.hubSlug
harmonyHubClient = harmonyHubClients[hubSlug]
if (harmonyHubClient) {
off(hubSlug)
res.json({message: "ok"})
}else{
res.status(404).json({message: "Not Found"})
}
})
// DEPRECATED
app.post('/hubs/:hubSlug/start_activity', function(req, res){
activity = activityBySlugs(req.params.hubSlug, req.query.activity)
if (activity) {
startActivity(req.params.hubSlug, activity.id)
res.json({message: "ok"})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.post('/hubs/:hubSlug/activities/:activitySlug', function(req, res){
activity = activityBySlugs(req.params.hubSlug, req.params.activitySlug)
if (activity) {
startActivity(req.params.hubSlug, activity.id)
res.json({message: "ok"})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.post('/hubs/:hubSlug/devices/:deviceSlug/commands/:commandSlug', function(req, res){
command = commandBySlugs(req.params.hubSlug, req.params.deviceSlug, req.params.commandSlug)
if (command) {
sendAction(req.params.hubSlug, command.action, req.query.repeat)
res.json({message: "ok"})
}else{
res.status(404).json({message: "Not Found"})
}
})
app.get('/hubs_for_index', function(req, res){
hubSlugs = Object.keys(harmonyHubClients)
output = ""
Object.keys(harmonyHubClients).forEach(function(hubSlug) {
output += '<h3 class="hub-name">' + hubSlug.replace('-', ' ') + '</h3>'
output += '<p><span class="method">GET</span> <a href="/hubs/' + hubSlug + '/status">/hubs/' + hubSlug + '/status</a></p>'
output += '<p><span class="method">GET</span> <a href="/hubs/' + hubSlug + '/activities">/hubs/' + hubSlug + '/activities</a></p>'
output += '<p><span class="method">GET</span> <a href="/hubs/' + hubSlug + '/commands">/hubs/' + hubSlug + '/commands</a></p>'
cachedHarmonyActivities(hubSlug).forEach(function(activity) {
path = '/hubs/' + hubSlug + '/activities/' + activity.slug + '/commands'
output += '<p><span class="method">GET</span> <a href="' + path + '">' + path + '</a></p>'
})
output += '<p><span class="method">GET</span> <a href="/hubs/' + hubSlug + '/devices">/hubs/' + hubSlug + '/devices</a></p>'
cachedHarmonyDevices(hubSlug).forEach(function(device) {
path = '/hubs/' + hubSlug + '/devices/' + device.slug + '/commands'
output += '<p><span class="method">GET</span> <a href="' + path + '">' + path + '</a></p>'
})
});
res.send(output)
})
if (enableHTTPserver) {
app.listen(process.env.PORT || 8282)
}