-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathindex.ts
More file actions
564 lines (493 loc) · 17.5 KB
/
index.ts
File metadata and controls
564 lines (493 loc) · 17.5 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
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
const baudrates = document.getElementById("baudrates") as HTMLSelectElement;
const consoleBaudrates = document.getElementById("consoleBaudrates") as HTMLSelectElement;
const reconnectDelay = document.getElementById("reconnectDelay") as HTMLInputElement;
const maxRetriesInput = document.getElementById("maxRetries") as HTMLInputElement;
const connectButton = document.getElementById("connectButton") as HTMLButtonElement;
const traceButton = document.getElementById("copyTraceButton") as HTMLButtonElement;
const disconnectButton = document.getElementById("disconnectButton") as HTMLButtonElement;
const resetButton = document.getElementById("resetButton") as HTMLButtonElement;
const consoleStartButton = document.getElementById("consoleStartButton") as HTMLButtonElement;
const consoleStopButton = document.getElementById("consoleStopButton") as HTMLButtonElement;
const eraseButton = document.getElementById("eraseButton") as HTMLButtonElement;
const addFileButton = document.getElementById("addFile") as HTMLButtonElement;
const programButton = document.getElementById("programButton");
const filesDiv = document.getElementById("files");
const terminal = document.getElementById("terminal");
const programDiv = document.getElementById("program");
const consoleDiv = document.getElementById("console");
const lblBaudrate = document.getElementById("lblBaudrate");
const lblConsoleBaudrate = document.getElementById("lblConsoleBaudrate");
const lblConsoleFor = document.getElementById("lblConsoleFor");
const lblConnTo = document.getElementById("lblConnTo");
const table = document.getElementById("fileTable") as HTMLTableElement;
const alertDiv = document.getElementById("alertDiv");
const flashMode = document.getElementById("flashMode") as HTMLSelectElement;
const flashFreq = document.getElementById("flashFreq") as HTMLSelectElement;
const flashSize = document.getElementById("flashSize") as HTMLSelectElement;
const lblFlashMode = document.getElementById("lblFlashMode");
const lblFlashFreq = document.getElementById("lblFlashFreq");
const lblFlashSize = document.getElementById("lblFlashSize");
const debugLogging = document.getElementById("debugLogging") as HTMLInputElement;
// This is a frontend example of Esptool-JS using local bundle file
// To optimize use a CDN hosted version like
// https://unpkg.com/esptool-js@0.5.0/bundle.js
import {
ESPLoader,
FlashOptions,
FlashModeValues,
FlashFreqValues,
FlashSizeValues,
LoaderOptions,
Transport,
} from "../../../lib";
import { serial } from "web-serial-polyfill";
const serialLib = !navigator.serial && navigator.usb ? serial : navigator.serial;
declare let Terminal; // Terminal is imported in HTML script
declare let CryptoJS; // CryptoJS is imported in HTML script
const term = new Terminal({ cols: 120, rows: 40 });
term.open(terminal);
let device = null;
let deviceInfo = null;
let transport: Transport;
let chip: string = null;
let esploader: ESPLoader;
disconnectButton.style.display = "none";
traceButton.style.display = "none";
eraseButton.style.display = "none";
consoleStopButton.style.display = "none";
resetButton.style.display = "none";
filesDiv.style.display = "none";
flashMode.style.display = "none";
flashFreq.style.display = "none";
flashSize.style.display = "none";
lblFlashMode.style.display = "none";
lblFlashFreq.style.display = "none";
lblFlashSize.style.display = "none";
/**
* The built in Event object.
* @external Event
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Event}
*/
/**
* File reader handler to read given local file.
* @param {Event} evt File Select event
*/
function handleFileSelect(evt) {
const file = evt.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev: ProgressEvent<FileReader>) => {
if (ev.target.result instanceof ArrayBuffer) {
evt.target.data = new Uint8Array(ev.target.result);
} else {
evt.target.data = ev.target.result;
}
};
reader.readAsArrayBuffer(file);
}
const espLoaderTerminal = {
clean() {
term.clear();
},
writeLine(data) {
term.writeln(data);
},
write(data) {
term.write(data);
},
};
/**
* Populate flash size and frequency dropdowns based on chip's supported values
*/
function populateFlashDropdowns() {
if (!esploader || !esploader.chip) {
return;
}
// Populate Flash Frequency dropdown
flashFreq.innerHTML = '<option value="keep">keep</option>';
const flashFreqKeys = Object.keys(esploader.chip.FLASH_FREQUENCY).sort((a, b) => {
const freqOrder = ["80m", "60m", "48m", "40m", "30m", "26m", "24m", "20m", "16m", "15m", "12m"];
const indexA = freqOrder.indexOf(a);
const indexB = freqOrder.indexOf(b);
if (indexA !== -1 && indexB !== -1) return indexA - indexB;
if (indexA !== -1) return -1;
if (indexB !== -1) return 1;
return a.localeCompare(b);
});
flashFreqKeys.forEach((freq) => {
const option = document.createElement("option");
option.value = freq;
option.textContent = freq;
flashFreq.appendChild(option);
});
flashFreq.options[0].selected = true;
// Populate Flash Size dropdown
flashSize.innerHTML = '<option value="detect">detect</option><option value="keep">keep</option>';
const flashSizeKeys = Object.keys(esploader.chip.FLASH_SIZES).sort((a, b) => {
const sizeOrder = [
"256KB",
"512KB",
"1MB",
"2MB",
"2MB-c1",
"4MB",
"4MB-c1",
"8MB",
"16MB",
"32MB",
"64MB",
"128MB",
];
const indexA = sizeOrder.indexOf(a);
const indexB = sizeOrder.indexOf(b);
if (indexA !== -1 && indexB !== -1) return indexA - indexB;
if (indexA !== -1) return -1;
if (indexB !== -1) return 1;
return a.localeCompare(b);
});
flashSizeKeys.forEach((size) => {
const option = document.createElement("option");
option.value = size;
option.textContent = size;
flashSize.appendChild(option);
});
flashSize.options[1].selected = true;
}
connectButton.onclick = async () => {
try {
if (device === null) {
device = await serialLib.requestPort({});
deviceInfo = device.getInfo();
transport = new Transport(device, true);
}
const flashOptions = {
transport,
baudrate: parseInt(baudrates.value),
terminal: espLoaderTerminal,
debugLogging: debugLogging.checked,
} as LoaderOptions;
esploader = new ESPLoader(flashOptions);
traceButton.style.display = "initial";
chip = await esploader.main();
// Populate flash dropdowns based on chip's supported values
populateFlashDropdowns();
// Temporarily broken
// await esploader.flashId();
// eslint-disable-next-line no-console
console.log("Settings done for :" + chip);
lblBaudrate.style.display = "none";
lblConnTo.innerHTML = "Connected to device: " + chip;
lblConnTo.style.display = "block";
baudrates.style.display = "none";
connectButton.style.display = "none";
disconnectButton.style.display = "initial";
eraseButton.style.display = "initial";
filesDiv.style.display = "initial";
flashMode.style.display = "initial";
flashFreq.style.display = "initial";
flashSize.style.display = "initial";
lblFlashMode.style.display = "initial";
lblFlashFreq.style.display = "initial";
lblFlashSize.style.display = "initial";
consoleDiv.style.display = "none";
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
term.writeln(`Error: ${e.message}`);
}
};
traceButton.onclick = async () => {
if (transport) {
transport.returnTrace();
}
};
resetButton.onclick = async () => {
if (transport) {
await transport.setDTR(false);
await new Promise((resolve) => setTimeout(resolve, 100));
await transport.setDTR(true);
}
};
eraseButton.onclick = async () => {
eraseButton.disabled = true;
try {
await esploader.eraseFlash();
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
term.writeln(`Error: ${e.message}`);
} finally {
eraseButton.disabled = false;
}
};
addFileButton.onclick = () => {
const rowCount = table.rows.length;
const row = table.insertRow(rowCount);
//Column 1 - Offset
const cell1 = row.insertCell(0);
const element1 = document.createElement("input");
element1.type = "text";
element1.id = "offset" + rowCount;
element1.value = "0x1000";
cell1.appendChild(element1);
// Column 2 - File selector
const cell2 = row.insertCell(1);
const element2 = document.createElement("input");
element2.type = "file";
element2.id = "selectFile" + rowCount;
element2.name = "selected_File" + rowCount;
element2.addEventListener("change", handleFileSelect, false);
cell2.appendChild(element2);
// Column 3 - Progress
const cell3 = row.insertCell(2);
cell3.classList.add("progress-cell");
cell3.style.display = "none";
cell3.innerHTML = `<progress value="0" max="100"></progress>`;
// Column 4 - Remove File
const cell4 = row.insertCell(3);
cell4.classList.add("action-cell");
if (rowCount > 1) {
const element4 = document.createElement("input");
element4.type = "button";
const btnName = "button" + rowCount;
element4.name = btnName;
element4.setAttribute("class", "btn");
element4.setAttribute("value", "Remove"); // or element1.value = "button";
element4.onclick = function () {
removeRow(row);
};
cell4.appendChild(element4);
}
};
/**
* The built in HTMLTableRowElement object.
* @external HTMLTableRowElement
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement}
*/
/**
* Remove file row from HTML Table
* @param {HTMLTableRowElement} row Table row element to remove
*/
function removeRow(row: HTMLTableRowElement) {
const rowIndex = Array.from(table.rows).indexOf(row);
table.deleteRow(rowIndex);
}
/**
* Clean devices variables on chip disconnect. Remove stale references if any.
*/
function cleanUp() {
device = null;
deviceInfo = null;
transport = null;
chip = null;
}
disconnectButton.onclick = async () => {
if (transport) await transport.disconnect();
term.reset();
lblBaudrate.style.display = "initial";
baudrates.style.display = "initial";
consoleBaudrates.style.display = "initial";
connectButton.style.display = "initial";
disconnectButton.style.display = "none";
traceButton.style.display = "none";
eraseButton.style.display = "none";
lblConnTo.style.display = "none";
filesDiv.style.display = "none";
flashMode.style.display = "none";
flashFreq.style.display = "none";
flashSize.style.display = "none";
lblFlashMode.style.display = "none";
lblFlashFreq.style.display = "none";
lblFlashSize.style.display = "none";
alertDiv.style.display = "none";
consoleDiv.style.display = "initial";
cleanUp();
};
let isConsoleClosed = false;
let isReconnecting = false;
const sleep = async (ms: number) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
consoleStartButton.onclick = async () => {
if (device === null) {
device = await serialLib.requestPort({});
transport = new Transport(device, true);
deviceInfo = device.getInfo();
// Set up device lost callback
transport.setDeviceLostCallback(async () => {
if (!isConsoleClosed && !isReconnecting) {
term.writeln("\n[DEVICE LOST] Device disconnected. Trying to reconnect...");
await sleep(parseInt(reconnectDelay.value));
isReconnecting = true;
const maxRetries = parseInt(maxRetriesInput.value);
let retryCount = 0;
while (retryCount < maxRetries && !isConsoleClosed) {
retryCount++;
term.writeln(`\n[RECONNECT] Attempt ${retryCount}/${maxRetries}...`);
if (serialLib && serialLib.getPorts) {
const ports = await serialLib.getPorts();
if (ports.length > 0) {
const newDevice = ports.find(
(port) =>
port.getInfo().usbVendorId === deviceInfo.usbVendorId &&
port.getInfo().usbProductId === deviceInfo.usbProductId,
);
if (newDevice) {
device = newDevice;
transport.updateDevice(device);
term.writeln("[RECONNECT] Found previously authorized device, connecting...");
await transport.connect(parseInt(consoleBaudrates.value));
term.writeln("[RECONNECT] Successfully reconnected!");
consoleStopButton.style.display = "initial";
resetButton.style.display = "initial";
isReconnecting = false;
startConsoleReading();
return;
}
}
}
if (retryCount < maxRetries) {
term.writeln(`[RECONNECT] Device not found, retrying in ${parseInt(reconnectDelay.value)}ms...`);
await sleep(parseInt(reconnectDelay.value));
}
}
if (retryCount >= maxRetries) {
term.writeln("\n[RECONNECT] Failed to reconnect after 5 attempts. Please manually reconnect.");
isReconnecting = false;
}
}
});
}
lblConsoleFor.style.display = "block";
lblConsoleBaudrate.style.display = "none";
consoleBaudrates.style.display = "none";
consoleStartButton.style.display = "none";
consoleStopButton.style.display = "initial";
resetButton.style.display = "initial";
programDiv.style.display = "none";
await transport.connect(parseInt(consoleBaudrates.value));
isConsoleClosed = false;
isReconnecting = false;
startConsoleReading();
};
/**
* Start the console reading loop
*/
async function startConsoleReading() {
if (isConsoleClosed || !transport) return;
try {
while (true && !isConsoleClosed) {
const value = await transport.rawRead();
if (!value || value.length === 0) {
break;
}
term.write(value);
}
} catch (error) {
if (!isConsoleClosed) {
term.writeln(`\n[CONSOLE ERROR] ${error instanceof Error ? error.message : String(error)}`);
}
}
if (!isConsoleClosed) {
term.writeln("\n[CONSOLE] Connection lost, waiting for reconnection...");
}
}
consoleStopButton.onclick = async () => {
isConsoleClosed = true;
isReconnecting = false;
if (transport) {
await transport.disconnect();
await transport.waitForUnlock(1500);
}
term.reset();
lblConsoleBaudrate.style.display = "initial";
consoleBaudrates.style.display = "initial";
consoleStartButton.style.display = "initial";
consoleStopButton.style.display = "none";
resetButton.style.display = "none";
lblConsoleFor.style.display = "none";
programDiv.style.display = "initial";
cleanUp();
};
/**
* Validate the provided files images and offset to see if they're valid.
* @returns {string} Program input validation result
*/
function validateProgramInputs() {
const offsetArr = [];
const rowCount = table.rows.length;
let row;
let offset = 0;
let fileData = null;
// check for mandatory fields
for (let index = 1; index < rowCount; index++) {
row = table.rows[index];
//offset fields checks
const offSetObj = row.cells[0].childNodes[0];
offset = parseInt(offSetObj.value);
// Non-numeric or blank offset
if (Number.isNaN(offset)) return "Offset field in row " + index + " is not a valid address!";
// Repeated offset used
else if (offsetArr.includes(offset)) return "Offset field in row " + index + " is already in use!";
else offsetArr.push(offset);
const fileObj = row.cells[1].childNodes[0];
fileData = fileObj.data;
if (fileData == null) return "No file selected for row " + index + "!";
}
return "success";
}
programButton.onclick = async () => {
const alertMsg = document.getElementById("alertmsg");
const err = validateProgramInputs();
if (err != "success") {
alertMsg.innerHTML = "<strong>" + err + "</strong>";
alertDiv.style.display = "block";
return;
}
// Hide error message
alertDiv.style.display = "none";
const fileArray = [];
const progressBars = [];
for (let index = 1; index < table.rows.length; index++) {
const row = table.rows[index];
const offSetObj = row.cells[0].childNodes[0] as HTMLInputElement;
const offset = parseInt(offSetObj.value);
const fileObj = row.cells[1].childNodes[0] as ChildNode & { data: Uint8Array };
const progressBar = row.cells[2].childNodes[0];
progressBar.textContent = "0";
progressBars.push(progressBar);
row.cells[2].style.display = "initial";
row.cells[3].style.display = "none";
fileArray.push({ data: fileObj.data, address: offset });
}
try {
const flashOptions: FlashOptions = {
fileArray: fileArray,
eraseAll: false,
compress: true,
flashMode: flashMode.value as FlashModeValues,
flashFreq: flashFreq.value as FlashFreqValues,
flashSize: flashSize.value as FlashSizeValues,
reportProgress: (fileIndex, written, total) => {
progressBars[fileIndex].value = (written / total) * 100;
},
calculateMD5Hash: (image: Uint8Array) => {
const latin1String = Array.from(image, (byte) => String.fromCharCode(byte)).join("");
return CryptoJS.MD5(CryptoJS.enc.Latin1.parse(latin1String)).toString();
},
};
await esploader.writeFlash(flashOptions);
await esploader.after();
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
term.writeln(`Error: ${e.message}`);
} finally {
// Hide progress bars and show erase buttons
for (let index = 1; index < table.rows.length; index++) {
table.rows[index].cells[2].style.display = "none";
table.rows[index].cells[3].style.display = "initial";
}
}
};
addFileButton.onclick(this);