-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathBLE_EPaper_OTA.html
More file actions
392 lines (353 loc) · 13.9 KB
/
BLE_EPaper_OTA.html
File metadata and controls
392 lines (353 loc) · 13.9 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Telink BLE E-Paper Flasher</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f8f8f8;
color: #333;
margin: 0;
padding: 0;
text-align: center;
}
.container {
max-width: 600px;
margin: 20px auto;
background-color: #fff;
border-radius: 8px;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #d32f2f;
}
h5 {
color: #d32f2f;
}
button {
background-color: #d32f2f;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #b71c1c;
}
input[type="checkbox"] {
margin-right: 5px;
}
label {
display: inline-block;
margin-bottom: 5px;
color: #666;
}
hr {
border: none;
border-top: 1px solid #ddd;
margin: 20px 0;
}
#percent {
text-align: left;
font-size: 18px;
margin-bottom: 10px;
}
#log {
text-align: left;
font-size: 14px;
padding: 10px;
background-color: #f0f0f0;
border-radius: 5px;
max-height: 5%;
overflow-y: auto;
}
</style>
</head>
<body>
<div class="container">
<h1>BLE E-Paper Flasher</h1>
<p>
Copyright: Aaron Christophel / Atc1441 <a href="https://atcnetz.de">https://ATCnetz.de</a>
</p>
<button onclick="connect();">Connect</button>
<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="NEMR"><br>
<hr>
<h5>CAUTION! this can soft-brick your device, make sure to flash the right firmware!</h5>
<p>Please select a .bin file you want to flash to a Telink BLE device.</p>
<p>Select Firmware: <input type="file" accept=".bin" id="file" onclick="resetFileSelector();" disabled></p>
<hr>
<div id="percent">Status: waiting for you to connect a device</div>
<div id="log">Log:<br></div>
<div id="result"></div>
</div>
<script>
//BLE values
var bluetoothDevice, gattServer, Theservice, writeCharacteristic;
//Firmware values
var firmwareArray = "",
startTime = 0,
blockCount = 0;
//Connection values
var connectTrys = 0;
function resetFileSelector() {
document.getElementById("file").value = '';
};
function resetVariables() {
gattServer = null;
Theservice = null;
writeCharacteristic = null;
document.getElementById('file').setAttribute('disabled', 'disabled');
resetFileSelector();
}
function handleError(error) {
if (error.message.includes("No Services matching")) {
setStatus("The connected device is not supported!<br>Its either not using a Telink Chip or uses a different OTA method");
addLog("The connected device is not supported!<br>Its either not using a Telink Chip or uses a different OTA method");
} else {
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'],
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 => {
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('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;
addLog("Connected");
setStatus("Connected, please select a file now")
document.getElementById('file').removeAttribute('disabled');
}).catch(handleError);
}
function reConnect() {
if (bluetoothDevice != null) bluetoothDevice.gatt.disconnect();
resetVariables();
addLog("Reconnect");
connectTrys = 0;
doConnect();
}
function startDFU() {
addLog("Start DFU");
updateBegin();
}
function addLog(logTXT) {
var today = new Date();
var time = ("0" + today.getHours()).slice(-2) + ":" + ("0" + today.getMinutes()).slice(-2) + ":" + ("0" + today.getSeconds()).slice(-2) + " : ";
document.getElementById("log").innerHTML += time + logTXT + '<br>';
console.log(time + logTXT);
while ((document.getElementById("log").innerHTML.match(/<br>/g) || []).length > 8) {
var logs_br_position = document.getElementById("log").innerHTML.search("<br>");
document.getElementById("log").innerHTML = document.getElementById("log").innerHTML.substring(logs_br_position + 4);
}
}
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 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 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);
}, "");
}
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]);
if (bluetoothDevice != null) {
setTimeout(function () {
startDFU();
}, 500);
}
}
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,<br>Duration: " + (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");
}).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");
});
});
}
</script>
</body>
</html>