-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
208 lines (177 loc) · 9.7 KB
/
index.js
File metadata and controls
208 lines (177 loc) · 9.7 KB
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
'use strict';
const axios = require('axios');
const NestConnection = require('./lib/nest-connection');
let ThermostatAccessory, HomeAwayAccessory, TempSensorAccessory, ProtectAccessory, LockAccessory;
require('promise.prototype.finally').shim(Promise);
Promise.delay = function(time_ms) {
return new Promise(resolve => setTimeout(resolve, time_ms));
};
Promise.prototype.asCallback = function(callback) {
this.then(res => callback(null, res)).catch(err => callback(err));
};
class NestPlatform {
constructor(log, config, api) {
// auth info
this.config = config;
this.log = log;
this.api = api;
this.accessoryLookup = {};
this.cachedAccessories = [];
api.on('didFinishLaunching', async () => {
this.log('Fetching Nest devices.');
const generateAccessories = function(data) {
const foundAccessories = [];
const loadDevices = function(DeviceType) {
const disableFlags = {
'thermostat': 'Thermostat.Disable',
'temp_sensor': 'TempSensor.Disable',
'protect': 'Protect.Disable',
'home_away_sensor': 'HomeAway.Disable',
'lock': 'Lock.Disable'
};
const devices = (data.devices && data.devices[DeviceType.deviceGroup]) || {};
for (const deviceId of Object.keys(devices)) {
const device = devices[deviceId];
const serialNumber = device.serial_number;
if (!this.optionSet(disableFlags[DeviceType.deviceType], serialNumber, deviceId)) {
const structureId = device.structure_id;
if (this.config.structureId && this.config.structureId !== structureId) {
this.log('Skipping device ' + deviceId + ' because it is not in the required structure. Has ' + structureId + ', looking for ' + this.config.structureId + '.');
continue;
}
const structure = data.structures[structureId];
const accessory = new DeviceType(this.conn, this.log, device, structure, this);
this.accessoryLookup[deviceId] = accessory;
foundAccessories.push(accessory);
}
}
}.bind(this);
loadDevices(ThermostatAccessory);
loadDevices(HomeAwayAccessory);
loadDevices(TempSensorAccessory);
loadDevices(ProtectAccessory);
loadDevices(LockAccessory);
this.conn.accessories = this.accessoryLookup;
return foundAccessories;
}.bind(this);
const updateAccessories = function(data, accList) {
accList.map(function(acc) {
const group = data.devices[acc.deviceGroup];
const device = group && group[acc.deviceId];
if (device) {
const structureId = device.structure_id;
const structure = data.structures[structureId];
acc.updateData(device, structure);
}
});
};
const handleUpdates = function(data) {
if (Object.keys(this.accessoryLookup).length > 0) {
updateAccessories(data, this.accessoryLookup);
}
}.bind(this);
try {
this.conn = await this.setupConnection(this.optionSet('Debug.Verbose'), this.optionSet('Nest.FieldTest.Enable'));
await this.conn.subscribe(handleUpdates);
await this.conn.observe(handleUpdates);
let initialState = this.conn.apiResponseToObjectTree(this.conn.currentState);
this.accessoryLookup = generateAccessories(initialState);
// Unregister any stale cached accessories not matched to a current device
if (this.cachedAccessories.length > 0) {
try {
this.api.unregisterPlatformAccessories('@skirkpatrick88/homebridge-nest', 'Nest', this.cachedAccessories);
} catch (e) {
this.log.debug('Could not unregister stale cached accessories (may not be bridged yet): ' + e.message);
}
this.cachedAccessories = [];
}
// Register only new accessories (those without a matching cached entry)
const newAccessories = this.accessoryLookup.filter(el => el.isNew).map(el => el.accessory);
if (newAccessories.length > 0) {
this.api.registerPlatformAccessories('@skirkpatrick88/homebridge-nest', 'Nest', newAccessories);
}
let accessoriesMounted = this.accessoryLookup.map(el => el.constructor.name);
if (this.config.readyCallback) {
try {
const cbUrl = new URL(this.config.readyCallback);
if (cbUrl.protocol !== 'https:') {
this.log.warn('readyCallback URL must use HTTPS; skipping callback.');
} else {
const counts = accessoriesMounted.reduce((acc, name) => {
if (name === 'NestThermostatAccessory') acc.thermostat_count++;
else if (name === 'NestTempSensorAccessory') acc.tempsensor_count++;
else if (name === 'NestProtectAccessory') acc.protect_count++;
else if (name === 'NestLockAccessory') acc.lock_count++;
return acc;
}, { thermostat_count: 0, tempsensor_count: 0, protect_count: 0, lock_count: 0 });
axios.post(this.config.readyCallback, counts).catch(() => { });
}
} catch(e) {
this.log.warn('readyCallback URL is invalid; skipping callback.');
}
}
} catch(err) {
this.log.error(err);
this.log.error('NOTE: Because we couldn\'t connect to the Nest service, your Nest devices in HomeKit will not be responsive.');
this.cachedAccessories.forEach(accessory => {
accessory.services.forEach(service => {
service.characteristics.forEach(characteristic => {
if (characteristic.props.perms.includes(this.api.hap.Perms.PAIRED_READ)) {
characteristic.onGet(() => { throw new Error('Nest service not connected'); });
}
if (characteristic.props.perms.includes(this.api.hap.Perms.PAIRED_WRITE)) {
characteristic.onSet(async () => { throw new Error('Nest service not connected'); });
}
});
});
});
}
});
}
configureAccessory(accessory) {
this.cachedAccessories.push(accessory);
}
consumeCachedAccessory(UUID) {
const idx = this.cachedAccessories.findIndex(a => a.UUID === UUID);
if (idx >= 0) {
return this.cachedAccessories.splice(idx, 1)[0];
}
return null;
}
optionSet(key, serialNumber, deviceId) {
return key && this.config.options && (this.config.options.includes(key) || (serialNumber && this.config.options.includes(key + '.' + serialNumber)) || (deviceId && this.config.options.includes(key + '.' + deviceId)));
}
async setupConnection(verbose, fieldTestMode) {
if (!this.config.access_token && !this.config.googleAuth && !this.config.refreshToken && (!this.config.email || !this.config.password)) {
throw('You did not specify your Nest account credentials {\'email\',\'password\'}, or an access_token, refreshToken, or googleAuth, in config.json');
}
if (this.config.googleAuth && this.config.refreshToken) {
throw('You have specified both googleAuth and refreshToken in config.json. Please pick the one you want to use, and remove the other one');
}
if (this.config.googleAuth && (!this.config.googleAuth.issueToken || !this.config.googleAuth.cookies)) { // || !this.config.googleAuth.apiKey)) {
throw('When using googleAuth, you must provide issueToken and cookies in config.json. Please see README.md for instructions');
}
const conn = new NestConnection(this.config, this.log, verbose, fieldTestMode);
if (await conn.auth()) {
return conn;
} else {
throw('Unable to authenticate with Google/Nest.');
}
}
}
module.exports = function(homebridge) {
const exportedTypes = {
Accessory: homebridge.platformAccessory,
Service: homebridge.hap.Service,
Characteristic: homebridge.hap.Characteristic,
hap: homebridge.hap,
uuid: homebridge.hap.uuid
};
require('./lib/nest-device-accessory')(exportedTypes);
ThermostatAccessory = require('./lib/nest-thermostat-accessory')();
HomeAwayAccessory = require('./lib/nest-homeaway-accessory')();
TempSensorAccessory = require('./lib/nest-tempsensor-accessory')();
ProtectAccessory = require('./lib/nest-protect-accessory')();
LockAccessory = require('./lib/nest-lock-accessory')();
homebridge.registerPlatform('@skirkpatrick88/homebridge-nest', 'Nest', NestPlatform);
};