forked from atc1441/atc1441.github.io
-
Notifications
You must be signed in to change notification settings - Fork 1
/
TelinkFlasherTasmota.html
886 lines (818 loc) · 38.2 KB
/
TelinkFlasherTasmota.html
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
<!-- Copyright: Aaron Christophel / Atc1441 https://atcnetz.de -->
<html class="telFlasherClass"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Telink Flasher</title>
<script type="text/javascript" src="./core.js"></script>
<style>
.hidden {
display: none;
}
.tasmota {
border: 2px solid green;
padding: 10px;
margin: 10px;
}
.tasmota2 {
border: 2px solid red;
padding: 10px;
margin: 10px;
}
</style>
</head>
<body>
<script>
//BLE values
var bluetoothDevice, gattServer, Theservice, writeCharacteristic;
var ServiceMain, writeCharacteristicSpeed, nitifiyCharTemp, time_char, enc_main, enc_10, enc_19;
//Firmware values
var firmwareArray = "",
startTime = 0,
blockCount = 0;
//Connection values
var state = 0,
connectTrys = 0;
//Custom firmware
var customEnabled;
var settingsCharacteristics;
//Mi values
var miEnabled = false,
miConnected = false,
mode_activation;
//Login values
var mi_random_key, mi_random_key_recv, mi_device_info_recv, mi_device_info_send, device_known_id, expected_device_infos, is_logged_in = false;
//Activation values
var keypair, is_activated, own_public_key, device_public_key, shared_key, derived_key, mi_write_did;
var device_new_id = "00626c742e332e31323976" + makeRandomID(6) + "415443";
// Tasmota variables
var mac = ''; // mac against which we are making the request for a key
var macstr = ''; // mac against which we are making the request for a key
var keyscallback = ''; // callback address for this Tasmota.
var isTasmotaCall = false;
function resetVariables() {
busy = false;
gattServer = null;
Theservice = null;
writeCharacteristic = null;
miConnected = false;
is_logged_in = false;
document.getElementById("known_id").value = '';
document.getElementById("mi_token").value = '';
document.getElementById("mi_bind_key").value = '';
}
function handleError(error) {
addLog(error);
resetVariables();
if (connectTrys < 5) {
connectTrys++;
addLog("Reconnect " + connectTrys + " from " + 5);
doConnect();
} else {
addLog("Something went wrong, to many reconnect's");
connectTrys = 0;
}
}
function onDisconnected() {
addLog('Disconnected.');
}
function connect() {
var deviceOptions = {
optionalServices: ['00010203-0405-0607-0809-0a0b0c0d1912', 'ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6', 0xfe95, 0x1f10],
acceptAllDevices: true,
};
const hideUnknown = document.getElementById('hideUnknown').checked;
const namePrefix = document.getElementById('namePrefix').value;
if (hideUnknown) {
deviceOptions.acceptAllDevices = false;
deviceOptions.filters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
.split("")
.map((x) => ({ namePrefix: x }));
}
if (namePrefix) {
deviceOptions.acceptAllDevices = false;
deviceOptions.filters = namePrefix.split(",")
.map((x) => ({ namePrefix: x }));
}
console.log(deviceOptions)
if (bluetoothDevice != null) bluetoothDevice.gatt.disconnect();
resetVariables();
addLog("Searching for devices");
connectTrys = 0;
navigator.bluetooth.requestDevice(deviceOptions).then(device => {
console.log(device);
bluetoothDevice = device;
bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
catchAdvertisement(device);
//addLog("Connecting to: " + bluetoothDevice.name);
//doConnect(); - done in catchAdvertisement only if we can't catch adverts
}).catch(handleError);
}
function catchAdvertisement(device) {
const abortController = new AbortController();
device.addEventListener('advertisementreceived', (event) => {
console.log('Received advertisement from "' + device.name + '"...');
event.serviceData.forEach((valueDataView) => {
const buffer = new Uint8Array(valueDataView.buffer);
console.log(buffer, device, event);
if(device.name=='LYWSD03MMC'){
console.log('LYWSD03MMC MAC:',buffer[10].toString(16),buffer[9].toString(16),buffer[8].toString(16),buffer[7].toString(16),buffer[6].toString(16),buffer[5].toString(16));
document.getElementById("MAC").innerHTML = 'LYWSD03MMC MAC: ' + buffer[10].toString(16) + buffer[9].toString(16) + buffer[8].toString(16) + buffer[7].toString(16) + buffer[6].toString(16) + buffer[5].toString(16);
}
if(device.name.startsWith('ATC')){
console.log('ATC MAC:',buffer[0].toString(16),buffer[1].toString(16),buffer[2].toString(16),buffer[3].toString(16),buffer[4].toString(16),buffer[5].toString(16));
document.getElementById("MAC").innerHTML = 'ATC MAC: ' + buffer[0].toString(16) + buffer[1].toString(16) + buffer[2].toString(16) + buffer[3].toString(16) + buffer[4].toString(16) + buffer[5].toString(16);
}
else {
console.log('only LYWSD03MMC/ATC supported');
}
})
abortController.abort();
}, { once: true });
if (device.watchAdvertisements){
console.log('Watching advertisements from "' + device.name + '"...');
device.watchAdvertisements({ signal: abortController.signal })
.catch(error => {
console.log('Argh! ' + error);
});
} else {
doConnect();
}
}
function miAction() {
gattServer.getPrimaryService('ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6')
.then(service => {
addClog("Found Main service");
ServiceMain = service;
return ServiceMain.getCharacteristic('ebe0ccd8-7a0a-4b0c-8a1a-6ff2997da3a6');
}).then(characteristic => {
addClog("Found Write characteristic Speed");
writeCharacteristicSpeed = characteristic;
return ServiceMain.getCharacteristic('ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6');
}).then(characteristic => {
addClog('Found Temp characteristic');
nitifiyCharTemp = characteristic;
return nitifiyCharTemp.startNotifications().then(() => {
nitifiyCharTemp.addEventListener('characteristicvaluechanged', event => {
var value = event.target.value;
var sign = value.getUint8(1) & (1 << 7);
var temp = ((value.getUint8(1) & 0x7F) << 8 | value.getUint8(0));
if(sign) temp = temp-32767;
temp = temp/100;
var hum = value.getUint8(2);
var tempTempString = "Temp/Humi: " + temp + "°C / " + hum + "%";
document.getElementById("tempHumiData").innerHTML = tempTempString;
addClog(tempTempString);
});
miAuthorization()
});
}).catch(handleError);
}
function customAction() {
gattServer.getPrimaryService('00001f10-0000-1000-8000-00805f9b34fb')
.then(service => {
addClog("Found custom Main service");
ServiceMain = service;
return ServiceMain.getCharacteristic('00001f1f-0000-1000-8000-00805f9b34fb');
}).then(characteristic => {
addClog("Found custom write characteristic");
settingsCharacteristics = characteristic;
}).catch(handleError);
}
function miAuthorization() {
gattServer.getPrimaryService(0xfe95)
.then(service => {
addClog("Found Main service");
enc_main = service;
return enc_main.getCharacteristic(0x0010);
}).then(characteristic => {
addClog("Found enc_10 char");
enc_10 = characteristic;
return enc_main.getCharacteristic(0x0019);
}).then(characteristic => {
addClog('Found enc_19 char');
enc_19 = characteristic;
miConnected = true;
return enc_10.startNotifications().then(() => {
enc_10.addEventListener('characteristicvaluechanged', event => {
var value = bytesToHex(event.target.value.buffer);
addClog("Enc_10: " + value);
if (value == "12000000") {
addLog("Activation Failed!");
} else if (value == "11000000") {
addLog("Activation successfull");
sendLogin();
}
if (value == "23000000") {
addLog("Login Failed!");
} else if (value == "21000000") {
is_logged_in = true;
addLog("Login successfull");
}
});
}).then(characteristic => {
return enc_19.startNotifications().then(() => {
enc_19.addEventListener('characteristicvaluechanged', event => {
var value = bytesToHex(event.target.value.buffer);
addClog("Enc_19: " + value);
if (mode_activation == 1) {
if (value == "000000000100") {
is_activated = false;
mainCharSend("00000101", enc_19);
} else if (value == "000000000200") {
is_activated = true;
mainCharSend("00000101", enc_19);
} else if ((is_activated == true) && (state == 0) && value.substring(0, 4) == "0100") {
device_known_id = value.substring(4);
} else if ((is_activated == true) && (state == 0) && value.substring(0, 4) == "0200") {
device_known_id += value.substring(4);
device_new_id = device_known_id.substring(8);
document.getElementById("known_id").value = hex2ascii(device_known_id.substring(10));
mainCharSend("00000100", enc_19).then(function(character) {
mainCharSend("15000000", enc_10).then(function(character) {
mainCharSend("000000030400", enc_19);
state = 1;
}).catch(function(err) {
updateFail(err);
});
}).catch(function(err) {
updateFail(err);
});
} else if (value == "010001000000") mainCharSend("00000100", enc_19).then(function(character) {
mainCharSend("15000000", enc_10).then(function(character) {
mainCharSend("000000030400", enc_19);
state = 1;
}).catch(function(err) {
updateFail(err);
});
}).catch(function(err) {
updateFail(err);
});
else if ((state == 1) && (value == "00000101")) {
state = 2;
mainCharSend("0100" + own_public_key.substring((36 * 0) + 2, (36 * 0) + 36 + 2), enc_19).then(function(character) {
mainCharSend("0200" + own_public_key.substring((36 * 1) + 2, (36 * 1) + 36 + 2), enc_19).then(function(character) {
mainCharSend("0300" + own_public_key.substring((36 * 2) + 2, (36 * 2) + 36 + 2), enc_19).then(function(character) {
mainCharSend("0400" + own_public_key.substring((36 * 3) + 2, (36 * 3) + 36 + 2), enc_19);
}).catch(function(err) {
updateFail(err);
});
}).catch(function(err) {
updateFail(err);
});
}).catch(function(err) {
updateFail(err);
});
} else if (value == "000000030400") mainCharSend("00000101", enc_19);
else if ((state == 2) && value.substring(0, 4) == "0100") {
device_public_key = "04" + value.substring(4);
} else if ((state == 2) && value.substring(0, 4) == "0200") {
device_public_key += value.substring(4);
} else if ((state == 2) && value.substring(0, 4) == "0300") {
device_public_key += value.substring(4);
} else if ((state == 2) && value.substring(0, 4) == "0400") {
device_public_key += value.substring(4);
mainCharSend("00000100", enc_19).then(function(character) {
makeSharedKey();
}).catch(function(err) {
updateFail(err);
});
} else if ((state == 2) && (value == "00000101")) {
state = 3;
mainCharSend("0100" + mi_write_did.substring(36 * 0, (36 * 0) + 36), enc_19).then(function(character) {
mainCharSend("0200" + mi_write_did.substring(36 * 1, (36 * 1) + 36), enc_19);
}).catch(function(err) {
updateFail(err);
});
} else if ((state == 3) && (value == "00000100")) {
state = 0;
mainCharSend("13000000", enc_10);
} else if (value == "000001050100") {
addLog("Received Timeout from device");
} else if (value == "12000000") {
addLog("Register Failed!");
} else if (value == "11000000") {
addLog("Register successfull");
}
} else { //Mode Login
if ((state == 0) && (value == "00000101")) {
state = 1;
mainCharSend("0100" + mi_random_key, enc_19);
} else if ((state == 1) && (value == "0000000d0100")) {
state = 2;
mainCharSend("00000101", enc_19);
} else if ((state == 2) && value.substring(0, 4) == "0100") {
state = 3;
mi_random_key_recv = value.substring(4);
do_login_generate();
} else if ((state == 3) && (value == "0000000c0200")) {
state = 4;
mainCharSend("00000101", enc_19);
} else if ((state == 4) && value.substring(0, 4) == "0100") {
state = 5;
mi_device_info_recv = value.substring(4);
} else if ((state == 5) && value.substring(0, 4) == "0200") {
state = 6;
mi_device_info_recv += value.substring(4);
if (expected_device_infos == mi_device_info_recv)
addLog("Received device infos are correct");
else
addLog("Received device infos are not correct");
mainCharSend("00000100", enc_19).then(function(character) {
mainCharSend("0000000a0200", enc_19);
})
} else if ((state == 6) && (value == "00000101")) {
state = 7;
mainCharSend("0100" + mi_device_info_send.substring(36 * 0, (36 * 0) + 36), enc_19).then(function(character) {
mainCharSend("0200" + mi_device_info_send.substring(36 * 1, (36 * 1) + 36), enc_19);
}).catch(function(err) {
updateFail(err);
});
}
}
});
addLog("Connected");
setStatus("Connected, you can now Do the Activation to either get the Token or flash a new Firmware")
document.querySelector("#waitconnect").classList.add('hidden');
document.querySelector("#tasactivation").classList.remove('hidden');
});
});
}).catch(handleError);
}
function doConnect() {
bluetoothDevice.gatt.connect().then(server => {
addClog("Found GATT server");
gattServer = server;
return gattServer.getPrimaryService('00010203-0405-0607-0809-0a0b0c0d1912');
}).then(service => {
addClog("Found service");
Theservice = service;
return Theservice.getCharacteristic('00010203-0405-0607-0809-0a0b0c0d2b12');
}).then(characteristic => {
addClog("Found write characteristic");
writeCharacteristic = characteristic;
detectMi();
}).catch(handleError);
}
function detectMi() {
gattServer.getPrimaryServices().then(services => {
miEnabled = false;
customEnabled = false;
for (var i = 0; i < services.length; i++) {
console.log("Services: " + services[i].uuid);
if (services[i].uuid == "ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6") miEnabled = true;
if (services[i].uuid == "00001f10-0000-1000-8000-00805f9b34fb") customEnabled = true;
}
if (miEnabled) {
addLog("Detected Mi Thermometer");
setStatus("Detected Mi Thermometer");
miAction();
} else if (customEnabled) {
addLog("Detected custom Firmware");
setStatus("Detected custom Firmware");
customAction();
} else {
addLog("Connected");
setStatus("Connected")
}
}).catch(handleError);
}
function reConnect() {
if (bluetoothDevice != null) bluetoothDevice.gatt.disconnect();
resetVariables();
addLog("Reconnect");
connectTrys = 0;
doConnect();
}
function startDFU() {
addLog("Start DFU");
if ((miConnected==true) && (is_logged_in==false)){
addLog("Please do the Activation first");
return;
}
document.querySelector("#updating").classList.remove('hidden');
updateBegin();
}
function sendBLEdata(data) {
addLog(data);
}
function send10(data) {
mainCharSend(data, enc_10);
}
function send19(data) {
mainCharSend(data, enc_19);
}
function sendRegister() {
if (miConnected == false) {
addLog("Not connected");
return;
}
addLog("Activating now, please wait...");
state = 0;
mode_activation = 1;
doGenerate();
mainCharSend("a2000000", enc_10);
}
function sendLogin() {
mi_random_key = bytesToHex(window.crypto.getRandomValues(new Uint8Array(16)));
state = 0;
mode_activation = 0;
mainCharSend("24000000", enc_10).then(function(character) {
mainCharSend("0000000b0100", enc_19);
}).catch(function(err) {
updateFail(err);
});
}
function addLog(logTXT) {
var time = new Date().toLocaleTimeString("de-DE");
var logString = time + ": " + logTXT;
document.getElementById("log").innerHTML += logString + "<br>";
}
function addClog(logTXT) {
console.log(logTXT);
}
function clearLog() {
document.getElementById("log").innerHTML = "Log:<br>";
}
function setStatus(status) {
addClog("Status: " + status);
document.getElementById("percent").innerHTML = "Status: " + status;
}
function updateFail(err) {
addLog("Update error: " + err);
setStatus("Update error: " + err);
}
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
while (hex.length < 4) {
hex = "0" + hex;
}
return hex;
}
function hexToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return new Uint8Array(bytes);
}
function bytesToHex(data) {
return new Uint8Array(data).reduce(function(memo, i) {
return memo + ("0" + i.toString(16)).slice(-2);
}, "");
}
function makeRandomID(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return bytesToHex(new TextEncoder("utf-8").encode(result));
}
function crc16_modbus(buffer) {
var crc = 0xFFFF;
var odd;
for (var i = 0; i < buffer.length; i++) {
crc = crc ^ buffer[i];
for (var j = 0; j < 8; j++) {
odd = crc & 0x0001;
crc = crc >> 1;
if (odd) {
crc = crc ^ 0xA001;
}
}
}
return crc;
};
function hex2ascii(hexx) {
var hex = hexx.toString();
var str = '';
for (var i = 0;
(i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
mac = urlParams.get('mac');
keyscallback = urlParams.get('cb');
if (mac){
isTasmotaCall = true;
macstr = mac.slice(0,2)+':'+mac.slice(2,4)+':'+mac.slice(4,6)+':'+mac.slice(6,8)+':'+mac.slice(8,10)+':'+mac.slice(10,12);
document.querySelector("#mac").innerHTML = macstr;
document.querySelector("#macstr").innerHTML = macstr;
document.querySelector("#cb").innerHTML = keyscallback;
document.title = 'MI Device '+macstr;
document.querySelector("#tasmota").classList.remove('hidden');
//document.querySelector("#tasmota2").classList.remove('hidden');
//document.querySelector("#nontasmota").classList.add('hidden');
} else {
document.querySelector("#tasmota").classList.add('hidden');
document.querySelector("#tasmota2").classList.add('hidden');
document.querySelector("#nontasmota").classList.remove('hidden');
}
//<p id="tasrequest">Tas Request mac:<span id="mac"></span> callback:<span id="cb"></span></p>
document.querySelector("#file").addEventListener("change", function() {
var reader = new FileReader();
reader.onload = function() {
firmwareArray = bytesToHex(this.result);
if(firmwareArray.substring(16,24)!="4b4e4c54"){
alert("Select file is no telink firmware .bin");
addLog("Select file is no telink firmware .bin");
blockCount = 0;
firmwareArray = "";
return;
}
addLog("File was selected, size: " + firmwareArray.length / 2 + " bytes");
if (firmwareArray.length % 32 !== 0) { // pad last block to 16bytes
var padHex = "ffffffffffffffffffffffffffffffff";
firmwareArray += padHex.substr(0, 32 - firmwareArray.length % 32);
}
blockCount = firmwareArray.length / 32;
addLog("Count: " + blockCount);
document.querySelector("#waitstartflashing").classList.add('hidden');
document.querySelector("#startflashing").classList.remove('hidden');
}
if (this.files[0] != null)
reader.readAsArrayBuffer(this.files[0]);
else
addLog("No file selected");
}, false);
}
function updateBegin() {
if (blockCount <= 0) {
addLog("No file selected aborting");
return;
}
if (miEnabled) mainCharSend("1e0000", writeCharacteristicSpeed); // this makes the upload faster
setTimeout(function() {
otaCharSend("00ff").then(function(character) {
otaCharSend("01ff").then(function(character) {
setTimeout(function() {
startTime = new Date().getTime();
sendOTAblock(0);
}, 300);
}).catch(function(err) {
updateFail(err);
});
}).catch(function(err) {
updateFail(err);
});
}, 500);
}
function sendOTAblock(blockNr) {
if (blockNr >= blockCount) {
sendLastOTA();
return;
}
setStatus("Sending block nr: " + blockNr + " from " + blockCount + ", " + Math.floor(blockNr / (blockCount * 1.0) * 100) + "% done, time since start " + (new Date().getTime() - startTime) / 1000.0 + "s");
var blockNrString = getHexBLockCount(blockNr);
var blockString = blockNrString + firmwareArray.substring(blockNr * 32, blockNr * 32 + 32);
var blockCRC = getHexCRC(blockString);
otaCharSend(blockString + blockCRC).then(function(character) {
setTimeout(function() {
if ((blockNr + 1) % 8 == 0) {
writeCharacteristic.readValue().then(function(result) {
addClog('reading OTA');
sendOTAblock(blockNr + 1);
}).catch(function(err) {
updateFail(err);
});
} else {
sendOTAblock(blockNr + 1);
}
}, 0);
}).catch(function(err) {
updateFail(err);
});
}
function getHexBLockCount(count) {
var tempHEX = decimalToHex(count);
return tempHEX.substring(2, 4) + tempHEX.substring(0, 2);
}
function getHexCRC(data) {
var tempCRC = decimalToHex(crc16_modbus(hexToBytes(data)));
return tempCRC.substring(2, 4) + tempCRC.substring(0, 2);
}
function sendLastOTA() {
var data = "02ff" + getHexBLockCount(blockCount - 1) + getHexBLockCount(~(blockCount - 1) & 0xffff);
otaCharSend(data).then(function(character) {
addLog("Update done after " + (new Date().getTime() - startTime) / 1000 + " seconds");
setStatus("Update done after " + (new Date().getTime() - startTime) / 1000 + " seconds");
document.querySelector("#updating").classList.add('hidden');
document.querySelector("#updatedonetxt").classList.remove('hidden');
document.querySelector("#nontasmota").classList.remove('hidden');
}).catch(function(err) {
updateFail(err);
});
}
var otaCharSend = function(data) {
return new Promise(function(resolve, reject) {
addClog("OTA: " + data);
writeCharacteristic.writeValue(hexToBytes(data)).then(function(character) {
resolve("ok");
}).catch(function(err) {
reject("some error while sending char data");
});
});
}
function sendCustomSetting(data){
mainCharSend(data,settingsCharacteristics).then(function() {
addLog("Settings " + data + " was send successful");
}).catch(function(err) {
addLog("Error on sending setting " + data);
});
}
var mainCharSend = function(data, characteristic) {
return new Promise(function(resolve, reject) {
addClog("Send: " + data);
characteristic.writeValue(hexToBytes(data)).then(function(character) {
resolve("ok");
}).catch(function(err) {
reject("some error while sending char data");
});
});
}
function doGenerate() {
window.crypto.subtle.generateKey({
name: 'ECDH',
namedCurve: 'P-256'
}, false, ['deriveKey', 'deriveBits'])
.then(own_key => {
keypair = own_key
return window.crypto.subtle.exportKey('raw', own_key.publicKey);
})
.then(ownPublicKeyExported => {
own_public_key = bytesToHex(ownPublicKeyExported);
})
.catch(err => {
addLog(err);
});
}
function makeSharedKey() {
window.crypto.subtle.importKey('raw', hexToBytes(device_public_key), {
name: 'ECDH',
namedCurve: 'P-256'
}, true, [])
.then(device_key_imported => {
return window.crypto.subtle.deriveBits({
name: 'ECDH',
namedCurve: 'P-256',
public: device_key_imported
}, keypair.privateKey, 256)
})
.then(sharedSecret => {
shared_key = bytesToHex(sharedSecret);
deriveTheKey();
})
.catch(err => {
addLog(err)
})
}
function deriveTheKey() {
var derived_key = sjcl.codec.hex.fromBits(sjcl.misc.hkdf(sjcl.codec.hex.toBits(shared_key), 8 * 64, null, "mible-setup-info", sjcl.hash["sha256"]));
document.getElementById("mi_token").value = derived_key.substring(0, 24);
let bindkey = derived_key.substring(24, 56);
document.getElementById("mi_bind_key").value = bindkey;
var mi_bind_A = derived_key.substring(56, 88);
mi_write_did = sjcl.codec.hex.fromBits(sjcl.mode.ccm.encrypt(new sjcl.cipher.aes(sjcl.codec.hex.toBits(mi_bind_A)), sjcl.codec.hex.toBits(device_new_id), sjcl.codec.hex.toBits("101112131415161718191A1B"), sjcl.codec.hex.toBits("6465764944"), 32));
mainCharSend("000000000200", enc_19);
if (isTasmotaCall){
document.querySelector("#tasmotaapplylink").href = keyscallback +'?mac='+mac.toUpperCase()+'&key='+bindkey.toUpperCase();
document.querySelector("#waitactivate").classList.add('hidden');
document.querySelector("#tasmotaapply").classList.remove('hidden');
document.querySelector("#taskey").innerHTML = "MI32Keys "+mac.toUpperCase()+"="+bindkey.toUpperCase();
}
}
function do_login_generate() {
var salt = hexToBytes(mi_random_key + mi_random_key_recv);
var salt1 = hexToBytes(mi_random_key_recv + mi_random_key);
var derived_key = sjcl.codec.hex.fromBits(sjcl.misc.hkdf(sjcl.codec.hex.toBits(document.getElementById("mi_token").value), 8 * 64, sjcl.codec.hex.toBits(bytesToHex(salt)), "mible-login-info", sjcl.hash["sha256"]));
expected_device_infos = sjcl.codec.hex.fromBits(new sjcl.misc.hmac(sjcl.codec.hex.toBits(derived_key.substring(0, 32))).mac(sjcl.codec.hex.toBits(bytesToHex(salt1))));
mi_device_info_send = sjcl.codec.hex.fromBits(new sjcl.misc.hmac(sjcl.codec.hex.toBits(derived_key.substring(32, 64))).mac(sjcl.codec.hex.toBits(bytesToHex(salt))));
mainCharSend("00000100", enc_19);
}
</script>
<big><big>Telink Flasher for Mi Thermostat</big></big><br>
Copyright: Aaron Christophel / Atc1441 <a href="https://atcnetz.de">https://ATCnetz.de</a><br/>
<a href="https://atc1441.github.io/TelinkFlasher.html">Original TeleLink Flasher - use original atc firmware configuration and for flashing</a><br/>
<a href="https://atc1441.github.io/Temp_universal_mi_activate.html"><b>Universal</b> TeleLink Flasher - use to get keys for other MI sensors (e.g. door sensor)</a><br/>
<a href="https://pvvx.github.io/ATC_MiThermometer/TelinkMiFlasher.html">pvvx TeleLink Flasher - use for pvvx firmware configuration and for flashing</a><br/>
Adapted by Simon Hailes / btsimonh <a href="https://github.com/btsimonh/atc1441.github.io">(github)</a><br/>
<a href="https://btsimonh.github.io/atc1441.github.io/TelinkFlasherTasmota.html">Raw page (without Tamsmota query string - e.g. for ATC firmware options)</a><br/>
<div id="tasmota" class="hidden tasmota">
<h2>Be sure to select the device with the requested MAC address:<span id=macstr></span></h2><br/>
Tas Request mac:<span id="mac"></span> callback:<span id="cb"></span><br/>
<h3>Instructions to get a key for original MI firmware:</h3>
<p>1/ Click connect, and select the device with the matching MAC address<br/>
Notes:<br/>
Currently we can't read the MAC address here to confirm you selected the right device.<br/>
If you have only one device, Chrome may not show you the MAC address.<br/>
You may need to wait for a minute or two for all devices to appear.<br/>
Every time you get a key for a device, the key changes, so you would need new startup commands in Tasmota</p>
<button type="button" onclick="connect();">Connect</button>
<p>2/ Wait for 'Do Activation' to appear, then click it.<br/>
<span id="waitconnect">Please wait</span></p>
<button id="tasactivation" class="hidden" type="button" onclick="sendRegister();">Do Activation</button>
<p>3/ Wait for a link to appear here:<br/>
<span id="waitactivate">Please wait</span>
<span id="tasmotaapply" class="hidden"><a id="tasmotaapplylink" target="_blank">Click to directly apply this key to Tasmota via a callback url.</a><br/>
Cmnd for boot would be:<br/><h3 id="taskey"></h3>
</span></p>
<p>4/ Note the presented Tasmota command.<br/>
This should be added to a rule or other boot mechanism to add the key at every Tasmota restart<br/>
You can combine setting of keys using 'MI32Keys mac=key mac2=key2 mac3=key3'<br/>
You can list all keys present in Tasmota to log/MQTT using the cmnd 'MI32Keys' on it's own</p>
<p>5/ Close this tab</p>
<br/>
</div>
<div id="tasmota2" class="hidden tasmota2">
<h2>Be sure to select the device with the requested MAC address:<span id=macstr></span></h2><br/>
<h3>Instructions to install custom firmware:</h3>
<p>1/ Click connect, and select the device with the matching MAC address<br/>
Notes:<br/>
Currently we can't read the MAC address here to confirm you selected the right device.<br/>
If you have only one device, Chrome may not show you the MAC address.<br/>
You may need to wait for a minute or two for all devices to appear.</p>
<button type="button" onclick="connect();">Connect</button>
<p>2/ Click on Choose file, and select your custom firmware file, e.g. "ATC_Thermometer.bin"<br/>
Select Firmware: <input type="file" accept=".bin" id="file"/>
</p>
<p>3/ Click 'Start Flashing'</p>
<span id="waitstartflashing">Please wait</span></p>
<span id="updatedonetxt" class="hidden">Flashing Complete</span></p>
<span id="updating" class="hidden">Flashing .....</span></p>
<button id="startflashing" class="hidden" type="button" onclick="startDFU();">Start Flashing</button>
<p>4/ Configure the custom firmware<br/>
Reconnect?<br/>
Use the features below to configure the new firmware.
</p>
</div>
<div id="nontasmota">
<h2>Note: this may be out of date - you are better to visit the links above</h2><br/>
<a href="https://youtu.be/NXKzFG61lNs">Video Manual</a> <a href="https://github.com/atc1441/ATC_MiThermometer">Custom firmware repo</a><br><br>
<button type="button" onclick="connect();">Connect</button>
<button type="button" onclick="reConnect();">Reconnect</button><br>
<label for="hideUnknown">Hide unknown</label>
<input type="checkbox" id="hideUnknown"><br>
<label for="namePrefix">BLE device name prefix filter(s)</label>
<input type="text" id="namePrefix" value="" placeholder="LYWSD03,ATC"><br>
<button type="button" onclick="sendRegister();">Do Activation</button>
<button type="button" onclick="startDFU();">Start Flashing</button>
<button type="button" onclick="clearLog();">Clear Log</button><br><br>
Please select a .bin file you want to flash to a Telink BLE device.<br><br>
Select Firmware: <input type="file" accept=".bin" id="file"/><br>
<div id="percent">Status: waiting for you to connect a device</div><hr>
<div id="tempHumiData">Temp/Humi: waiting for data, this will not change on devices with custom firmware, only on stock firmware</div><hr>
<div id="MAC">#enable-experimental-web-platform-features may be needed to read MAC</div><hr>
Device known id:<br>
<input size="40" type="text" id="known_id" value=""><br>
Mi Token:<br>
<input size="40" type="text" id="mi_token" value=""><br>
Mi Bind Key:<br>
<input size="40" type="text" id="mi_bind_key" value=""><br>
<br>
When doing an activation here the device is needed to be activated in the Mi app again when wanted to use there.
<hr>
Send settings to custom firmware:<br>
<input type="text" id="cmdTXT" value="">
<button type="button" onclick="sendCustomSetting(document.getElementById("cmdTXT").value,settingsCharacteristics);">Send</button>
<br><br>
Smiley:
<button type="button" onclick="sendCustomSetting("A0");">Off</button>
<button type="button" onclick="sendCustomSetting("A1");">Happy</button>
<button type="button" onclick="sendCustomSetting("A2");">Sad</button>
<button type="button" onclick="sendCustomSetting("AB");">Blinking</button>
<button type="button" onclick="sendCustomSetting("A3");">Comfort Indicator</button>
<br><br>
Advertising Type:
<button type="button" onclick="sendCustomSetting("AE");">Custom</button>
<button type="button" onclick="sendCustomSetting("AF");">Mi Like</button>
<br><br>
Sensor display:
<button type="button" onclick="sendCustomSetting("CC");">In °C</button>
<button type="button" onclick="sendCustomSetting("FF");">In °F</button>
<br><br>
Show battery in LCD:
<button type="button" onclick="sendCustomSetting("B1");">Enabled</button>
<button type="button" onclick="sendCustomSetting("B0");">Disabled</button>
<br><br>
Advertising interval:
<button type="button" onclick="sendCustomSetting("FE01");">10 Seconds</button>
<button type="button" onclick="sendCustomSetting("FE06");">1 Minute</button>
<button type="button" onclick="sendCustomSetting("FE1E");">5 Minutes</button>
<button type="button" onclick="sendCustomSetting("FE3C");">10 Minutes</button>
<br><br>
Sensor offset:
<button type="button" onclick="sendCustomSetting("FA00");">Temp 0°C offset</button>
<button type="button" onclick="sendCustomSetting("FB00");">Humi 0% offset</button><br>
To set a precise offset use the text input field with FA+offset for Temp and FB+offset for Humiditiy convert an int8 to hex.
<br><br>
Sensor instant Advertising:
<button type="button" onclick="sendCustomSetting("FC05");">Temp 0,5°C instant alarm</button>
<button type="button" onclick="sendCustomSetting("FD05");">Humi 5% instant alarm</button><br>
To set other values use the text input with FC+temp alarm or FD+humi alarm with uint8_t values.
This can be used to get instant advertising if the sensor data changes to fast. Temp divided by 10
<br>
<hr>
</div>
<div id="log">Log:<br></div>
<div id="result"></div>
</body></html>