-
Notifications
You must be signed in to change notification settings - Fork 34
/
functions.js
591 lines (537 loc) · 17.4 KB
/
functions.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
// Main source: https://pypi.org/project/tuyapy/
// Insert the address of your cors anywhere server here, eg
const defaultCorsServer = "https://cors-anywhere.herokuapp.com/";
const approvedHosts = [
"smartathome.co.uk",
"www.smartathome.co.uk",
"192.168.1.93:8000",
"192.168.1.93:4443"
]
var proxyurl;
if (approvedHosts.includes(location.host)) {
proxyurl = "https://cors.smartathome.co.uk/";
} else {
proxyurl = defaultCorsServer;
}
var baseurl = "https://px1.tuyaeu.com/homeassistant/";
var autoRefreshTimer;
var user_info = {};
// Jquery ready is deprecated since 3.0
$(document).ready(function () {
testFirstCookie();
document.getElementById("password").onkeydown = function (e) {
if (e.key === 'Enter') {
do_login();
}
};
user_info = {
"access_token": getCookie("access_token"),
"sl_refresh_token": getCookie("sl_refresh_token"),
"sl_expires_in": getCookie("sl_expires_in")
};
console.log(user_info);
if (user_info["access_token"] !== "") {
const region = user_info.access_token.substring(0, 2);
if (region === "EU") {
} else if (region === "AY") {
baseurl = baseurl.replace("eu", "cn");
} else if (region === "AZ") {
baseurl = baseurl.replace("eu", "us");
}
if (region !== "AY") {
proxyurl = '';
}
}
logged_in = check_login();
if (logged_in["success"] === true) {
user_info["devices"] = logged_in["devices"];
on_login();
user_info["logged_in"] = true;
} else {
on_logout();
user_info["logged_in"] = false;
}
readLocalStorage();
$('#autorefresh').on("change", function () {
localStorage.autoRefresh = $(this).prop("checked");
checkAutorefresh();
});
checkAutorefresh();
var searchParams = new URLSearchParams(window.location.search);
if (searchParams.get("minimal") == "true") {
var els_to_hide = document.getElementsByClassName("minimal");
for (var i = 0; i < els_to_hide.length; i++) {
els_to_hide.item(i).classList.add("hidden")
};
}
});
function login(username, password, region, platform, storecreds) {
var url = baseurl + "auth.do";
if (region == '1') {
url = baseurl.replace('eu', 'us') + "auth.do";
} else if (region == '86') {
url = proxyurl + baseurl.replace('eu', 'cn') + "auth.do";
}
var headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
var data = {
"userName": username,
"password": password,
"countryCode": region,
"bizType": platform,
"from": "tuya",
}
$.ajax({
url: url, // since the default is eu, cors are enabled
type: "POST",
headers: headers,
data: data,
dataType: "json",
async: false,
success: function (json) {
store_tokens(json, storecreds);
}
});
}
function store_tokens(json, storecreds) {
if ("access_token" in json) {
user_info["access_token"] = json["access_token"];
user_info["sl_refresh_token"] = json["refresh_token"];
user_info["sl_expires_in"] = Date.now() + json["expires_in"] * 1000;
user_info["logged_in"] = true;
if (storecreds === true) {
setCookie("access_token", json["access_token"], json["expires_in"] / 3600);
setCookie("sl_refresh_token", json["refresh_token"], json["expires_in"] / 3600);
setCookie("sl_expires_in", Date.now() + json["expires_in"] * 1000, json["expires_in"] / 3600);
}
}
}
function get_device_list(refresh_access_token) {
if (refresh_access_token === true) {
refresh_token();
}
to_return = {};
var url = baseurl + "skill";
var headers = {
"Content-Type": "application/json"
}
data = {
"header": {
"name": "Discovery",
"namespace": "discovery",
"payloadVersion": 1,
},
"payload": {
"accessToken": user_info["access_token"],
},
}
$.ajax({
url: proxyurl + url,
type: "POST",
headers: headers,
data: JSON.stringify(data),
dataType: "json",
async: false,
success: function (json) {
console.log(json);
if ("header" in json && "code" in json["header"] && json["header"]["code"] === "FrequentlyInvoke") {
to_return["devices"] = (user_info["devices"] !== undefined ? user_info["devices"] : JSON.parse(localStorage.devices));
to_return["success"] = true;
} else if ("payload" in json && "devices" in json["payload"]) {
to_return["devices"] = merge_devices(json["payload"]["devices"], user_info["devices"]);
to_return["success"] = true;
localStorage.devices = JSON.stringify(to_return["devices"]);
}
}
});
return to_return
}
function merge_devices(a, b) {
if (b == null) { return a };
if (a.length != b.length) { return a };
for (device_no in b) {
if (!("data" in b[device_no])) { continue; };
if (!("data" in a[device_no])) { continue; };
for (prop in b[device_no]["data"]) {
if (!(prop in a[device_no]["data"])) {
a[device_no]["data"][prop] = b[device_no]["data"][prop];
}
}
}
return a;
}
function adjust_device(device, action, value_name, new_state) {
var to_return = {};
var url = baseurl + "skill";
var headers = {
"Content-Type": "application/json"
}
var data = {
"header": {
"name": action,
"namespace": "control",
"payloadVersion": 1
},
"payload": {
"accessToken": user_info["access_token"],
"devId": device["id"]
}
}
// object must be created before you can use a variable as a key
data["payload"][value_name] = new_state;
$.ajax({
url: proxyurl + url,
type: "POST",
headers: headers,
data: JSON.stringify(data),
dataType: "json",
async: false,
success: function (json) {
console.log(json);
to_return = json;
}
});
return to_return
}
function refresh_token() {
url = baseurl + "access.do";
params = { "grant_type": "refresh_token", "refresh_token": user_info["sl_refresh_token"], "rand": Math.random() }
$.ajax({
url: proxyurl + url,
type: "GET",
data: params,
dataType: "json",
async: false,
success: function (json) {
console.log(json);
new_info = store_tokens(json, true);
}
});
}
function do_login() {
var login_div = document.getElementById("login");
login_div.classList.add("hidden");
var loader_div = document.getElementById("loader");
loader_div.classList.remove("hidden");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var region = document.getElementById("region").value;
var platform = document.getElementById("platform").value;
var storecreds = document.getElementById("storecreds").checked;
setTimeout(function () {
login(username, password, region, platform, storecreds);
if (user_info["logged_in"] === true) {
const region = user_info.access_token.substring(0, 2);
if (region === "EU") {
} else if (region === "AY") {
baseurl = baseurl.replace("eu", "cn");
} else if (region === "AZ") {
baseurl = baseurl.replace("eu", "us");
}
if (region !== "AY") {
proxyurl = '';
}
device_list = get_device_list(false);
user_info["devices"] = device_list["devices"]
on_login();
} else {
on_logout();
document.getElementById("loginfailed").innerHTML = "Login failed";
}
}, 100);
}
function check_login() {
if (user_info["access_token"] !== "") {
console.log("Getting devices");
device_list = get_device_list(false);
return device_list;
} else {
console.log("No access_token");
return { "success": false };
}
}
function readLocalStorage() {
// Not initialized
if (localStorage.autoRefresh == null) {
localStorage.autoRefresh = "true";
localStorage.theme = "a";
}
$('#autorefresh').prop("checked", localStorage.autoRefresh === "true").checkboxradio("refresh");
if (localStorage.theme !== "a") {
checkTheme();
}
}
function checkTheme() {
switchTheme();
localStorage.theme = $("#page").attr("data-theme");
}
function checkAutorefresh() {
clearInterval(autoRefreshTimer);
if (localStorage.autoRefresh === "true" && user_info["logged_in"] === true) {
autoRefreshTimer = setInterval(update_devices, 31_000, true);
}
}
function on_login() {
var login_div = document.getElementById("login");
login_div.classList.add("hidden");
var switches = document.getElementById("switches");
switches.classList.remove("hidden");
var buttons = document.getElementById("buttons");
buttons.classList.remove("hidden");
var loader_div = document.getElementById("loader");
loader_div.classList.add("hidden");
update_devices(false);
checkAutorefresh();
}
function update_devices(force_update) {
if (force_update === true) {
device_list = get_device_list(true);
user_info["devices"] = device_list["devices"];
//$('#switches').html('');
}
var devices = user_info["devices"];
for (device_no in devices) {
add_or_update_switch(devices[device_no], device_no);
}
}
function toggle(device_no) {
var device = user_info["devices"][device_no];
var state = device["data"]["state"];
var dev_type = device["dev_type"];
if (state === false || dev_type === "scene") {
new_state = 1;
} else {
new_state = 0;
}
success = adjust_device(device, "turnOnOff", "value", new_state);
if ("header" in success && "code" in success["header"] && success["header"]["code"] === "SUCCESS" && dev_type !== "scene") {
device["data"]["state"] = !state;
add_or_update_switch(device, device_no);
}
}
function change_brightness(device_no, new_brightness) {
var device = user_info["devices"][device_no];
success = adjust_device(device, "brightnessSet", "value", new_brightness);
if ("header" in success && "code" in success["header"] && success["header"]["code"] === "SUCCESS") {
device["data"]["brightness"] = new_brightness * 10;
device["data"]["state"] = true;
add_or_update_switch(device, device_no);
}
}
function change_color_temperature(device_no, new_temperature) {
var device = user_info["devices"][device_no];
success = adjust_device(device, "colorTemperatureSet", "value", new_temperature);
if ("header" in success && "code" in success["header"] && success["header"]["code"] === "SUCCESS") {
// min temp = 1000, reports as 1000
// max temp = 10000, reports as 36294
new_color_temp = ((new_temperature - 1000) * 4.033) + 1000;
device["data"]["color_temp"] = new_color_temp;
device["data"]["color_mode"] = "white";
device["data"]["state"] = true;
add_or_update_switch(device, device_no);
}
}
function on_logout() {
var switches = document.getElementById("switches");
switches.classList.add("hidden");
var login_div = document.getElementById("login");
login_div.classList.remove("hidden");
var loader_div = document.getElementById("loader");
loader_div.classList.add("hidden");
}
function hide_device(device_id, name) {
console.log("hide: " +device_id);
var hiddenDevices = getCookie("sl_hidden_devices");
hiddenDevices += " "+device_id;
setCookie("sl_hidden_devices", hiddenDevices, 24*365*10);
document.getElementById("switches").innerHTML = "";
update_devices(false);
setTimeout(function() {alert(name+" hidden. Clear your cookies to undo.")}, 100);
}
function add_or_update_switch(device, device_no) {
var device_id = device["id"];
var hiddenDevices = getCookie("sl_hidden_devices");
if (hiddenDevices.split(" ").includes(device_id)) { return };
var name = device["name"];
var state = device["data"]["state"];
var online = device["data"]["online"];
if (online === false) { state = false };
var icon = device["icon"];
var type = device["dev_type"];
var currentActionDiv = $('#action_' + device_id);
if (currentActionDiv.length === 0) {
var deviceDiv = createElement("div", "gridElem singleSwitch borderShadow ui-btn ui-btn-up-b ui-btn-hover-b " + getSwitchClass(type, state));
var nameDiv = createElement("div", "switchName");
nameDiv.innerHTML = name;
var hideSpan = createElement("span", "hideDevice");
hideSpan.innerHTML = "❌";
hideSpan.onclick = function() {hide_device(device_id, name)};
var imgTable = createElement("table", "switchImg");
var imgTd = createElement("td");
imgTd.innerHTML = createImg(icon, name, type);
imgTable.appendChild(imgTd);
if ("color_mode" in device["data"] && online === true) {
var cTd = createColorSelector(device, device_no);
imgTable.appendChild(cTd);
}
var actionDiv = createElement("div", "switchAction");
actionDiv.id = "action_" + device_id;
actionDiv.innerHTML = createActionLink(device_no, online, state, type);
deviceDiv.appendChild(nameDiv);
deviceDiv.appendChild(hideSpan);
deviceDiv.appendChild(imgTable);
deviceDiv.appendChild(actionDiv);
if ("brightness" in device["data"] && online === true) {
var bTable = createBrightnessSlider(device, device_no);
deviceDiv.appendChild(bTable);
}
if ("color_temp" in device["data"] && online === true) {
var ctTable = createColorTempSlider(device, device_no);
deviceDiv.appendChild(ctTable);
}
$('#switches')[0].appendChild(deviceDiv);
setUpColors(device_no);
} else {
var parentDiv = currentActionDiv.parent()[0];
parentDiv.classList.remove("switch_true");
parentDiv.classList.remove("switch_false");
parentDiv.classList.add(getSwitchClass(type, state));
currentActionDiv.remove();
var newActionDiv = createElement("div", "switchAction");
newActionDiv.setAttribute("id", "action_" + device_id);
newActionDiv.innerHTML = createActionLink(device_no, online, state, type);
parentDiv.appendChild(newActionDiv);
if ("brightness" in device["data"] && online === true) {
document.getElementById("brightness_" + device_id).value = device["data"]["brightness"] / 10;
}
if ("color_temp" in device["data"] && online === true) {
document.getElementById("colortemp_" + device_id).value = ((device["data"]["color_temp"] - 1000) / 4.033) + 1000;
}
}
}
function getSwitchClass(type, state) {
return "switch_" + (type === "scene" ? "scene" : state);
}
function setUpColors(device_no) {
$("#color_" + device_no).spectrum({
type: "color",
hideAfterPaletteSelect: true,
showInitial: true,
showAlpha: false,
change: function () {
changeColor(this)
}
});
}
function createColorSelector(device, device_no) {
var cTd = createElement("td", "colorSelectorTd");
var inp = document.createElement("input", "colorSelector");
h = device["data"]["hue"];
s = device["data"]["saturation"];
v = device["data"]["brightness"];
inp.value = "hsv(" + h + ", " + s + ", " + v + ")";
inp.id = "color_" + device_no;
cTd.appendChild(inp);
return cTd;
}
function createBrightnessSlider(device, device_no) {
var device_id = device["id"];
var bTable = createElement("table", "switchBrightness");
var bTd = createElement("td");
var brightnessDiv = createElement("input", "slider100");
brightnessDiv.id = "brightness_" + device_id;
brightnessDiv.type = "range";
brightnessDiv.min = 11;
brightnessDiv.max = 100;
brightnessDiv.value = device["data"]["brightness"] / 10;
brightnessDiv.onchange = function () { change_brightness(device_no, this.value) };
bTd.appendChild(brightnessDiv);
bTable.appendChild(bTd);
var bTd2 = createElement("td");
bTd2.innerHTML = "🔆";
bTable.appendChild(bTd2);
return bTable;
}
function createColorTempSlider(device, device_no) {
var device_id = device["id"];
var ctTable = createElement("table", "switchColorTemp");
var ctTd1 = createElement("td");
ctTd1.innerHTML = "<small>2700K</small>";
ctTable.appendChild(ctTd1);
var ctTd = createElement("td");
var colorTempDiv = createElement("input", "colorTempSlider");
colorTempDiv.id = "colortemp_" + device_id;
colorTempDiv.type = "range";
colorTempDiv.min = 1000;
colorTempDiv.max = 10000;
colorTempDiv.value = ((device["data"]["color_temp"] - 1000) / 4.033) + 1000;
colorTempDiv.onchange = function () { change_color_temperature(device_no, this.value) };
ctTd.appendChild(colorTempDiv);
ctTable.appendChild(ctTd);
var ctTd2 = createElement("td");
ctTd2.innerHTML = "<small>6500K</small>";
ctTable.appendChild(ctTd2);
return ctTable;
}
function createActionLink(device_no, online, state, type) {
var onString = type === "scene" ? "Start" : "On";
if (online === false) {
return '<a href="#" class="borderShadow ui-btn ui-disabled ui-btn-inline ui-icon-power ui-btn-icon-left">Offline</a>';
} else if (state === false) {
return '<a href="#" class="borderShadow ui-btn ui-btn-b ui-btn-inline ui-icon-power ui-btn-icon-left" onclick="toggle(' + device_no + ');">Off</a>';
} else {
return '<a href="#" class="borderShadow ui-btn ui-btn-inline ui-icon-power ui-btn-icon-left" onclick="toggle(' + device_no + ');">' + onString + '</a>';
}
}
function createImg(icon, name, type) {
if (isNullOrEmpty(icon)) {
return "<p>" + type + "</p>";
}
return "<img width=50 src='" + icon + "' alt='" + name + "'>";
}
function createElement(typeName, className) {
var elem = document.createElement(typeName);
if (!isNullOrEmpty(className)) {
elem.className = className;
}
return elem;
}
function isNullOrEmpty(entry) {
return entry == null || entry === '';
}
function logout() {
setCookie("access_token", "", -1);
setCookie("sl_refresh_token", "", -1);
setCookie("sl_expires_in", "", -1);
location.reload();
}
function changeColor(element) {
device_no = element.id.replace("color_", "");
var device = user_info["devices"][device_no];
var t = $("#" + element.id).spectrum("get");
var new_color = {};
if (t === null || t.toName() == "white") {
h = 0;
s = 0;
t = "white";
} else {
hsv = t.toHsv();
h = hsv["h"];
s = hsv["s"];
v = hsv["v"];
}
new_color = { "hue": h, "saturation": s, "brightness": 100 };
if ("brightness" in device["data"]) {
new_color["brightness"] = device["data"]["brightness"] / 10;
}
success = adjust_device(device, "colorSet", "color", new_color);
if ("header" in success && "code" in success["header"] && success["header"]["code"] === "SUCCESS") {
device["data"]["state"] = true;
device["data"]["hue"] = h;
device["data"]["saturation"] = s;
localStorage.devices = JSON.stringify(user_info["devices"]);
$("#color_" + device_no).spectrum("set", t);
add_or_update_switch(device, device_no);
}
}