forked from philsniff/com.groups
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
108 lines (85 loc) · 2.63 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
'use strict';
const Homey = require('homey');
const HomeyAPI = require('athom-api').HomeyAPI;
const Librarian = require('./lib/librarian');
/**
*
*/
class Groups extends Homey.App {
onInit() {
this.log('<'+this.constructor.name+'>');
// Set our library reference
this.library = new Librarian();
// Prime the API into memory, set its events.
this.cache();
// Initialise the devices objects.
this.devices = {};
}
trace(message) {
var trace = new Error().stack, caller = stack.split('\n')[2].trim();
this.log('<' + caller + '>' + message);
}
/**
* IF the API hasn't been set, get it otherwise just returned cached API for current homey.
*
* @returns {object}
*/
getApi() {
if (!this.api) {
this.api = HomeyAPI.forCurrentHomey();
}
return this.api;
}
/**
* Gets all API devices from the Homey
*
* @todo should this be cached?
*
* @param id
* @returns {Promise<*>}
*/
async getDevices() {
const api = await this.getApi();
return await api.devices.getDevices();
}
/**
* Gets an API device from the APP, cache it
*
* Was added as storing the entire device with in a variable, in order to reduce the calls to the API
*
* @param id
* @returns {Promise<*>}
*/
async getDevice(id) {
if (!this.devices[id]) {
this.devices[id] = await (await this.getApi()).devices.getDevice({
id: id
});
}
return this.devices[id];
}
/**
* Primes the cache - then set watchers of when to clear it.
*
* When ever a device is added/deleted from Home, ensure that the cache is cleared
* so we can then add the new devices to a group, or stop old device from being added.
*
* Will also reset the cache when we add a new group (as it is a device).
*/
cache() {
this.getApi().then((api) => {
// When a new device is added to homey, clear the cache
api.devices.on('device.create', async (device) => {
console.log('device.create: ' + device.name);
this.api = false;
});
// when a device is deleted from homey, clear the cache.
// @todo investigate removing all devices from settings of groups which have been deleted.
api.devices.on('device.delete', async (device) => {
console.log('device.delete: ' + device);
this.api = false;
});
})
}
}
module.exports = Groups;