-
Notifications
You must be signed in to change notification settings - Fork 2
/
index - 4.html
756 lines (602 loc) · 22.9 KB
/
index - 4.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
<!doctype html>
<html>
<head>
<title>Arduboy Web Flasher</title>
<meta name="description" content="One click to update your Arduboy FX over the web, no installation required.">
<!-- Facebook Meta Tags -->
<meta property="og:url" content="https://bateske.github.io/ArduboyWebFlasher/">
<meta property="og:type" content="website">
<meta property="og:title" content="Arduboy Web Flasher">
<meta property="og:description" content="One click to update your Arduboy FX over the web, no installation required.">
<meta property="og:image" content="https://bateske.github.io/ArduboyWebFlasher/images/social.jpg">
<!-- Twitter Meta Tags -->
<meta name="twitter:card" content="summary_large_image">
<meta property="twitter:domain" content="bateske.github.io">
<meta property="twitter:url" content="https://bateske.github.io/arduboywebflasher/">
<meta name="twitter:title" content="Arduboy Web Flasher">
<meta name="twitter:description" content="One click to update your Arduboy FX over the web, no installation required.">
<meta name="twitter:image" content="https://bateske.github.io/ArduboyWebFlasher/images/social.jpg">
<link rel="stylesheet" href="style.css?cachebust=202312101" />
</head>
<body>
<center>
<h1>Arduboy Web Flasher</h1>
<h3>Update your Arduboy FX with one click!<br>Get the most up to date collection of all the games!</h3>
<div id="progressBar" class="circular-progress" data-inner-circle-color="lightgrey" data-percentage="0" data-progress-color="#FBF157" data-bg-color="black">
<div class="inner-circle"></div>
<div class="progressHolder">
<div id="progressPercent"></div>
<div id="progressTime"></div>
<div id="uploadBtn">
<div id="uploadIco"></div>
<div id="uploadTxt">Upload</div>
</div>
</div>
</div>
<br>
<div class="bottomContainer">
<div class="fileButtonWrapper">
<div class="restWrap">
<div id="resetBtn"></div>
<div id="fileButton">File Select</div>
</div>
<input id="fileInput" tabindex="-1" type="file"/>
<div id="fileName">Whole Enchilada.bin</div>
</div>
</div>
<div id="instructions">- or -<br>Drag & Drop your own .hex or .bin file anywhere on the page</div>
<h3>Instructions</h3>
<div id="instructions">Connect your Arduboy FX to USB and power on, then click the Upload button.<BR>The Arduboy FX must be in the bootloader menu to perform the upload.</div>
<h3>FAQ</h3>
<div id="instructions">.hex files are individual Arduboy games created using <a href="https://community.arduboy.com/t/make-your-own-arduboy-game-part-1-setting-up-your-computer/7924">Arduino</a> or download from the <a href="https://community.arduboy.com/c/games/35">Arduboy Community</a>.</div>
<div id="instructions">.bin files are a collection of Arduboy games, to be stored on the external memory of the Arduboy FX.</div>
<div id="instructions">Create .bin files using the <a href="https://community.arduboy.com/t/arduboy-fx-cart-builder/10395">Online Cart Builder</a> or Mr. Blinky's <a href="https://community.arduboy.com/t/using-python/7745">Arduboy Python Utilities</a>.</div>
<div id="instructions">For all of your more advanced and offline Arduboy needs please see: <a href="https://community.arduboy.com/t/arduboy-toolset/11227">Arduboy Toolset</a></div>
<br><br>
<div class="credits">Thank you to Mr. Blinky and Benjamin Naigener</div>
</center>
<script>
// --- DOM Element object definitions ---
const progressPercent = document.getElementById('progressPercent');
const progressTime = document.getElementById('progressTime');
const progressBar = document.getElementById('progressBar');
const resetBtn = document.getElementById('resetBtn');
const fileInput = document.getElementById('fileInput');
const fileButton = document.getElementById('fileButton');
const fileName = document.getElementById('fileName');
const uploadBtn = document.getElementById('uploadBtn');
uploadBtn.addEventListener('click', handleSubmit, false);
resetBtn.addEventListener('click', handleReset, false);
fileButton.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file)
fileName.textContent = file.name;
});
// --- Drag Drop Handling ---
let dragCounter = 0;
document.addEventListener('dragenter', (e) => {
dragCounter++;
document.body.style.backgroundColor = '#9831c4'; // Change to your preferred color
});
document.addEventListener('dragleave', (e) => {
dragCounter--;
if (dragCounter === 0) {
document.body.style.backgroundColor = ''; // Revert to original color
}
});
document.addEventListener('dragover', (e) => {
e.preventDefault();
});
document.addEventListener('drop', (e) => {
dragCounter = 0; // Reset counter on drop
const fileDrop = e.dataTransfer.files[0];
if (fileDrop) {
fileName.textContent = fileDrop.name;
document.getElementById('fileInput').files = e.dataTransfer.files;
console.log(document.getElementById('fileInput').files);
}
document.body.style.backgroundColor = ''; // Revert to original color
e.preventDefault()
});
// --- Progress Bar Animation ---
// Library calls: drawInit(), drawComplete() and drawPercentage(percentVal)
function drawInit(){
uploadBtn.style.display = "none";
}
function drawComplete(){
uploadBtn.style.display = "block";
}
let currentAnimation = null;
let lastEndValue = 0; // Cache the last end value
let lastCallTime = 0; // Timestamp of the last function call
let currentValue = 0; // Current progress value
let progressHistory = []; // Stores history of progress values and timestamps
function drawPercentage(percentVal) {
let now = Date.now();
let timeElapsed = now - lastCallTime; // Time since last call
lastCallTime = now; // Update the timestamp
let endValue = Math.round(percentVal);
if(percentVal>5){
// the beginning is slow and unfairly weights the average
progressHistory.push({
time: now,
value: endValue
});
}
let estimatedTimeToComplete = Math.round(estimateTimeToComplete());
if (percentVal > 0) {
progressPercent.textContent = endValue + '%';
console.log("Estimated Time to Complete: ", estimatedTimeToComplete, "seconds");
if (estimatedTimeToComplete == 0) {
if (percentVal == 100) {
progressTime.textContent = "Complete!";
} else {
progressTime.textContent = "Calculating...";
}
}
else if(estimatedTimeToComplete > 60){
const minutes = Math.floor(estimatedTimeToComplete / 60);
const seconds = estimatedTimeToComplete % 60;
let minWord = "minute";
if(minutes>1) minWord += "s";
let secWord = "second";
if(seconds>1) secWord += "s";
progressTime.innerHTML = minutes + " " + minWord + "<br>" + seconds + " " + secWord + " left";
}
else {
progressTime.textContent = estimatedTimeToComplete + " seconds left";
}
}
let progressColor = progressBar.getAttribute("data-progress-color");
// Adjust animation speed based on new endValue
let frameRate = calculateFrameRate(timeElapsed, endValue);
if (currentAnimation !== null) {
cancelAnimationFrame(currentAnimation);
}
function animate(step) {
if (currentValue > endValue) {
currentValue = currentValue - step;
} else {
currentValue = Math.min(currentValue + step, endValue);
}
progressBar.style.background = 'conic-gradient('+progressColor+' '+currentValue * 3.6+'deg, '+ progressBar.getAttribute("data-bg-color")+' 0deg)';
if (currentValue + endValue == 0) {
progressBar.style.background = '';
progressHistory = [];
}
currentAnimation = requestAnimationFrame(() => animate(frameRate));
}
animate(frameRate);
}
function calculateFrameRate(timeElapsed, endValue) {
let baseFrameRate = 0.02;
let expectedDuration = 500; // Adjust as needed
if (endValue === 0) {
progressTime.textContent = '';
progressPercent.textContent = '';
return 5; // Faster frame rate for resetting
} else if (timeElapsed > 0) {
let dynamicRate = baseFrameRate * (expectedDuration / timeElapsed);
return dynamicRate * (endValue - currentValue);
} else {
return baseFrameRate;
}
}
let counter = 0;
let lastComputedEstimate = 0;
let lastComputedTime = 0;
function estimateTimeToComplete() {
counter++;
if (counter % 10 === 0) {
// Compute the estimate every 10th call
lastComputedEstimate = computeEstimate();
lastComputedTime = Date.now();
return lastComputedEstimate;
} else {
// For other calls, adjust the estimate based on time elapsed
const currentTime = Date.now();
const timeElapsed = currentTime - lastComputedTime;
// Adjust the estimate based on the elapsed time
const adjustedEstimate = Math.max(0, lastComputedEstimate - timeElapsed / 1000);
return adjustedEstimate.toFixed(2);
}
}
function computeEstimate() {
if (progressHistory.length < 5) {
return 0; // Not enough data to calculate
}
// Calculate average speed (percent change per millisecond)
let totalChange = 0;
let totalTime = 0;
for (let i = 1; i < progressHistory.length; i++) {
let change = progressHistory[i].value - progressHistory[i - 1].value;
let time = progressHistory[i].time - progressHistory[i - 1].time;
totalChange += change;
totalTime += time;
}
let averageSpeed = totalChange / totalTime;
if (averageSpeed === 0) {
return "Infinity"; // No progress being made
}
let remaining = 100 - progressHistory[progressHistory.length - 1].value;
let estimatedTimeMillis = remaining / averageSpeed;
return (estimatedTimeMillis / 1000).toFixed(2); // Convert to seconds
}
// --- End of DOM Manipulation ---
// --- Library Interface ---
async function handleSubmit(e) {
if (!("serial" in navigator)) {
alert("Please use Chromium based browsers!");
return;
}
let fileType = 0;
let fileContents;
let file = fileInput.files[0];
const readerF = new FileReader();
if (!file) {
// If no file is provided, use the default file
const response = await fetch('Whole Enchilada.bin');
if (!response.ok) {
alert("Error loading default file");
return;
}
fileType = 2;
console.log("awaiting blob");
file = await response.blob();
console.log("blobbed");
} else {
//User uploaded a file, determine if it is a HEX or BIN and set the fileType
const name = fileInput.files[0].name;
const lastDot = name.lastIndexOf('.');
const fileName = name.substring(0, lastDot);
const ext = name.substring(lastDot + 1);
if (ext == "hex") {
console.log("hex file detected");
fileType = 1;
} else if (ext == "bin") {
console.log("bin file detected");
fileType = 2;
} else {
alert("Only .hex and .bin files are supported");
}
}
readerF.onload = async function (event) {
fileContents = event.target.result;
if (fileType == 1) {
flashHex(fileContents);
} else if (fileType == 2) {
const uint8ArrayData = new Uint8Array(fileContents);
flashFx(uint8ArrayData);
}
};
if (fileType == 1) {
readerF.readAsText(file);
} else if (fileType == 2) {
readerF.readAsArrayBuffer(file);
}
}
// --- End Library Interface ---
// --- Begin Library Functions ---
// --- Hex Parser ---
// based on code by benjamin naigener https://github.com/benjaminaigner/avr109-webserial
//credits: https://stackoverflow.com/questions/38987784/how-to-convert-a-hexadecimal-string-to-uint8array-and-back-in-javascript
const fromHexString = hexString =>
new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
//Intel Hex record types
const DATA = 0,
END_OF_FILE = 1,
EXT_SEGMENT_ADDR = 2,
START_SEGMENT_ADDR = 3,
EXT_LINEAR_ADDR = 4,
START_LINEAR_ADDR = 5;
const EMPTY_VALUE = 0xFF;
/* intel_hex.parse(data)
`data` - Intel Hex file (string in ASCII format or Buffer Object)
`bufferSize` - the size of the Buffer containing the data (optional)
returns an Object with the following properties:
- data - data as a Buffer Object, padded with 0xFF
where data is empty.
- startSegmentAddress - the address provided by the last
start segment address record; null, if not given
- startLinearAddress - the address provided by the last
start linear address record; null, if not given
Special thanks to: http://en.wikipedia.org/wiki/Intel_HEX
*/
function parseIntelHex(data) {
//if(data instanceof Buffer)
data = data.toString("ascii");
//Initialization
var buf = new Uint8Array(32768); //max. words in mega32u4
var bufLength = 0, //Length of data in the buffer
highAddress = 0, //upper address
startSegmentAddress = null,
startLinearAddress = null,
lineNum = 0, //Line number in the Intel Hex string
pos = 0; //Current position in the Intel Hex string
const SMALLEST_LINE = 11;
while (pos + SMALLEST_LINE <= data.length) {
//Parse an entire line
if (data.charAt(pos++) != ":")
throw new Error("Line " + (lineNum + 1) +
" does not start with a colon (:).");
else
lineNum++;
//Number of bytes (hex digit pairs) in the data field
var dataLength = parseInt(data.substr(pos, 2), 16);
pos += 2;
//Get 16-bit address (big-endian)
var lowAddress = parseInt(data.substr(pos, 4), 16);
pos += 4;
//Record type
var recordType = parseInt(data.substr(pos, 2), 16);
pos += 2;
//Data field (hex-encoded string)
var dataField = data.substr(pos, dataLength * 2);
if (dataLength)
var dataFieldBuf = fromHexString(dataField);
else
var dataFieldBuf = new Uint8Array();
pos += dataLength * 2;
//Checksum
var checksum = parseInt(data.substr(pos, 2), 16);
pos += 2;
//Validate checksum
var calcChecksum = (dataLength + (lowAddress >> 8) +
lowAddress + recordType) & 0xFF;
for (var i = 0; i < dataLength; i++)
calcChecksum = (calcChecksum + dataFieldBuf[i]) & 0xFF;
calcChecksum = (0x100 - calcChecksum) & 0xFF;
if (checksum != calcChecksum)
throw new Error("Invalid checksum on line " + lineNum +
": got " + checksum + ", but expected " + calcChecksum);
//Parse the record based on its recordType
switch (recordType) {
case DATA:
var absoluteAddress = highAddress + lowAddress;
//Expand buf, if necessary
/*if(absoluteAddress + dataLength >= buf.length)
{
var tmp = Buffer.alloc((absoluteAddress + dataLength) * 2);
buf.copy(tmp, 0, 0, bufLength);
buf = tmp;
}*/
//Write over skipped bytes with EMPTY_VALUE
if (absoluteAddress > bufLength)
buf.fill(EMPTY_VALUE, bufLength, absoluteAddress);
//Write the dataFieldBuf to buf
//dataFieldBuf.copy(buf, absoluteAddress);
dataFieldBuf.forEach(function (val, index) {
buf[absoluteAddress + index] = val;
});
bufLength = Math.max(bufLength, absoluteAddress + dataLength);
break;
case END_OF_FILE:
if (dataLength != 0)
throw new Error("Invalid EOF record on line " +
lineNum + ".");
return {
"data": buf.slice(0, bufLength),
"startSegmentAddress": startSegmentAddress,
"startLinearAddress": startLinearAddress
};
break;
case EXT_SEGMENT_ADDR:
if (dataLength != 2 || lowAddress != 0)
throw new Error("Invalid extended segment address record on line " +
lineNum + ".");
highAddress = parseInt(dataField, 16) << 4;
break;
case START_SEGMENT_ADDR:
if (dataLength != 4 || lowAddress != 0)
throw new Error("Invalid start segment address record on line " +
lineNum + ".");
startSegmentAddress = parseInt(dataField, 16);
break;
case EXT_LINEAR_ADDR:
if (dataLength != 2 || lowAddress != 0)
throw new Error("Invalid extended linear address record on line " +
lineNum + ".");
highAddress = parseInt(dataField, 16) << 16;
break;
case START_LINEAR_ADDR:
if (dataLength != 4 || lowAddress != 0)
throw new Error("Invalid start linear address record on line " +
lineNum + ".");
startLinearAddress = parseInt(dataField, 16);
break;
default:
throw new Error("Invalid record type (" + recordType +
") on line " + lineNum);
break;
}
//Advance to the next line
if (data.charAt(pos) == "\r")
pos++;
if (data.charAt(pos) == "\n")
pos++;
}
throw new Error("Unexpected end of input: missing or invalid EOF record.");
};
// --- Helper Functions ---
function waitforme(milisec) {
return new Promise(resolve => {
setTimeout(() => {
resolve('')
}, milisec);
})
}
const equals = (a, b) =>
a.length === b.length &&
a.every((v, i) => v === b[i]);
// --- Web Serial API Calls after this point ---
let filters = [{ // Port filters for Arduino Leonardo in Bootloader and Application Mode
usbVendorId: 0x2341,
usbProductId: 0x0036
}, {
usbVendorId: 0x2341,
usbProductId: 0x8036
}
];
async function handleReset(e) {
if (!("serial" in navigator)) {
alert("Please use Chromium based browsers!");
}
port = await navigator.serial.requestPort({
filters
});
await port.open({
baudRate: 1200
});
await waitforme(500);
await port.close();
await waitforme(500);
}
class SerialPortManager {
constructor() {
this.port = null;
this.writer = null;
this.reader = null;
}
async initPort() {
this.port = await navigator.serial.requestPort({ filters });
await this.port.open({ baudRate: 115200, bufferSize: 65536 });
this.writer = this.port.writable.getWriter();
this.reader = this.port.readable.getReader();
}
async writeAndRead(data) {
await this.writer.write(data);
const { value } = await this.reader.read(1);
return value;
}
async cleanup() {
if (this.reader) {
try {
this.reader.releaseLock();
} catch (error) {
console.error("Error releasing reader lock:", error);
}
}
if (this.writer) {
try {
this.writer.releaseLock();
} catch (error) {
console.error("Error releasing writer lock:", error);
}
}
if (this.port) {
try {
await this.port.close();
} catch (error) {
console.error("Error closing the port:", error);
}
}
}
}
async function beginProgramming(serialManager) {
await serialManager.writer.write(new Uint8Array([0x53])); //trigger update by sending programmer ID command
await waitforme(500);
// TODO -- should be doing a read and verifying it returns "ARDUBOY"
await serialManager.writer.write(new Uint8Array([120, 0xC2])); // red led and disable buttons
drawPercentage(0);
drawInit();
}
async function endProgramming(serialManager) {
await serialManager.writer.write(new Uint8Array([120, 0x40])); // red led off and enable buttons
drawPercentage(100);
setTimeout(function () {
drawComplete();
drawPercentage(0);
}, 5000);
}
async function flashBlock(serialManager, block, blocks, flashData, pageNumber, FX_PAGESIZE, FX_BLOCKSIZE) {
let blockAddr = pageNumber + block * FX_BLOCKSIZE / FX_PAGESIZE;
let blockLen = FX_BLOCKSIZE;
console.log("Writing Block: ", block);
drawPercentage((block / blocks) * 100);
await serialManager.writeAndRead(new Uint8Array(['A'.charCodeAt(0), blockAddr >> 8, blockAddr & 0xFF])); // address command
let dataSlice = flashData.slice(block * FX_BLOCKSIZE, block * FX_BLOCKSIZE + blockLen);
console.log("Length of data Block: ", dataSlice.length);
let realBlockLen = dataSlice.length;
await serialManager.writer.write(new Uint8Array(['B'.charCodeAt(0), realBlockLen >> 8, blockLen & 0xFF, 'C'.charCodeAt(0)])); // data command
await serialManager.writer.write(dataSlice); // data write
console.log("Block written! attempting to Read");
await serialManager.reader.read(1);
console.log("read complete!");
}
async function flashFx(flashData, pageNumber = 0, verify = false) {
if (!flashData.length) {
throw new Error("No flash data provided!");
}
const FX_PAGESIZE = 256;
const FX_BLOCKSIZE = 65536;
const FX_PAGES_PER_BLOCK = FX_BLOCKSIZE / FX_PAGESIZE;
const serial1 = new SerialPortManager();
await serial1.initPort();
await beginProgramming(serial1);
let blocks = Math.ceil(flashData.length / FX_BLOCKSIZE);
console.log('Flashing ${blocks} blocks to FX');
for (let block = 0; block < blocks; block++) {
await flashBlock(serial1, block, blocks, flashData, pageNumber, FX_PAGESIZE, FX_BLOCKSIZE);
if (verify) {
// TODO -- TEST and get working --- UNTESTED
await serial1.writeAndRead(new Uint8Array(['A'.charCodeAt(0), blockAddr >> 8, blockAddr & 0xFF]));
await serial1.writeAndRead(new Uint8Array(['g'.charCodeAt(0), blockLen >> 8, blockLen & 0xFF, 'C'.charCodeAt(0)]));
const verifyData = await serial1.reader.read(blockLen);
if (!equals(verifyData, flashData.slice(block * FX_BLOCKSIZE, block * FX_BLOCKSIZE + blockLen))) {
throw new Error('FX verify failed at address ${blockAddr.toString(16)}. Upload unsuccessful.');
}
}
}
await endProgramming(serial1);
await serial1.cleanup();
console.log("Success in flashing FX!!");
}
async function leaveBootloader(serialManager) {
await serialManager.writer.write(new Uint8Array([0x4C])); //"L" -> leave programming mode
await serialManager.writer.write(new Uint8Array([120, 0x40])); // red led off and enable buttons
await waitforme(5);
await serialManager.writer.write(new Uint8Array([0x45])); //"E" -> exit bootloader
}
function flashHexBlock(flashData, pageStart) {
let data, pad, txx;
cmd = new Uint8Array([0x42, 0x00, 0x80, 0x46]); //flash page write command ('B' + 2bytes size + 'F')
// Check if this is the last page (possibly incomplete -> fill with 0xFF)
if (pageStart + 128 > flashData.data.length) {
data = flashData.data.slice(pageStart); // Take the remaining bit
pad = new Uint8Array(128 - data.length); // Create a new padding array
pad.fill(0xFF);
txx = Uint8Array.from([...cmd, ...data, ...pad]); // Concat command, remaining data, and padding
console.log("last page");
} else {
data = flashData.data.slice(pageStart, pageStart + 128); // Take subarray with 128B
txx = Uint8Array.from([...cmd, ...data]); // Concatenate command with page data
}
return txx;
}
async function flashHex(hexData) {
if (!hexData.length) {
throw new Error("No hex data provided!");
}
let pageStart = 0;
let address = 0;
let flashData = parseIntelHex(hexData);
const serial1 = new SerialPortManager();
await serial1.initPort();
await beginProgramming(serial1);
do {
drawPercentage((pageStart / flashData.data.length) * 100);
await serial1.writeAndRead(new Uint8Array([0x41, (address >> 8) & 0xFF, address & 0xFF])); //addresss command
let txx = flashHexBlock(flashData, pageStart); //generate page data
await serial1.writeAndRead(txx); //write the page data
pageStart += 128;
address += 64;
} while (pageStart + 128 <= flashData.data.length);
await leaveBootloader(serial1);
await endProgramming(serial1);
await serial1.cleanup();
console.log("finished!");
}
</script>
</body>
</html>