This repository has been archived by the owner on Feb 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.js
693 lines (590 loc) · 22.4 KB
/
index.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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/*
Copyright 2012 WiredPrairie.us
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
FYI: Nest is a registered trademark of Nest Labs
*/
(function () {
"use strict";
var https = require('https'),
queryString = require('querystring'),
url = require('url'),
util = require('util');
var nestSession = {};
var defaultNestUserAgent = 'Nest/3.0.15 (iOS) os=6.0 platform=iPad3,1';
var fanModes = {
'auto': 'auto',
'on': 'on'
};
var temperatureTypes = {
'cool' : 'cool',
'heat' : 'heat',
'off': 'off',
'range' : 'range'
};
/* always call login first. :) */
/**
* Login to the Nest thermostat.
* @param {String} username Your Nest user name.
* @param {String} password Your nest password.
* @param {Function} done Callback to be called when login is complete.
*/
var login = function (username, password, done) {
nestPost({
hostname: 'home.nest.com',
port: 443,
path:'/user/login',
body: { 'username': username, 'password': password },
done: function(data) {
if (!data) {
if (typeof done === 'function') return done(new Error('parse error'), null);
} else if (data.error) {
if (typeof done === 'function') {
done(new Error(data.error_description), null);
}
} else {
nestSession = data;
nestExports.session = data;
nestSession.urls.transport_url = url.parse(nestSession.urls.transport_url);
if (typeof done === 'function') {
done(null, data);
}
}
}
});
};
// Post data to Nest.
// Settings object
// {
// hostname: string, usually set to the transport URL (default)
// port: defaults to 443, override here
// path : string
// body : string or object, if string, sent as is
// if object, converted to form-url encoded
// if body is string, content-type is auto set to
// application/json
// otherwise, set to urlencoded
// override this value with the headers param if
// needed
// headers: { headerName: Value }
// done: callback function
// }
var nestPost = function (settings) {
var allData = [];
var post_data;
var contentType;
var hostname, port, path, body, headers, done;
if (typeof settings === 'function') {
// call the function and get the results, which
// MUST be an object (so that it's processed below)
settings = settings();
}
if (settings && typeof settings === 'object') {
hostname = settings.hostname || nestSession.urls.transport_url.hostname;
port = settings.port || nestSession.urls.transport_url.port;
path = settings.path;
body = settings.body || null;
headers = settings.headers;
done = settings.done;
} else {
throw new Error("Settings I need to function properly!");
}
// convert to a form url encoded body
if (typeof body !== 'string') {
post_data = queryString.stringify(body);
contentType = 'application/x-www-form-urlencoded; charset=utf-8';
} else {
post_data = body;
contentType = 'application/json';
}
var options = {
host:hostname,
port:port,
path:path,
method:'POST',
headers:{
'Content-Type':contentType,
'User-Agent':nestExports.userAgent,
'Content-Length':post_data.length
}
};
if (headers) {
options.headers = merge(options.headers, headers);
}
// if we're already authorized, add the necessary stuff....
if (nestSession && nestSession.access_token) {
options.headers = merge(options.headers, {
'X-nl-user-id':nestSession.userid,
'X-nl-protocol-version':'1',
'Accept-Language':'en-us',
'Authorization':'Basic ' + nestSession.access_token
});
}
var request = https.request(options,
function (response) {
response.setEncoding('utf8');
response.on('data', function (data) {
allData.push(data);
});
response.on('error', function () {
if (done) {
done(null, response.headers || {});
}
});
response.on('end', function () {
// convert all data
allData = allData.join('');
if (allData && typeof allData === 'string' && allData.length > 0) {
try { allData = JSON.parse(allData); } catch(ex) {
nestExports.logger.error('Error parsing JSON', { exception: ex });
allData = null;
}
} else {
allData = null;
}
if (done) {
done(allData, response.headers || {});
}
});
});
request.write(post_data);
request.end();
};
var nestGet = function (path, done) {
var allData = [];
var options = {
host:nestSession.urls.transport_url.hostname,
port:nestSession.urls.transport_url.port,
path:path,
method:'GET',
headers:{
'User-Agent':nestExports.userAgent,
'X-nl-user-id':nestSession.userid,
'X-nl-protocol-version':'1',
'Accept-Language':'en-us',
'Authorization':'Basic ' + nestSession.access_token
}
};
var request = https.request(options,
function (response) {
response.setEncoding('utf8');
response.on('data', function (data) {
allData.push(data);
});
response.on('error', function (err) {
nestExports.logger.error('Error setting fetching information', { exception: err });
if (done) {
done(null);
}
});
response.on('end', function () {
// convert all data
allData = allData.join('');
if (allData && typeof allData === 'string' && allData.length > 0) {
try { allData = JSON.parse(allData); } catch(ex) {
nestExports.logger.error('Error parsing JSON', { exception: ex });
allData = null;
}
} else {
allData = null;
}
if (done) {
done(allData);
}
});
});
request.end();
};
var fetchCurrentStatus = function (done) {
nestGet('/v2/mobile/' + nestSession.user, function (data) {
if (!data) {
return nestExports.logger.error('Error to retrieve status');
}
nestExports.lastStatus = data;
if (done) {
done(data);
}
});
};
function pushKeys(keys, node, idNode) {
idNode = idNode || node; // might be the same thing ...
var lastStatus = nestExports.lastStatus;
var src;
var version = 0;
var timestamp = 0;
// loop through a master list (that always has all keys)
// but we might find data stored more specifically for a single key
for (var id in lastStatus[idNode]) {
src = version = timestamp = 0;
if (lastStatus[node] && lastStatus[node].hasOwnProperty(id)) {
src = node;
version = lastStatus[node][id]['$version'];
timestamp = lastStatus[src][id]['$timestamp'] || toUtc().getTime();
} else if (lastStatus[idNode] && lastStatus[idNode].hasOwnProperty(id)) {
src = idNode;
}
if (src) {
keys.push({
key:node + '.' + id,
version:parseInt(version, 10), // subtle -- this MUST be a number, and not a quoted string with a number
timestamp:parseInt(timestamp, 10) // ditto
});
}
}
}
// returns current date/time as UTC (or UTC of passed value)
// to convert to a nest friendly time, use .getTime() on the return
// value.
function toUtc(now) {
now = now || new Date();
var now_utc = new Date(now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds(),
now.getUTCMilliseconds()
);
return now_utc;
}
var subscribe = function (done, types) {
validateStatus();
// always have something ...
types = types || ['shared'];
var body = {};
// the only thing sent are the keys in a subscription
var keys = body.keys = [];
// here's what we did last time
var lastStatus = nestExports.lastStatus;
for (var i = 0, l = types.length; i < l; i++) {
var key = types[i];
switch (key) {
case 'user':
case 'shared':
case 'track':
case 'device':
case 'structure':
case 'user_alert_dialog':
case 'user_settings':
pushKeys(keys, key);
break;
case 'energy_latest':
pushKeys(keys, key, 'device');
break;
default:
throw new Error("Unknown subscription type: " + key);
}
}
keys.sort(function (a, b) {
var d1 = a.key.split('.');
var d2 = b.key.split('.');
if (d1[1] < d2[1]) {
return -1;
}
if (d1[1] > d2[1]) {
return 1;
}
if (d1[0].substr(0, 6) === 'energy') {
return 1;
}
return 0;
});
nestPost({
path:'/v2/subscribe',
body:JSON.stringify(body),
headers:{
'X-nl-subscribe-timeout':60
},
done:function (data, headers) {
if (!data || !headers) {
// nothing to do apparently ....
done();
return;
}
var device = headers['x-nl-skv-key'];
var timestamp = headers['x-nl-skv-timestamp'] || toUtc().getTime();
var version = headers['x-nl-skv-version'];
if (typeof device === 'string' && device.length > 0) {
device = device.split('.');
if (device.length > 1) {
// throw the version and timestamp on in a standard location for next time!
data['$version'] = version;
data['$timestamp'] = timestamp;
lastStatus[device[0]] = lastStatus[device[0]] || {};
lastStatus[device[0]][device[1]] = data;
if (done) {
done(device[1], data, device[0]);
return;
}
}
}
done();
}
}
);
};
// if first parameter is not a deviceId, treats
// it like a temperature, and sets the temperature
// using that value (and then uses the first thermostat
// found in your structure
// setTemperature(temp)
// equiv to setTemperature(getFirstDeviceId(), temp)
var setTemperature = function (deviceId, tempC) {
validateStatus();
if (typeof tempC === 'undefined') {
if (!isDeviceId(deviceId)) {
deviceId = getFirstDeviceId();
tempC = deviceId;
}
}
// likely passed in a F temp, so just convert it.
if (tempC > 45) {
tempC = fahrenheitToCelsius(tempC);
}
var body = {
'target_change_pending':true,
'target_temperature':tempC
};
body = JSON.stringify(body);
var headers = {
'X-nl-base-version':nestExports.lastStatus['shared'][deviceId]['$version'],
'Content-Type':'application/json'
};
nestPost({
path:'/v2/put/shared.' + deviceId,
body:body,
headers:headers,
done:function (data) {
nestExports.logger.debug('Set temperature');
}
});
};
var setTemperatureRange = function (deviceId, tempCLow, tempCHigh) {
validateStatus();
if (typeof tempCHigh === 'undefined') {
if (!isDeviceId(deviceId)) {
tempCHigh = tempCLow;
tempCLow = deviceId;
deviceId = getFirstDeviceId();
}
}
// likely passed in a F temp, so just convert it.
if (tempCLow > 45) {
tempCLow = fahrenheitToCelsius(tempCLow);
}
if (tempCHigh > 45) {
tempCHigh = fahrenheitToCelsius(tempCHigh);
}
var body = {
'target_change_pending':true,
'target_temperature_low':tempCLow,
'target_temperature_high':tempCHigh
};
body = JSON.stringify(body);
var headers = {
'X-nl-base-version':nestExports.lastStatus['shared'][deviceId]['$version'],
'Content-Type':'application/json'
};
nestPost({
path:'/v2/put/shared.' + deviceId,
body:body,
headers:headers,
done:function (data) {
console.log('Set temperature range');
}
});
};
var setAway = function (away, structureId) {
validateStatus();
structureId = structureId || getFirstStructureId();
if (!structureId) {
throw new Error('Missing required structureId');
}
away = typeof away === 'undefined' ? true : away; // default to Away
var body = {
'away_timestamp':toUtc().getTime(),
'away':away,
'away_setter':0
};
body = JSON.stringify(body);
var headers = {
'X-nl-base-version':nestExports.lastStatus['structure'][structureId]['$version'],
'Content-Type':'application/json'
};
nestPost({
path:'/v2/put/structure.' + structureId,
body:body,
headers:headers,
done:function (data) {
nestExports.logger.debug('Set away to ' + away);
}
});
};
var setHome = function (structureId) {
setAway(false, structureId);
};
var setFanMode = function (deviceId, fanMode) {
validateStatus();
deviceId = deviceId || getFirstDeviceId();
if (!deviceId) {
throw new Error('Missing required deviceId');
}
if (! (fanMode in fanModes)) {
throw new Error('Invalid fanMode: ' + fanMode);
}
var body = JSON.stringify({
'fan_mode': fanMode
});
var postData = {
path:'/v2/put/device.' + deviceId,
body:body,
done:function (data) {
nestExports.logger.debug('Set fan mode to ' + fanMode);
}
};
nestPost(postData);
};
var setFanModeOn = function (deviceId) {
setFanMode(deviceId, fanModes.on);
};
var setFanModeAuto = function (deviceId) {
setFanMode(deviceId, fanModes.auto);
};
var setTargetTemperatureType = function(deviceId, tempType) {
validateStatus();
deviceId = deviceId || getFirstDeviceId();
if (!deviceId) {
throw new Error('Missing required deviceId');
}
if (! (tempType in temperatureTypes)) {
throw new Error('Invalid temperature type: ' + tempType);
}
var body = JSON.stringify({
'target_temperature_type': tempType
});
var headers = {
'X-nl-base-version':nestExports.lastStatus['shared'][deviceId]['$version'],
'Content-Type':'application/json'
};
var postData = {
path:'/v2/put/shared.' + deviceId,
headers: headers,
body: body,
done: function(data) {
nestExports.logger.debug('Set temperature mode to ' + tempType);
},
error: function(res, error) {
nestExports.logger.error('Error setting temperature mode to ' + tempType, { exception: error });
}
};
nestPost(postData);
};
var fahrenheitToCelsius = function (f) {
return (f - 32) * 5 / 9.0;
};
var celsiusToFahrenheit = function (c) {
return Math.round(c * (9 / 5.0) + 32.0);
};
function merge(o1, o2) {
o1 = o1 || {};
if (!o2) {
return o1;
}
for (var p in o2) {
o1[p] = o2[p];
}
return o1;
}
function validateStatus() {
if (!nestExports.lastStatus) {
throw new Error("Must call fetchStatus to initialize.");
}
}
// this just gets the first structure id, nothing fancy
var getFirstStructureId = function () {
validateStatus();
var allIds = getStructureIds();
if (!allIds || allIds.length === 0) {
return null;
}
return allIds[0];
};
var getStructureIds = function () {
validateStatus();
var structures = nestExports.lastStatus.structure;
var allIds = [];
for (var id in structures) {
if (structures.hasOwnProperty(id)) {
allIds.push(id);
}
}
return allIds;
};
var getFirstDeviceId = function () {
validateStatus();
var allIds = getDeviceIds();
if (!allIds || allIds.length === 0) {
return null;
}
return allIds[0];
};
var getDeviceIds = function () {
validateStatus();
var devices = nestExports.lastStatus.device;
var allIds = [];
for (var id in devices) {
if (devices.hasOwnProperty(id)) {
allIds.push(id);
}
}
return allIds;
};
function isDeviceId(deviceId) {
return getDeviceIds().indexOf(deviceId) > -1;
}
// exported function list
var nestExports = {
'login':login,
'setTemperature':setTemperature,
'setTemperatureRange':setTemperatureRange,
'setAway':setAway,
'setHome':setHome,
'setFanModeOn':setFanModeOn,
'setFanModeAuto':setFanModeAuto,
'setTargetTemperatureType':setTargetTemperatureType,
'fetchStatus':fetchCurrentStatus,
'subscribe':subscribe,
'get':nestGet,
'post':nestPost,
'ftoc':fahrenheitToCelsius,
'ctof':celsiusToFahrenheit,
'getStructureId':getFirstStructureId,
'getStructureIds':getStructureIds,
'getDeviceIds':getDeviceIds,
'logger': { error : function(msg, props) { console.log(msg); if (!!props) console.trace(props.exception); }
, warning : function(msg, props) { console.log(msg); if (!!props) console.log(props); }
, notice : function(msg, props) { console.log(msg); if (!!props) console.log(props); }
, info : function(msg, props) { console.log(msg); if (!!props) console.log(props); }
, debug : function(msg, props) { console.log(msg); if (!!props) console.log(props); }
}
};
nestExports.userAgent = defaultNestUserAgent;
var root = this; // might be window ...
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = nestExports;
}
exports.nest = nestExports;
} else {
root.nest = nestExports;
}
})();