-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathTelinkOTA.html
366 lines (330 loc) · 11.1 KB
/
TelinkOTA.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
<html class="telFlasherClass">
<head>
<link rel="stylesheet" href="styles.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Telink OTA</title>
</head>
<body>
<script>
//BLE values
var PServ = '00010203-0405-0607-0809-0a0b0c0d1912';
var PChar = '00010203-0405-0607-0809-0a0b0c0d2b12';
var bluetoothDevice, gattServer, Theservice, writeCharacteristic;
//Firmware values
var firmwareArray = "",
startTime = 0,
blockCount = 0;
//Connection values
var connectTrys = 0;
var $ = function(id) { return document.getElementById(id);}
function resetVariables() {
busy = false;
gattServer = null;
Theservice = null;
writeCharacteristic = null;
}
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() {
PServ = $('iPServ').value;
PChar = $('iPChar').value;
var deviceOptions = {
optionalServices: [PServ],
acceptAllDevices: true,
};
const hideUnknown = $('hideUnknown').checked;
const namePrefix = $('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 => {
bluetoothDevice = device;
bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
addLog("Connecting to: " + bluetoothDevice.name);
doConnect();
}).catch(handleError);
}
function doConnect() {
bluetoothDevice.gatt.connect().then(server => {
addClog("Found GATT server");
gattServer = server;
return gattServer.getPrimaryService(PServ);
}).then(service => {
addClog("Found service");
Theservice = service;
return Theservice.getCharacteristic(PChar);
}).then(characteristic => {
addClog("Found write characteristic");
writeCharacteristic = characteristic;
let s = "Connected.";
addClog(s);
addLog(s);
setStatus(s);
}).catch(handleError);
}
function reConnect() {
if (bluetoothDevice != null) bluetoothDevice.gatt.disconnect();
resetVariables();
addLog("Reconnect");
connectTrys = 0;
doConnect();
}
function startDFU() {
addLog("Start DFU");
updateBegin();
}
function sendBLEdata(data) {
addLog(data);
}
function addLog(logTXT) {
var time = new Date().toLocaleTimeString();
var logString = time + ": " + logTXT;
$("log").innerHTML += logString + "<br>";
}
function addClog(logTXT) {
console.log(logTXT);
}
function clearLog() {
$("log").innerHTML = "";
}
function setStatus(status) {
// addClog("Status: " + status);
$("percent").innerHTML = "Status: " + status;
}
function updateFail(err) {
let s = "Update error: " + err;
addClog(s);
addLog(s);
setStatus(s);
}
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 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 getHexCRC(data) {
var tempCRC = decimalToHex(crc16_modbus(hexToBytes(data)));
return tempCRC.substring(2, 4) + tempCRC.substring(0, 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 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() {
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);
}
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;
}
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 sendLastOTA() {
var data = "02ff" + getHexBLockCount(blockCount - 1) + getHexBLockCount(~(blockCount - 1) & 0xffff);
otaCharSend(data).then(function(character) {
let s = "Update done after " + (new Date().getTime() - startTime) / 1000 + " seconds";
addClog(s);
addLog(s);
setStatus(s);
}).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");
});
});
}
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");
});
});
}
</script>
<h1>Telink OTA</big></big> <a style="font-size: 12px" href="https://github.com/pvvx/ATC_MiThermometer">ⓘ</a></h1>
<div class="navbar">
<div class="container nav-container">
<input class="checkbox" type="checkbox" name="" id="">
<div class="hamburger-lines">
<span class="line line1"></span>
<span class="line line2"></span>
<span class="line line3"></span>
</div>
<div class="menu-items">
<li> Live Data </li>
<li><a href="GraphAtc.html">Graph Atc 1</a></li>
<li><a href="GraphAtc1.html">Graph Atc 2</a></li>
<li><a href="GraphAtc2.html">Graph Atc 3</a></li>
<li><a href="DevPoint.html">Dev Point</a></li>
<li><a href="Advertising.html">Advertising</a></li>
<li>Stored data</li>
<li><a href="GraphMemo.html">Memo Graph</a></li>
<li><a href="GraphMemoOriginal.html">LYWSD03MMC Memo Graph </a></li>
<li>Others & Flasher</li>
<li><a href="TelinkMiFlasher.html">Flasher</a></li>
<li><a href="TelinkOTA.html">OTA Flasher</a></li>
</div>
</div>
</div>
<hr>
Services UUID:<br>
<input size="40" type="text" id="iPServ" value="00010203-0405-0607-0809-0a0b0c0d1912" maxlength="36"><br>
Characteristic:<br>
<input size="40" type="text" id="iPChar" value="00010203-0405-0607-0809-0a0b0c0d2b12" maxlength="36"><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" checked><br>
<label for="namePrefix">BLE device name prefix filter(s)</label>
<input type="text" id="namePrefix" value="" placeholder="LYWSD03,ATC"><br><hr>
Please select a .bin file you want to flash to a Telink BLE device.<br>
Select Firmware: <input type="file" accept=".bin" id="file"/><br>
<div id="percent">Status: waiting for you to connect a device</div>
<button type="button" onclick="startDFU();">Start Flashing</button><br><hr>
<button type="button" onclick="clearLog();">Clear Log</button><br>
<div id="log"></div>
</body></html>