-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
355 lines (336 loc) · 14.1 KB
/
server.js
File metadata and controls
355 lines (336 loc) · 14.1 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
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
// import required essentials
const http = require('http');
const https = require('https')
const express = require('express');
var cors = require('cors');
const crypto = require('crypto');
const fetch = require('node-fetch');
const path = require('path');
const { access } = require('fs');
// create new app
const app = express();
app.use(express.json());
// app.use(express.static("express"));
// use it before all route definitions
// allowing below URL to access these APIs end-points
// you can replace this URL(http://localhost:8100) with your
// application URL from where you are calling these APIs
app.use(cors({origin: 'http://tuyaserver.herokuapp.com'}));
/* this '/items' URL will have two end-points:
→ localhost:3000/items/ (this returns array of objects)
→ localhost:3000/items/:id (this returns single object)
*/
const redHSV = {'h': 0, 's': 255, 'v': 255}
const yellowHSV = {'h': 60, 's': 255, 'v': 255}
const greenHSV = {'h': 120, 's': 255, 'v': 255}
const skyHSV = {'h': 180, 's': 255, 'v': 255}
const blueHSV = {'h': 240, 's': 255, 'v': 255}
const purpleHSV = {'h': 300, 's': 255, 'v': 255}
const whiteHSV = {'h': 0, 's': 0, 'v': 255}
const gorgCommand = JSON.stringify({commands: [{"code": "flash_scene_4",
"value": {
"bright": 255,
"frequency": 191,
"hsv": [
redHSV, yellowHSV, greenHSV, skyHSV, blueHSV, purpleHSV
],
"temperature": 0
}}]});
const onCommand = JSON.stringify({commands: [{'code': 'switch_led', 'value': true}]});
const offCommand = JSON.stringify({commands: [{'code': 'switch_led', 'value': false}]});
const brightCommand = {commands: [{'code': 'bright_value', 'value': 0}]};
const whiteCommand = JSON.stringify({commands: [{'code': 'work_mode', 'value': 'white'}]});
const devices = {lights: ["", ""], vals: [false, false], modes: ['white', 'white']}
var apiHead = { client_id: "", access_token: "", sign: "", sign_method: "HMAC-SHA256", t: 0};
var keyExpireTime = 0;
var refreshToken;
var accessTokenInterval;
var brightness;
const refreshAccessToken = (rt) => {
var t = Date.now();
const signature1 = crypto.createHmac('sha256', '').update(apiHead['client_id']).update(t.toString()).digest("hex").toUpperCase();
apiHead.t = t;
apiHead.sign = signature1;
let refreshPath = 'https://openapi.tuyaus.com/v1.0/token/' + refreshToken;
fetch(refreshPath, {
headers: apiHead
})
.then((response) => response.json())
.then((data) => {
console.log(apiHead);
console.log(data);
apiHead.access_token = data['result']['access_token'];
keyExpireTime = data['result']['expire_time'];
refreshToken = data['result']['refresh_token'];
t = Date.now();
const signature2 = crypto.createHmac('sha256', '').update(apiHead.client_id).update(apiHead.access_token).update(t.toString()).digest("hex").toUpperCase();
apiHead.t = t;
apiHead.sign = signature2;
console.log(apiHead);
// clearInterval();
accessTokenInterval = setTimeout(refreshAccessToken, 7200000, refreshToken);
return [data['result']['access_token'], signature2, t];
})
.catch((error) => {console.log(error)});
};
const initialize = () => {
var t = Date.now();
const signature1 = crypto.createHmac('sha256', '').update(apiHead['client_id']).update(t.toString()).digest("hex").toUpperCase();
apiHead.t = t;
apiHead.sign = signature1;
fetch('https://openapi.tuyaus.com/v1.0/token?grant_type=1', {
headers: apiHead
})
.then((response) => response.json())
.then((data) => {
console.log(data);
apiHead.access_token = data['result']['access_token'];
keyExpireTime = data['result']['expire_time'];
refreshToken = data['result']['refresh_token'];
accessTokenInterval = setTimeout(refreshAccessToken, keyExpireTime*1000, refreshToken)
// setTimeout(refreshAccessToken, keyExpireTime*1000, refreshToken);
t = Date.now();
const signature2 = crypto.createHmac('sha256', '').update(apiHead.client_id).update(apiHead.access_token).update(t.toString()).digest("hex").toUpperCase();
apiHead.t = t;
apiHead.sign = signature2;
console.log(apiHead);
let opts = {
hostname: 'openapi.tuyaus.com',
path: '/v1.0/devices/64304636a4cf12d76aad/status',
headers: apiHead
};
https.get(opts, (res2) => {
const { statusCode } = res2;
const contentType = res2.headers['content-type'];
res2.setEncoding('utf8');
let rawData = '';
res2.on('data', (chunk) => { rawData += chunk; });
res2.on('end', () => {
try {
let data = JSON.parse(rawData);
// console.log(data)
brightness = data['result'][2]['value']
devices['vals'][0] = data['result'][0]['value']
devices['vals'][1] = data['result'][0]['value']
devices['modes'][0] = data['result'][1]['value']
devices['modes'][1] = data['result'][1]['value']
//res.send(JSON.parse(rawData));
} catch (e) {
console.error(e.message);
}
});
});
})
.catch((error) => {console.log(error)});
}
initialize();
app.post('/onoff', function(req, res) {
let result = true;
for (var i = 0; i < devices['lights'].length; ++i) {
var commandEnd = "/v1.0/devices/" + devices['lights'][i] + "/commands";
let opts = {
hostname: 'openapi.tuyaus.com',
method: "POST",
path: commandEnd,
headers: apiHead
}
const req2 = https.request(opts, (res2) => {
const { statusCode } = res2;
const contentType = res2.headers['content-type'];
res2.setEncoding('utf8');
let rawData = '';
res2.on('data', (chunk) => { rawData += chunk; });
res2.on('end', () => {
try {
let data = JSON.parse(rawData);
if (data['success'] == false){
// clearTimeout();
result = false;
let newHead = refreshAccessToken(refreshToken);
req2.setHeader('access_token', newHead[0]);
req2.setHeader('sign', newHead[1]);
req2.setHeader('t', newHead[2]);
}
console.log(data);
} catch (e) {
console.error(e.message);
}
});
});
if (result == true) {
if (devices['vals'][i] == true) {
req2.write(offCommand);
devices['vals'][i] = false;
} else {
req2.write(onCommand);
devices['vals'][i] = true;
}
}
req2.end();
}
let commandLineOut = "Turned lights " + (devices['vals'][0] == true ? "on" : "off");
console.log(commandLineOut);
res.status(200).json({command: "on/off", results: {sucess: true, changed_to: devices['vals'][0]}});
});
app.post('/modechange', function(req, res) {
for (var i = 0; i < devices['lights'].length; ++i) {
var commandEnd = "/v1.0/devices/" + devices['lights'][i] + "/commands";
let opts = {
hostname: 'openapi.tuyaus.com',
method: "POST",
path: commandEnd,
headers: apiHead
}
const req2 = https.request(opts, (res2) => {
const { statusCode } = res2;
const contentType = res2.headers['content-type'];
res2.setEncoding('utf8');
let rawData = '';
res2.on('data', (chunk) => { rawData += chunk; });
res2.on('end', () => {
try {
let data = JSON.parse(rawData);
if (data['success'] == false){
// clearTimeout();
let newHead = refreshAccessToken(refreshToken);
req2.setHeader('access_token', newHead[0]);
req2.setHeader('sign', newHead[1]);
req2.setHeader('t', newHead[2]);
}
console.log(data);
} catch (e) {
console.error(e.message);
}
});
});
if (devices['modes'][i] == 'scene_4') {
req2.write(whiteCommand);
devices['modes'][i] = 'white';
} else {
req2.write(gorgCommand);
devices['modes'][i] = 'scene_4';
}
req2.end();
}
let commandLineOut = "Mode changed to " + (devices['modes'][0] == 'white' ? "white" : "rainbow");
console.log(commandLineOut);
res.status(200).json({command: "changeMode", results: {sucess: true, changed_to: devices['modes'][0]}});
});
app.post('/brightup', function(req, res) {
let oldBrightness = brightness;
if (brightness != 255 && devices['modes'][0] != "scene_4") {
let thisCommand = brightCommand;
if (brightness + 23 >= 255) {
thisCommand['commands'][0]['value'] = 255;
brightness = 255;
} else {
thisCommand['commands'][0]['value'] = brightness + 23;
brightness = brightness + 23;
}
for (var i = 0; i < devices['lights'].length; ++i){
var commandEnd = "/v1.0/devices/" + devices['lights'][i] + "/commands";
let opts = {
hostname: 'openapi.tuyaus.com',
method: "POST",
path: commandEnd,
headers: apiHead
}
const req2 = https.request(opts, (res2) => {
const { statusCode } = res2;
const contentType = res2.headers['content-type'];
res2.setEncoding('utf8');
let rawData = '';
res2.on('data', (chunk) => { rawData += chunk; });
res2.on('end', () => {
try {
let data = JSON.parse(rawData);
if (data['success'] == false){
// clearTimeout();
let newHead = refreshAccessToken(refreshToken);
req2.setHeader('access_token', newHead[0]);
req2.setHeader('sign', newHead[1]);
req2.setHeader('t', newHead[2]);
}
console.log(data);
} catch (e) {
console.error(e.message);
}
});
});
req2.write(JSON.stringify(thisCommand));
req2.end();
}
}
let commandLineOut = (brightness == oldBrightness ? "Brightness unchanged" : "Brightness changed to " + brightness);
console.log(commandLineOut);
res.status(200).json({command: "brightnessUp", results: {sucess: true, changed_to: brightness}});
});
app.post('/brightdown', function(req, res) {
let oldBrightness = brightness;
let canChange = (brightness != 25 && devices['modes'][0] != "scene_4");
if (canChange) {
let thisCommand = brightCommand;
if (brightness - 23 <= 25) {
thisCommand['commands'][0]['value'] = 25;
brightness = 25;
} else {
thisCommand['commands'][0]['value'] = brightness - 23;
brightness = brightness - 23;
}
for (var i = 0; i < devices['lights'].length; ++i) {
var commandEnd = "/v1.0/devices/" + devices['lights'][i] + "/commands";
let opts = {
hostname: 'openapi.tuyaus.com',
method: "POST",
path: commandEnd,
headers: apiHead
}
const req2 = https.request(opts, (res2) => {
const { statusCode } = res2;
const contentType = res2.headers['content-type'];
res2.setEncoding('utf8');
let rawData = '';
res2.on('data', (chunk) => { rawData += chunk; });
res2.on('end', () => {
try {
let data = JSON.parse(rawData);
if (data['success'] == false){
// clearTimeout();
let newHead = refreshAccessToken(refreshToken);
req2.setHeader('access_token', newHead[0]);
req2.setHeader('sign', newHead[1]);
req2.setHeader('t', newHead[2]);
}
console.log(data);
} catch (e) {
console.error(e.message);
}
});
});
req2.write(JSON.stringify(thisCommand));
req2.end();
}
}
let commandLineOut = (brightness == oldBrightness ? "Brightness unchanged" : "Brightness changed to " + brightness);
console.log(commandLineOut);
res.status(200).json({command: "brightnessDown", results: {sucess: true, changed_to: brightness}});
});
app.get('/keepalive', function(req, res) {
console.log("STAYING ALIVE, STAYING ALIVE");
res.status(200).json({command: "keepAlive", results: {sucess: true}});
});
app.post('/newtoken', function(req, res) {
//refreshAccessToken(refreshToken);
res.status(200).json({command: "newToken", results: {sucess: true}});
});
// default URL to API
app.get('/', function(req, res) {
res.send("Nothing to see here");
});
app.get('*', function(req, res){
res.status(404).send('I think you\'re lost...');
});
const server = http.createServer(app);
const port = process.env.PORT || 8080;
server.listen(port);
console.debug('Server listening on port ' + port);