-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
1469 lines (1253 loc) · 69 KB
/
Copy pathindex.html
File metadata and controls
1469 lines (1253 loc) · 69 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
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<!-- Version: v1.31-1766831033 -->
<title>🦇 Vampire Deauther 2.4GHz & 5GHz - BW16 Web Flasher v1.31 AUTO-DOWNLOAD MODE</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0d1117;
color: #c9d1d9;
line-height: 1.6;
}
.container { max-width: 900px; margin: 0 auto; padding: 40px 20px; }
h1 { font-size: 2.5em; margin-bottom: 10px; color: #ffffff; text-align: center; }
h3 { color: #ffffff; }
.subtitle { text-align: center; color: #8b949e; margin-bottom: 40px; }
.flasher-box {
background: #161b22;
border: 1px solid #30363d;
border-radius: 6px;
padding: 30px;
margin-bottom: 30px;
}
.warning-box {
background: #1c1416;
border: 2px solid #f85149;
border-radius: 6px;
padding: 20px;
margin-bottom: 20px;
}
.info-box {
background: #1c2128;
border: 2px solid #30363d;
border-radius: 6px;
padding: 20px;
margin-bottom: 20px;
}
.success-box {
background: #0f2818;
border: 2px solid #238636;
border-radius: 6px;
padding: 20px;
margin-bottom: 20px;
}
.warning-box h3 { color: #f85149; margin-bottom: 10px; }
.info-box h3 { color: #ffffff; margin-bottom: 10px; }
.success-box h3 { color: #3fb950; margin-bottom: 10px; }
.downloads-section {
background: #161b22;
border: 1px solid #30363d;
border-radius: 6px;
padding: 20px;
margin-bottom: 30px;
text-align: center;
}
.downloads-section h3 {
color: #ffffff;
margin-bottom: 15px;
}
.download-link {
display: inline-block;
background: #1a1a1a;
color: white;
padding: 12px 24px;
border-radius: 6px;
text-decoration: none;
margin: 10px 5px;
transition: background 0.2s;
font-weight: bold;
border: 1px solid #30363d;
}
.download-link:hover { background: #2a2a2a; }
button {
background: #1a1a1a;
color: white;
border: 1px solid #30363d;
padding: 12px 24px;
font-size: 16px;
border-radius: 6px;
cursor: pointer;
width: 100%;
margin: 10px 0;
transition: background 0.2s;
}
button:hover { background: #2a2a2a; }
button:disabled { background: #21262d; color: #484f58; cursor: not-allowed; }
#statusBox {
background: #0d1117;
border: 1px solid #30363d;
border-radius: 6px;
padding: 15px;
height: 400px;
overflow-y: auto;
font-family: 'Courier New', monospace;
font-size: 13px;
margin: 20px 0;
}
#progressContainer { display: none; margin: 20px 0; }
#progressBar {
background: linear-gradient(90deg, #000000 0%, #1a1a1a 100%);
height: 30px;
border-radius: 6px;
text-align: center;
line-height: 30px;
color: white;
font-weight: bold;
transition: width 0.3s;
}
</style>
</head>
<body>
<div class="container">
<h1>Vampire Deauther 2.4Ghz & 5Ghz</h1>
<p class="subtitle">BW16 Web Flasher v2.4.6 Now save PCAP, AUTO-DOWNLOAD MODE</p>
<div class="downloads-section">
<h3>📥 Downloads</h3>
<a href="./vampire_deauther.fap" class="download-link" download>
📦 Download Flipper FAP
</a>
<a href="https://github.com/Vampel/Vampire-Deauther" class="download-link" target="_blank">
🦇 View on GitHub
</a>
</div>
<div class="flasher-box">
<h3 style="color: #ffffff; margin-bottom: 15px;">🚀 Flash BW16 Firmware</h3>
<button id="connectBtn">Connect BW16 (COM port)</button>
<button id="flashBtn" disabled>Flash Firmware</button>
<div id="progressContainer">
<div id="progressBar" style="width: 0%;">0%</div>
</div>
<div id="statusBox"></div>
<hr style="border: none; border-top: 1px solid #30363d; margin: 30px 0;">
<h3 style="color: #ffffff; margin-bottom: 15px;">📁 Custom Firmware (Optional)</h3>
<p style="color: #8b949e; margin-bottom: 15px; font-size: 14px;">
Leave empty to use default Vampire Deauther firmware from GitHub, or select your own files to flash any ameba RTL872xDx firmware.:
</p>
<div style="margin-bottom: 10px;">
<label style="display: block; margin-bottom: 5px; font-size: 14px;">Flashloader (imgtool_flashloader_amebad.bin):</label>
<input type="file" id="flashloaderFile" accept=".bin" style="width: 100%; padding: 8px; background: #0d1117; border: 1px solid #30363d; border-radius: 4px; color: #c9d1d9;">
</div>
<div style="margin-bottom: 10px;">
<label style="display: block; margin-bottom: 5px; font-size: 14px;">Your Ameba Firmware (2MB, 4MB, or any size - no padding):</label>
<input type="file" id="firmwareFile" accept=".bin" style="width: 100%; padding: 8px; background: #0d1117; border: 1px solid #30363d; border-radius: 4px; color: #c9d1d9;">
</div>
</div>
<div class="info-box">
<h3>🔌 BW16 to Flipper Zero Wiring</h3>
<pre style="background: #0d1117; padding: 15px; border-radius: 4px; overflow-x: auto; font-size: 13px; line-height: 1.8;">
BW16 (22 pins) Flipper Zero GPIO Header
================ =========================
Pin 1 - 3V3 (Red) ---> Pin 9 - 3.3V ✅
Pin 2 - GND (Black) ---> Pin 18 - GND ✅
Pin 3 - PA26_TXD (Any Color) ---> Pin 14 - RX (Flipper receive data) ✅
Pin 4 - PA25_RXD (Any Color) <--- Pin 13 - TX (Flipper transmit data) ✅
</pre>
<p style="margin-top: 15px; line-height: 1.8;">
<strong>⚠️ Note:</strong> Used black PCB 22 pins BW16(RTL8720DN). 30 pins version doesn't work properly (blue PCB).
</p>
<p style="line-height: 1.8;">
<strong>🔧 Leds indication:</strong><br>
Solid green = BW16 ready<br>
Blinking blue = Scanning Wi-Fi networks<br>
Blinking red = Deauthentication of single network(press RESET button on board to stop it)<br>
Blinking red (slower) = Deauthentication of all networks(press RESET button on board to stop it)<br>
Blinking green = Beacon spam. (Pressing back button on Flipper stops it)<br>
Note: Memory fills during deauth, may need RESET board
</p>
<p style="line-height: 1.8;">
<strong>💻 Standalone Use:</strong> Can be used without Flipper Zero via Arduino IDE at 115200 baud
</p>
<h4 style="color: #ffffff; margin-top: 20px; margin-bottom: 10px;">Serial Monitor Commands:</h4>
<ul style="margin-left: 20px; line-height: 2; font-family: 'Courier New', monospace; font-size: 14px;">
<li><code style="color: #79c0ff;">AT+SCAN</code> - Scan WiFi networks and save them to memory as indexed list</li>
<li><code style="color: #79c0ff;">AT+DEAUTHIDX=</code> - = followed by the index number Deauth a single network(press RESET button to restart BW16)</li>
<li><code style="color: #79c0ff;">AT+DEAUTHIDX=ALL</code> - Deauth all networks in index (press RESET button to restart BW16)</li>
<li><code style="color: #79c0ff;">AT+BEACONRANDOM=Vampel</code> - Spam networks with suffix "Vampel 001, Vampel 002... up to 50"</li>
<li><code style="color: #79c0ff;">AT+STOP</code> - Stop current operation (Note: Memory fills during deauth, may need RESET)</li>
</ul>
<p style="margin-top: 10px; color: #8b949e; font-size: 14px;">
With Flipper Zero, the menu guides you through all options easily.<br>
Note: some Devices have PMF enabled (cant Deauth)
</p>
</div>
<div class="info-box">
<h3>🚀 Future Features</h3>
<ul style="margin-left: 20px; margin-top: 10px; line-height: 2; color: #c9d1d9;">
<li>Change baud rate to 1500000 for faster flashing</li>
<li>Ability to read & save firmwares from BW16 & any Ameba board </li>
<li>Thanks to all the developers of SharpRTL872xTool & tesa-klebeband, my codes was based on.</li>
</ul>
</div>
</div>
<script>
/*
* BW16 Flash Protocol v40 - RAM Address Protocol
*
* This flasher uses the CORRECT protocol as discovered by analyzing
* Arduino IDE Device Monitoring Studio logs and disassembling the
* imgtool_flashloader_amebad.bin binary.
*
* CRITICAL FINDINGS:
*
* 1. ADDRESSES: Use RAM addresses (0x08xxxxxx), NOT flash (0x0xxxxx)
* - The flashloader translates RAM → FLASH internally
* - RAM 0x08000000 → FLASH 0x000000
* - RAM 0x08004000 → FLASH 0x004000
* - RAM 0x08006000 → FLASH 0x006000
*
* 2. SEQUENCE:
* a) Upload flashloader to RAM 0x82000 via XMODEM
* b) Reset flashloader (CMD 0x04)
* c) Sync with flashloader (CMD 0x07)
* d) Initialize flash controller (CMD 0x26 [01 01 00])
* e) ERASE each area explicitly (CMD 0x17 [addr:4][blocks:2])
* f) XMODEM upload data to RAM addresses
*
* 3. COMMANDS:
* CMD_SYNC (0x07) - Synchronize
* CMD_RESET (0x04) - Reset flashloader
* CMD_ERASE (0x17) - Erase flash [addr:4bytes][blocks:2bytes]
* CMD_FLASH_MODE (0x26) - Initialize flash [01 01 00]
*
* The flashloader does NOT automatically erase or copy from RAM to flash.
* All operations must be explicitly commanded.
*/
let port = null;
let reader = null;
let writer = null;
const SOH = 0x01; // XMODEM Start of Header
const EOT = 0x04; // XMODEM End of Transmission
const ACK = 0x06;
const NAK = 0x15;
const BAUD_RATE_INITIAL = 115200; // Initial connection
const BAUD_RATE_FLASH = 1500000; // Fast flashing (like VampelRTL)
const CMD_SYNC = 0x07;
const CMD_WRITE = 0x02;
const CMD_RESET = 0x04;
const CMD_ERASE = 0x17;
const CMD_FLASH_MODE = 0x26;
const CMD_SET_BAUD = 0x05; // Set baudrate command
const FLASHLOADER_ADDR = 0x082000;
// Flash OFFSETS (not RAM addresses) for flashloader writes
const FIRMWARE_FLASH_OFFSET = 0x006000; // Flash offset, not RAM address!
const OTA2_ADDR = 0x08106000;
const FIRMWARE_SIZE_2MB = 0x200000; // 2MB = 2,097,152 bytes
function log(msg, color = '#c9d1d9') {
const statusBox = document.getElementById('statusBox');
const time = new Date().toLocaleTimeString();
const line = document.createElement('div');
line.style.color = color;
line.textContent = `[${time}] ${msg}`;
statusBox.appendChild(line);
statusBox.scrollTop = statusBox.scrollHeight;
}
function updateProgress(percent, text) {
const container = document.getElementById('progressContainer');
const bar = document.getElementById('progressBar');
container.style.display = 'block';
bar.style.width = percent + '%';
bar.textContent = text || `${percent}%`;
}
async function setBaudRate(newBaud) {
// VampelRTL baudrate mapping
const baudRates = [115200, 128000, 153600, 230400, 380400, 460800, 500000, 921600, 1000000, 1382400, 1444400, 1500000];
let baudIndex = 0x0D;
for (let i = 0; i < baudRates.length; i++) {
if (baudRates[i] >= newBaud) {
newBaud = baudRates[i];
baudIndex = 0x0D + i;
break;
}
}
log(`Setting baudrate to ${newBaud}...`, '#d29922');
// Send CMD_SET_BAUD (0x05) with baud index
const baudCmd = new Uint8Array([CMD_SET_BAUD, baudIndex]);
await writer.write(baudCmd);
// Wait for ACK
const ack = await readByteWithTimeout(1000);
if (ack !== ACK) {
throw new Error(`Baudrate change failed: expected ACK, got 0x${ack?.toString(16)}`);
}
// Release locks
writer.releaseLock();
reader.releaseLock();
// Wait a bit before changing
await new Promise(r => setTimeout(r, 50));
// Change port baudrate
await port.close();
await port.open({ baudRate: newBaud });
// Get new locks
reader = port.readable.getReader();
writer = port.writable.getWriter();
// Wait and flush
await new Promise(r => setTimeout(r, 50));
try {
while (true) {
const { value } = await readWithTimeout(10);
if (!value || value.length === 0) break;
}
} catch {}
log(`✓ Baudrate changed to ${newBaud}`);
return newBaud;
}
async function connectSerial() {
try {
// Check if Web Serial API is supported
if (!('serial' in navigator)) {
log('❌ Web Serial API not supported in this browser', '#f85149');
log('Please use Chrome, Edge, or Opera browser', '#d29922');
alert('Web Serial API not supported!\n\nPlease use:\n• Chrome 89+\n• Edge 89+\n• Opera 75+');
return;
}
log('Select BW16 serial port...', '#58a6ff');
port = await navigator.serial.requestPort();
await port.open({ baudRate: BAUD_RATE_INITIAL });
reader = port.readable.getReader();
writer = port.writable.getWriter();
log(`✅ Connected to BW16 at ${BAUD_RATE_INITIAL} baud`);
document.getElementById('connectBtn').disabled = true;
document.getElementById('flashBtn').disabled = false;
} catch (error) {
log(`❌ Connection error: ${error.message}`, '#f85149');
if (error.name === 'NotFoundError') {
log('No port selected. Please try again.', '#d29922');
}
}
}
async function readWithTimeout(timeoutMs = 1000) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), timeoutMs)
);
const read = reader.read();
return Promise.race([read, timeout]);
}
async function readByte() {
const { value } = await readWithTimeout();
return value[0];
}
async function flushBuffer() {
log('Flushing initial buffer...', '#58a6ff');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', '#58a6ff');
log('⚠️ SHOWING FIRST 100 BYTES FROM BOOTLOADER:', '#d29922');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', '#58a6ff');
const startTime = Date.now();
let foundNak = false;
let foundDownloadMsg = false;
let byteCount = 0;
let nullCount = 0;
const debugBytes = [];
const allBytes = [];
// At 115200 baud, flush aggressively for max 2 seconds
while (Date.now() - startTime < 2000) {
try {
const { value } = await readWithTimeout(100);
if (!value || value.length === 0) break;
for (let i = 0; i < value.length; i++) {
byteCount++;
allBytes.push(value[i]);
if (value[i] === 0x00) nullCount++;
if (value[i] === NAK) foundNak = true;
// Save first 100 bytes for display
if (debugBytes.length < 100) {
debugBytes.push(value[i]);
}
}
} catch {
break;
}
}
// Check for "Flash Download Start" message
const allStr = String.fromCharCode(...allBytes);
if (allStr.includes('Flash Download Start')) {
foundDownloadMsg = true;
}
// Display first 100 bytes as hex AND try to show ASCII
if (debugBytes.length > 0) {
const hexStr = debugBytes.map(b => b.toString(16).padStart(2, '0')).join(' ');
const asciiStr = debugBytes.map(b =>
(b >= 0x20 && b <= 0x7E) ? String.fromCharCode(b) : '.'
).join('');
log(`HEX (${debugBytes.length} bytes):`, '#58a6ff');
log(hexStr, '#c9d1d9');
log(`ASCII:`, '#58a6ff');
log(asciiStr, '#c9d1d9');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', '#58a6ff');
}
if (foundDownloadMsg) {
log('✅ "Flash Download Start" detected!');
}
if (foundNak) {
log(`✓ Found NAK! Bootloader detected`);
} else {
log(`Total: ${byteCount} bytes, ${nullCount} nulls, NO NAK`, '#f85149');
if (nullCount > 100) {
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', '#f85149');
log('❌ BOOTLOADER NOT DETECTED!', '#f85149');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', '#f85149');
log('Expected to see: "#Flash Download Start"', '#d29922');
log('But got: Only null bytes (0x00)', '#d29922');
log('', '');
log('📝 TRY THIS:', '#58a6ff');
log('1. Hold BURN button (5 seconds)', '#c9d1d9');
log('2. Keep holding BURN, press RST (2 seconds)', '#c9d1d9');
log('3. Release RST first', '#c9d1d9');
log('4. Then release BURN', '#c9d1d9');
log('5. Should see: "#Flash Download Start"', '#c9d1d9');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', '#f85149');
}
}
}
async function waitForNAKs(count = 2) {
log(`Waiting for ${count} NAK(s)...`);
let nakCount = 0;
const startTime = Date.now();
const timeout = 5000; // 5 seconds total timeout
while (nakCount < count && Date.now() - startTime < timeout) {
try {
const { value } = await readWithTimeout(200); // 200ms per byte timeout
if (!value || value.length === 0) continue;
for (let i = 0; i < value.length; i++) {
if (value[i] === NAK) {
nakCount++;
if (nakCount >= count) break;
} else {
// Log non-NAK bytes we're skipping
if (value[i] >= 0x20 && value[i] <= 0x7E) {
// Printable ASCII
log(` Skipping: '${String.fromCharCode(value[i])}'`, '#8b949e');
} else {
log(` Skipping: 0x${value[i].toString(16).padStart(2, '0')}`, '#8b949e');
}
}
}
} catch {
// Timeout - keep waiting
continue;
}
}
if (nakCount < count) {
throw new Error(`Timeout: only got ${nakCount}/${count} NAKs`);
}
log(`✓ Got ${count} NAK(s)`);
}
async function sendCommand(cmd, data = []) {
const packet = [cmd, ...data];
log(`→ CMD: 0x${cmd.toString(16)} [${packet.map(b => '0x' + b.toString(16)).join(' ')}]`, '#d29922');
await writer.write(new Uint8Array(packet));
}
// Special command sender for flashloader that waits for NAK first
async function sendFlashloaderCommand(cmd, data = [], timeoutMs = 1000, allowFailure = false) {
// Wait for and consume NAK from flashloader
const nakStart = Date.now();
while (Date.now() - nakStart < 2000) {
try {
const byte = await readByte();
if (byte === NAK) {
break;
}
} catch {}
}
// Send command
await sendCommand(cmd, data);
// Flashloader responds with ACK + NAK
const response = await readByteWithTimeout(timeoutMs);
if (response === ACK) {
log('← ACK (0x06)');
// Read the NAK that follows
try {
const nak = await readByteWithTimeout(500);
if (nak === NAK) {
log('← NAK (0x15) - ready for next command', '#8b949e');
}
} catch {
// Some commands might not send NAK after ACK
}
return { success: true, acked: true };
} else if (response === NAK && allowFailure) {
// Command not supported or failed - but continue if allowed
log(`← NAK (0x15) - command not supported/failed`, '#d29922');
return { success: false, acked: false };
}
throw new Error(`Expected ACK, got 0x${response.toString(16)}`);
}
async function waitForACK(timeoutMs = 1000, consumeNAKs = false) {
if (consumeNAKs) {
// For flashloader XMODEM: the device may send NAKs mixed with ACK
// Read with short timeout and look for ACK among the bytes
const startTime = Date.now();
let bytesRead = [];
while (Date.now() - startTime < timeoutMs) {
try {
const { value } = await readWithTimeout(50);
if (!value || value.length === 0) continue;
// Check each byte
for (let byte of value) {
bytesRead.push(byte);
if (byte === ACK) {
if (bytesRead.length > 1) {
// Show NAKs we skipped
const naks = bytesRead.filter(b => b === NAK).length;
if (naks > 0) {
log(`← Consumed ${naks} NAKs before ACK`, '#8b949e');
}
}
log('← ACK (0x06)');
return true;
}
}
} catch {
// Timeout on read - keep trying
continue;
}
}
// Timeout - show what we got
if (bytesRead.length > 0) {
log(`← Read ${bytesRead.length} bytes without ACK: ${bytesRead.slice(0, 20).map(b => '0x' + b.toString(16)).join(' ')}${bytesRead.length > 20 ? '...' : ''}`, '#d29922');
}
throw new Error(`Timeout waiting for ACK after ${timeoutMs}ms`);
}
// Normal mode for bootloader ROM
const response = await readByteWithTimeout(timeoutMs);
if (response === ACK) {
log('← ACK (0x06)');
return true;
}
throw new Error(`Expected ACK, got 0x${response.toString(16)}`);
}
async function readByteWithTimeout(timeoutMs = 1000) {
const { value } = await readWithTimeout(timeoutMs);
return value[0];
}
async function syncCommand() {
log('Sending SYNC command...');
await sendCommand(CMD_SYNC);
await waitForACK();
log('✓ SYNC complete');
}
function calculateChecksum(data) {
// 32-bit word sum for VERIFY command
let sum = 0;
for (let i = 0; i < data.length; i += 4) {
const word = (data[i] | (data[i+1] << 8) | (data[i+2] << 16) | (data[i+3] << 24)) >>> 0;
sum = (sum + word) >>> 0;
}
return sum;
}
function crc16Ccitt(data) {
// CRC-16/CCITT-FALSE (polynomial 0x1021, init 0x0000)
// This is what BW16 flashloader uses for XMODEM
let crc = 0x0000;
for (const byte of data) {
crc ^= (byte << 8);
for (let i = 0; i < 8; i++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ 0x1021;
} else {
crc = crc << 1;
}
crc &= 0xFFFF;
}
}
return crc;
}
async function purgeRX(ms = 300) {
// Simulate PURGE by reading and discarding all pending data
const start = Date.now();
let purged = 0;
while (Date.now() - start < ms) {
try {
const { value } = await readWithTimeout(50);
if (value && value.length > 0) {
purged += value.length;
}
} catch {
// Timeout is OK - continue purging
}
}
if (purged > 0) {
log(`🧹 Purged ${purged} bytes from RX buffer`, '#8b949e');
}
}
// CRC16-XMODEM (polynomial 0x1021) for XMODEM-CRC protocol
function crc16Xmodem(data) {
let crc = 0x0000;
for (const byte of data) {
crc ^= (byte << 8);
for (let i = 0; i < 8; i++) {
crc = (crc & 0x8000) ? (crc << 1) ^ 0x1021 : (crc << 1);
crc &= 0xFFFF;
}
}
return crc;
}
// Send RAW binary data with VampelRTL timing (NO XMODEM!)
async function sendRawBinary(data, description) {
const CHUNK_SIZE = 4096; // 4KB chunks like VampelRTL
const totalChunks = Math.ceil(data.length / CHUNK_SIZE);
log(`Sending ${description} as RAW binary (${totalChunks} chunks, ${data.length} bytes)...`);
log(`Using VampelRTL timing: 4KB chunks with 1ms delays`, '#d29922');
// Create Uint8Array once
const dataUint8 = new Uint8Array(data);
for (let i = 0; i < totalChunks; i++) {
const offset = i * CHUNK_SIZE;
const chunk = dataUint8.slice(offset, offset + CHUNK_SIZE);
// Send chunk
await writer.write(chunk);
// CRITICAL: 1ms delay between chunks (like VampelRTL Thread.Sleep(1))
if (i < totalChunks - 1) { // No delay after last chunk
await new Promise(r => setTimeout(r, 1));
}
// Update progress every 32 chunks (~128KB)
if ((i + 1) % 32 === 0 || i === totalChunks - 1) {
const percent = Math.round(((i + 1) / totalChunks) * 50) + 45;
const transferredKB = Math.round((offset + chunk.length) / 1024);
updateProgress(percent, `${i+1}/${totalChunks} chunks (${transferredKB}KB)`);
// Optional: Small pause every 128KB to "breathe"
if ((i + 1) % 128 === 0 && i < totalChunks - 1) {
await new Promise(r => setTimeout(r, 10));
}
}
}
updateProgress(95, 'Transfer complete');
log(`✓ ${description} transferred (VampelRTL timing)`);
// CRITICAL: Wait 100ms like VampelRTL (Thread.Sleep(100))
log('Waiting 100ms for flashloader to process...', '#d29922');
await new Promise(r => setTimeout(r, 100));
}
// Send RAW binary to specific flash address (for bootloaders + firmware)
async function sendXmodemToFlash(data, ramAddress, description) {
const SOH = 0x01; // 128 byte packets
const STX = 0x02; // 1024 byte packets
const EOT = 0x04; // End of transmission
const CMD_XMD = 0x07; // Start XMODEM
log(`Writing ${description} to RAM 0x${ramAddress.toString(16).toUpperCase()} (${data.byteLength} bytes)...`, '#d29922');
// CRITICAL: VampelRTL WaitResp consumes ALL bytes until ACK is found
log(` Sending CMD 0x07 to start XMODEM...`, '#8b949e');
await writer.write(new Uint8Array([CMD_XMD]));
// Wait for ACK (consume all bytes including NAKs until ACK found)
let foundAck = false;
let bytesConsumed = [];
const ackStartTime = Date.now();
while (!foundAck && Date.now() - ackStartTime < 5000) {
try {
const byte = await readByteWithTimeout(100);
if (byte !== null) {
bytesConsumed.push(byte);
if (byte === ACK) {
foundAck = true;
log(` ✓ ACK found (consumed ${bytesConsumed.length} bytes)`);
} else if (byte === NAK) {
log(` ← NAK consumed, waiting for ACK...`, '#8b949e');
}
}
} catch {}
}
if (!foundAck) {
log(` ⚠️ No ACK found, consumed: ${bytesConsumed.map(b => '0x'+b.toString(16)).join(' ')}`, '#d29922');
log(` ⚠️ Continuing anyway (VampelRTL style)...`, '#d29922');
}
// Small delay
await new Promise(r => setTimeout(r, 50));
log(` Sending XMODEM packets...`, '#8b949e');
// Send data in XMODEM packets
const dataUint8 = new Uint8Array(data);
let sequence = 1;
let offset = 0;
let packetsTotal = 0;
while (offset < data.byteLength) {
// Determine packet size
const remaining = data.byteLength - offset;
let packetSize, cmd;
if (remaining <= 128) {
packetSize = 128;
cmd = SOH;
} else {
packetSize = 1024;
cmd = STX;
}
// Read data for this packet
const readSize = Math.min(remaining, packetSize);
// Create packet data (pad with 0xFF)
const packetData = new Uint8Array(packetSize);
packetData.fill(0xFF);
for (let i = 0; i < readSize; i++) {
packetData[i] = dataUint8[offset + i];
}
// Build XMODEM packet: [CMD][SEQ][~SEQ][OFFSET:4][DATA][CHECKSUM]
const packet = new Uint8Array(3 + 4 + packetSize + 1);
// Header
packet[0] = cmd;
packet[1] = sequence & 0xFF;
packet[2] = (~sequence) & 0xFF;
// Offset (RAM address - VampelRTL sends RAM address)
const currentAddr = ramAddress + offset;
packet[3] = currentAddr & 0xFF;
packet[4] = (currentAddr >> 8) & 0xFF;
packet[5] = (currentAddr >> 16) & 0xFF;
packet[6] = (currentAddr >> 24) & 0xFF;
// Data
for (let i = 0; i < packetSize; i++) {
packet[7 + i] = packetData[i];
}
// Checksum: SUM from byte 3 to end (like VampelRTL CalcChecksum)
// VampelRTL: CalcChecksum(pkt, 3, pkt.Length)
// Means: sum from pkt[3] to pkt[pkt.Length-1]
let checksum = 0;
for (let i = 3; i < packet.length - 1; i++) {
checksum = (checksum + packet[i]) & 0xFF;
}
packet[packet.length - 1] = checksum;
// DETAILED DEBUG for first packet
if (packetsTotal === 0) {
log(` [DEBUG] First packet analysis:`, '#d29922');
log(` CMD: 0x${cmd.toString(16)} (${cmd === STX ? 'STX/1024' : 'SOH/128'})`, '#8b949e');
log(` SEQ: ${sequence}, ~SEQ: ${(~sequence) & 0xFF}`, '#8b949e');
log(` RAM Addr: 0x${currentAddr.toString(16).padStart(8, '0')}`, '#8b949e');
log(` Addr bytes: [${packet[3].toString(16).padStart(2, '0')} ${packet[4].toString(16).padStart(2, '0')} ${packet[5].toString(16).padStart(2, '0')} ${packet[6].toString(16).padStart(2, '0')}]`, '#8b949e');
log(` Data[0-15]: ${Array.from(packet.slice(7, 23)).map(b => b.toString(16).padStart(2, '0')).join(' ')}`, '#8b949e');
log(` Checksum: 0x${checksum.toString(16).padStart(2, '0')}`, '#8b949e');
log(` Total size: ${packet.length} bytes`, '#8b949e');
}
// Send packet with retry (up to 3 times)
let retries = 3;
let success = false;
while (retries > 0 && !success) {
await writer.write(packet);
// Wait for ACK (VampelRTL style - consume all bytes until ACK)
let foundPacketAck = false;
let bytesConsumed = [];
const packetStartTime = Date.now();
while (!foundPacketAck && Date.now() - packetStartTime < 2000) {
try {
const byte = await readByteWithTimeout(100);
if (byte !== null) {
bytesConsumed.push(byte);
if (byte === ACK) {
foundPacketAck = true;
success = true;
} else if (byte === NAK) {
// NAK means retry
break;
}
}
} catch {}
}
if (!foundPacketAck) {
retries--;
if (retries > 0) {
if (bytesConsumed.length > 0) {
log(` Packet ${sequence} got [${bytesConsumed.map(b => '0x'+b.toString(16)).join(',')}], retrying...`, '#d29922');
} else {
log(` Packet ${sequence} timeout, retrying...`, '#d29922');
}
}
}
}
if (!success) {
throw new Error(`Failed to send packet ${sequence} after 3 retries`);
}
// Update counters
sequence = (sequence + 1) % 256;
offset += packetSize; // ← Increment by packetSize (like VampelRTL)
packetsTotal++;
// Progress (every 16 packets = 16KB)
if (packetsTotal % 16 === 0 || offset >= data.byteLength) {
const percent = Math.round((offset / data.byteLength) * 100);
log(` ${description}: ${packetsTotal} packets (${percent}%)`, '#8b949e');
}
}
// 3. Send EOT
log(` Sending EOT...`, '#8b949e');
await writer.write(new Uint8Array([EOT]));
const eotAck = await readByteWithTimeout(1000);
if (eotAck !== ACK) {
log(` ⚠️ EOT got 0x${eotAck?.toString(16)} (expected ACK)`, '#d29922');
}
log(`✓ ${description} written via XMODEM (${packetsTotal} packets)`);
}
async function writeBlock(addr, data) {
// Use ROM bootloader protocol for both ROM and Flash
// Single packet: [CMD][SEQ][~SEQ][ADDR][DATA][CHECKSUM]
const BLOCK_SIZE = 1024; // Use 1024 for both
const blocks = Math.ceil(data.length / BLOCK_SIZE);
if (addr < 0x08000000) {
log(`Writing ${blocks} ROM blocks (${data.length} bytes) to 0x${addr.toString(16)}...`);
} else {
log(`Writing ${blocks} flash blocks (${data.length} bytes) to 0x${addr.toString(16)}...`);
}
for (let i = 0; i < blocks; i++) {
const offset = i * BLOCK_SIZE;
const chunk = data.slice(offset, offset + BLOCK_SIZE);
const padded = new Uint8Array(BLOCK_SIZE);
padded.set(chunk);
padded.fill(0xFF, chunk.length);
if (i === 0) {
const preview = Array.from(padded.slice(0, 32)).map(b => b.toString(16).padStart(2, '0')).join(' ');
log(`[DEBUG] First 32 bytes: ${preview}`, '#d29922');
}
const seq = (i + 1) & 0xFF;
const packet = new Uint8Array(1032);
packet[0] = CMD_WRITE;
packet[1] = seq;
packet[2] = (~seq) & 0xFF;
const targetAddr = addr + offset;
packet[3] = targetAddr & 0xFF;
packet[4] = (targetAddr >> 8) & 0xFF;
packet[5] = (targetAddr >> 16) & 0xFF;
packet[6] = (targetAddr >> 24) & 0xFF;
packet.set(padded, 7);
let checksum = 0xFF;
for (let j = 0; j < 1031; j++) {
checksum = (checksum + packet[j]) & 0xFF;
}
packet[1031] = checksum;
if (i === 0) {
log(`[DEBUG] Packet checksum: 0x${checksum.toString(16)}`, '#d29922');
}
await writer.write(packet);
await waitForACK(1000, false);
if (i % 100 === 0 || i === blocks - 1) {
updateProgress(Math.round((i + 1) / blocks * 100));
}
}
log(`✓ ${addr < 0x08000000 ? 'ROM' : 'Flash'} write complete`);
}
async function eraseFlash(addr, blocks) {
const totalBytes = blocks * 4096;
const sizeMB = (totalBytes / 1024 / 1024).toFixed(2);
// Align address to 4KB boundary like VampelRTL
let offset = addr & 0xFFF000;
log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, '#d29922');
log(`Erasing ${blocks} sectors (${sizeMB} MB) from 0x${offset.toString(16).padStart(8,'0')}`, '#d29922');
log(`⚠️ CRITICAL: Using VampelRTL method - 1 sector at a time`, '#d29922');
log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`, '#d29922');
// CRITICAL: VampelRTL erases 1 sector (4KB) at a time in a loop
// NOT all sectors in one command!
for (let i = 0; i < blocks; i++) {
const data = [
offset & 0xFF,
(offset >> 8) & 0xFF,
(offset >> 16) & 0xFF,
(offset >> 24) & 0xFF,
0x01, // ← ALWAYS erase 1 sector
0x00
];
const result = await sendFlashloaderCommand(CMD_ERASE, data, 60000, true);
if (!result.acked) {
log(`✗ Erase failed at sector ${i} (0x${offset.toString(16)})`, '#f85149');
return false;
}
offset += 4096; // Next sector
// Progress update every 64 sectors
if ((i + 1) % 64 === 0 || i === blocks - 1) {
const progress = Math.round(((i + 1) / blocks) * 100);
log(` Erased ${i + 1}/${blocks} sectors (${progress}%)`, '#8b949e');
}