This repository has been archived by the owner on Jan 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnest.js
executable file
·189 lines (158 loc) · 3.71 KB
/
nest.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
#!/usr/bin/env node
'use strict';
/**
* config.json
*
* {
* device: "device id",
* token: "client token"
* }
*
*/
const commandLineArgs = require('command-line-args');
const commandLineUsage = require('command-line-usage');
const fs = require('fs');
const path = require('path');
const rp = require('request-promise');
const optionDefinitions = [
{
description: 'Show help',
name: 'help',
type: Boolean
},
{
description: 'Accepts cool or heat, sets mode of thermostat',
name: 'mode',
type: String
},
{
defaultOption: true,
description: 'Temperature to set thermostat to',
name: 'temp',
type: Number
}
];
let options;
try {
options = commandLineArgs(optionDefinitions);
} catch (e) {
options = {
help: true
}
}
const {
mode,
temp
} = options;
if (mode && mode !== 'heat' && mode !== 'cool') {
console.error(`Invalid mode '${mode}', accepted values are 'heat' and 'cool'`);
options.help = true;
}
if (temp && (temp > 76 || temp < 65)) {
console.error(`${temp} is too crazy!`);
options.help = true;
}
if (options.help) {
const usage = commandLineUsage([
{
content: `Set temperature and mode of nest thermostat
nest | reads temperature
nest 72 | sets temperature to 72
nest --mode cool 72 | sets mode to cool and temperature to 72`,
header: 'Nest'
},
{
header: 'Options',
optionList: optionDefinitions
},
{
content: 'If no options provided, reads current temperature'
}
]);
console.log(usage);
process.exit();
}
const baseUrl = 'https://developer-api.nest.com';
// config.json is in root directory
let config;
try {
const configPath = path.join(__dirname, './config.json');
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
} catch (e) {
console.error('Missing config.json, please copy from config.example.json and setup.');
process.exit(1);
}
if (!config) {
console.error('Missing config.json, please copy from config.example.json and setup.');
process.exit(1);
}
const {
device,
token
} = config;
const req = (data) => JSON.parse(data).devices.thermostats[device].target_temperature_f;
const reject = (resp) => {
const { response } = resp;
if (!response) {
return;
}
// Rate limit
if (response.statusCode === 429) {
console.error('Unable to set: rate limit exceeded');
return;
}
if (nested > 3) {
console.error('Unable to set: too many redirects');
return;
}
nested++;
requestOptions.url = resp.response.headers.location;
return rp(requestOptions).catch(reject);
};
const requestOptions = {
'headers': {
'Authorization': 'Bearer ' + token
},
'followRedirect': true
};
let nested;
const set = () => {
nested = 0;
requestOptions.method = 'PUT';
requestOptions.headers['Content-Type'] = 'application/json';
requestOptions.url = `${baseUrl}/devices/thermostats/${device}`;
requestOptions.removeRefererHeader = false;
return rp(requestOptions).catch(reject);
};
// Writing temperature
const setTemp = (temp) => {
requestOptions.body = JSON.stringify({ 'target_temperature_f': temp });
return set();
};
// Writing mode
const setMode = (mode) => {
requestOptions.body = JSON.stringify({ 'hvac_mode': mode });
return set();
};
const read = () => {
// Reading temperature
requestOptions.method = 'GET';
requestOptions.url = baseUrl;
requestOptions.path = '/';
nested = 0;
return rp(requestOptions).then(req);
};
// Writing temperature
const rs = [];
if (temp) {
rs.push(setTemp(temp));
}
if (mode) {
rs.push(setMode(mode));
}
// Doesn't matter if setters overlap, but read can't
Promise.all(rs).then(() =>
read()
.then(t => console.log(t))
.catch(e => {})
);