-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcpinstaller.js
More file actions
2072 lines (1881 loc) · 86.8 KB
/
Copy pathcpinstaller.js
File metadata and controls
2072 lines (1881 loc) · 86.8 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
// SPDX-FileCopyrightText: 2023 Melissa LeBlanc-Williams for Adafruit Industries
//
// SPDX-License-Identifier: MIT
'use strict';
import { html } from 'https://cdn.jsdelivr.net/npm/lit-html/+esm';
import { map } from 'https://cdn.jsdelivr.net/npm/lit-html/directives/map/+esm';
import * as toml from "https://cdn.jsdelivr.net/npm/iarna-toml-esm@3.0.5/+esm"
import * as zip from "https://cdn.jsdelivr.net/npm/@zip.js/zip.js@2.6.65/+esm";
import { REPL } from 'https://cdn.jsdelivr.net/gh/adafruit/circuitpython-repl-js@3.2.1/repl.js';
import { InstallButton, ESP_ROM_BAUD, NotRomBootloaderError } from "./base_installer.js";
// TODO: Combine multiple steps together. For now it was easier to make them separate,
// but for ease of configuration, it would be work better to combine them together.
// For instance stepSelectBootDrive and stepCopyUf2 should always be together and in
// that order, but due to having handlers in the first of those steps, it was easier to
// just call nextStep() from the handler.
//
// TODO: Hide the log and make it accessible via the menu (future feature, output to console for now)
// May need to deal with the fact that the ESPTool uses Web Serial and CircuitPython REPL uses Web Serial
//
// TODO: Update File Operations to take advantage of the REPL FileOps class to allow non-CIRCUITPY drive access
const PREFERRED_BAUDRATE = 921600;
const COPY_CHUNK_SIZE = 64 * 1024; // 64 KB Chunks
const DEFAULT_RELEASE_LATEST = false; // Use the latest release or the stable release if not specified
const BOARD_DEFS = "https://adafruit-circuit-python.s3.amazonaws.com/esp32_boards.json";
const CSS_DIALOG_CLASS = "cp-installer-dialog";
const attrMap = {
"bootloader": "bootloaderUrl",
"uf2file": "uf2FileUrl",
"binfile": "binFileUrl"
}
export class CPInstallButton extends InstallButton {
constructor() {
super();
this.releaseVersion = "[version]";
this.boardName = "ESP32-based device";
this.boardIds = null;
this.selectedBoardId = null;
this.bootloaderUrl = null;
this.boardDefs = null;
this.uf2FileUrl = null;
this.binFileUrl = null;
this.releaseVersion = 0;
this.chipFamily = null;
this.dialogCssClass = CSS_DIALOG_CLASS;
this.dialogs = { ...this.dialogs, ...this.cpDialogs };
this.bootDriveHandle = null;
this.circuitpyDriveHandle = null;
this._bootDriveName = null;
this._serialPortName = null;
this.replSerialDevice = null;
this.repl = null;
this.fileCache = [];
this.reader = null;
this.writer = null;
this.tomlSettings = null;
this.init();
}
static get observedAttributes() {
return Object.keys(attrMap);
}
parseVersion(version) {
const versionRegex = /(\d+)\.(\d+)\.(\d+)(?:-([a-z]+)\.(\d+))?/;
const versionInfo = {};
let matches = version.match(versionRegex);
if (matches && matches.length >= 4) {
versionInfo.major = matches[1];
versionInfo.minor = matches[2];
versionInfo.patch = matches[3];
if (matches[4] && matches[5]) {
versionInfo.suffix = matches[4];
versionInfo.suffixVersion = matches[5];
} else {
versionInfo.suffix = "stable";
versionInfo.suffixVersion = 0;
}
}
return versionInfo;
}
sortReleases(releases) {
// Return a sorted list of releases by parsed version number
const sortHieratchy = ["major", "minor", "patch", "suffix", "suffixVersion"];
releases.sort((a, b) => {
const aVersionInfo = this.parseVersion(a.version);
const bVersionInfo = this.parseVersion(b.version);
for (let sortKey of sortHieratchy) {
if (aVersionInfo[sortKey] < bVersionInfo[sortKey]) {
return -1;
} else if (aVersionInfo[sortKey] > bVersionInfo[sortKey]) {
return 1;
}
}
return 0;
});
return releases;
}
async connectedCallback() {
// Load the Board Definitions before the button is ever clicked
const response = await fetch(BOARD_DEFS);
this.boardDefs = await response.json();
let boardIds = this.getAttribute("boardid")
if (!boardIds || boardIds.trim().length === 0) {
this.boardIds = Object.keys(this.boardDefs);
} else {
this.boardIds = boardIds.split(",");
}
// If there is only one board id, then select it by default
if (this.boardIds.length === 1) {
this.selectedBoardId = this.boardIds[0];
}
// If not provided, it will use the stable release if DEFAULT_RELEASE_LATEST is false
if (this.getAttribute("version")) {
this.releaseVersion = this.getAttribute("version");
}
super.connectedCallback();
}
async loadBoard(boardId) {
// Pull in the info from the json as the default values. These can be overwritten by the attributes.
let releaseInfo = null;
if (Object.keys(this.boardDefs).includes(boardId)) {
const boardDef = this.boardDefs[boardId];
this.chipFamily = boardDef.chipfamily;
if (boardDef.name) {
this.boardName = boardDef.name;
}
if (boardDef.bootloader) {
this.bootloaderUrl = this.updateBinaryUrl(boardDef.bootloader);
}
const sortedReleases = this.sortReleases(boardDef.releases);
if (this.releaseVersion) { // User specified a release
for (let release of sortedReleases) {
if (release.version == this.releaseVersion) {
releaseInfo = release;
break;
}
}
}
if (!releaseInfo) { // Release version not found or not specified
if (DEFAULT_RELEASE_LATEST) {
releaseInfo = sortedReleases[sortedReleases.length - 1];
} else {
releaseInfo = sortedReleases[0];
}
this.releaseVersion = releaseInfo.version;
}
if (releaseInfo.uf2file && !this.uf2FileUrl) {
this.uf2FileUrl = this.updateBinaryUrl(releaseInfo.uf2file);
}
if (releaseInfo.binfile && !this.binFileUrl) {
this.binFileUrl = this.updateBinaryUrl(releaseInfo.binfile);
}
}
// Nice to have for now
if (this.getAttribute("chipfamily")) {
this.chipFamily = this.getAttribute("chipfamily");
}
if (this.getAttribute("boardname")) {
this.boardName = this.getAttribute("boardname");
}
this.menuTitle = `CircuitPython Installer for ${this.boardName}`;
}
attributeChangedCallback(attribute, previousValue, currentValue) {
const classVar = attrMap[attribute];
this[classVar] = currentValue ? this.updateBinaryUrl(currentValue) : null;
}
updateBinaryUrl(url) {
//if (location.hostname == "localhost") {
if (url) {
url = url.replace("https://downloads.circuitpython.org/", "https://adafruit-circuit-python.s3.amazonaws.com/");
}
//}
return url;
}
// These are a series of the valid steps that should be part of a program flow
// Some steps currently need to be grouped together
flows = {
uf2FullProgram: { // Native USB Install
label: `Full CircuitPython [version] Install`,
// stepFsapiCheck sits right after the welcome dialog so the
// user sees the normal welcome first, then immediately gets
// the "your browser can't finish automatically" dialog if
// they're on Firefox. The "Continue Manually" path swaps
// the drive-picker tail of this flow for the manual
// variants via continueManuallyHandler. (Issue #24)
steps: [this.stepWelcome, this.stepFsapiCheck, this.stepSerialConnect, this.stepConfirm, this.stepEraseAll, this.stepBootloader, this.stepSelectBootDrive, this.stepCopyUf2, this.stepSelectCpyDrive, this.stepCredentials, this.stepSuccess],
isEnabled: async () => { return this.hasNativeUsb() && !!this.bootloaderUrl && !!this.uf2FileUrl },
},
binFullProgram: { // Non-native USB Install (Once we have boot drive disable working, we can remove hasNativeUsb() check)
label: `Full CircuitPython [version] Install`,
steps: [this.stepWelcome, this.stepSerialConnect, this.stepConfirm, this.stepEraseAll, this.stepFlashBin, this.stepSetupRepl, this.stepCredentials, this.stepSuccess],
isEnabled: async () => { return !this.hasNativeUsb() && !!this.binFileUrl },
},
uf2Only: { // Upgrade when Bootloader is already installer
label: `Install CircuitPython [version] UF2 Only`,
steps: [this.stepWelcome, this.stepSelectBootDrive, this.stepCopyUf2, this.stepSelectCpyDrive, this.stepCredentials, this.stepSuccess],
// Every step in this flow needs the File System Access API:
// we never flash anything ourselves, we just pick the BOOT
// drive, copy the UF2 onto it, then pick CIRCUITPY and write
// settings.toml. With no FSAPI there's literally nothing the
// installer can do, so hide the flow on Firefox rather than
// present a button that opens a dialog and silently fails.
// (Issue #24)
isEnabled: async () => { return this.hasNativeUsb() && !!this.uf2FileUrl && this.hasFileSystemAccess },
},
binOnly: {
label: `Install CircuitPython [version] Bin Only`,
steps: [this.stepWelcome, this.stepSerialConnect, this.stepConfirm, this.stepEraseAll, this.stepFlashBin, this.stepSuccess],
isEnabled: async () => { return !!this.binFileUrl },
},
bootloaderOnly: { // Used to allow UF2 Upgrade/Install
label: "Install Bootloader Only",
steps: [this.stepWelcome, this.stepSerialConnect, this.stepConfirm, this.stepEraseAll, this.stepBootloader, this.stepSuccess],
isEnabled: async () => { return this.hasNativeUsb() && !!this.bootloaderUrl },
},
credentialsOnlyRepl: { // Update via REPL
label: "Update WiFi credentials",
steps: [this.stepWelcome, this.stepSetupRepl, this.stepCredentials, this.stepSuccess],
isEnabled: async () => { return !this.hasNativeUsb() },
},
credentialsOnlyDrive: { // Update via CIRCUITPY Drive
label: "Update WiFi credentials",
steps: [this.stepWelcome, this.stepSelectCpyDrive, this.stepCredentials, this.stepSuccess],
// Drive-based credential update needs to pick the CIRCUITPY
// drive and write settings.toml. With no FSAPI we can't do
// either, so hide on Firefox. Native-USB users on Firefox
// hit the no-flows menu state; non-native-USB users still
// get credentialsOnlyRepl (which talks over Web Serial and
// doesn't need FSAPI at all). (Issue #24)
isEnabled: async () => { return this.hasNativeUsb() && this.hasFileSystemAccess },
}
}
// This is the data for the CircuitPython specific dialogs. Some are reused.
cpDialogs = {
boardSelect: {
closeable: true,
template: (data) => html`
<p>
There are multiple boards are available. Select the board you have:
</p>
<p>
<select id="availableBoards">
<option value="0"> - boards - </option>
${map(data.boards, (board, index) => html`<option value="${board.id}" ${board.id == data.default ? "selected" : ""}>${board.name}</option>`)}
</select>
</p>
`,
buttons: [{
label: "Select Board",
onClick: this.selectBoardHandler,
isEnabled: async () => { return this.currentDialogElement.querySelector("#availableBoards").value != "0" },
}],
},
welcome: {
closeable: true,
template: (data) => html`
<h3>Web Firmware Installer</h3>
<p>
Welcome!
This tool will install a UF2 bootloader and/or CircuitPython on your ${data.boardName}.
</p>
<p>
This tool is <strong>experimental</strong>.
If you experience any issues, feel free to check out
<a href="https://github.com/adafruit/circuitpython-org/issues">https://github.com/adafruit/circuitpython-org/issues</a>
to see if the issue you are experiencing has already been reported.
If not, feel free to open a new issue.
If you do see the same issue and are able to contribute additional information,
that would be appreciated.
</p>
<p>
If you are unable to use this tool,
then the manual installation methods like the
<a href="https://adafruit.github.io/Adafruit_WebSerial_ESPTool/">Adafruit WebSerial Tool</a>
and esptool.py should still work.
</p>
`
},
espSerialConnect: {
closeable: true,
template: (data) => html`
<h3>
Connect to Your Board
</h3>
<ol>
<li>
<p>
Plug your board into this computer.
<em>Make sure the USB cable is good for data sync, and is not a charge-only cable.</em>
</p>
</li>
<li>
<p>
<strong>Put your board into ROM bootloader mode</strong>,
by holding down the BOOT button (sometimes marked "B0"),
and clicking the RESET button (sometimes marked "RST").
If your board doesn't have a BOOT button, just press RESET.
</p>
</li>
<li>
<p>
<button id="butConnect" type="button" @click=${this.espToolConnectHandler.bind(this)}>Connect</button>
Click this button to open the Web Serial connection menu and choose the serial port for this board.
</p>
<p>
There may be many devices listed, such as your remembered Bluetooth peripherals, anything else plugged into USB, etc.
If you aren't sure which to choose, look for words like "USB", "UART", "JTAG", and "Bridge Controller".
There may be more than one right option depending on your system configuration. Experiment if needed.
</p>
</li>
</ul>
`,
buttons: [this.previousButton, {
label: "Next",
onClick: this.nextStep,
isEnabled: async () => { return (this.currentStep < this.currentFlow.steps.length - 1) && this.connected == this.connectionStates.CONNECTED },
onUpdate: async (e) => { this.currentDialogElement.querySelector("#butConnect").innerText = this.connected; },
}],
},
// Shown when the user picks a serial port that's clearly not
// an ESP32 ROM bootloader (e.g. TinyUF2 CDC, a running
// CircuitPython console). This is a user-recoverable hiccup,
// not an install failure -- they just need to put the board
// into ROM bootloader mode and try again -- so we show a
// dialog with a single Continue button that drops them back
// on the serial-connect dialog of whichever flow they're in.
// (Issue #20 / #24)
notRomBootloader: {
closeable: true,
template: (data) => html`
<h3>Not in ROM Bootloader mode</h3>
${(data && data.message ? data.message.split("\n\n") : [])
.filter((p) => p.trim().length > 0)
.map((p) => html`<p>${p}</p>`)}
`,
buttons: [{
label: "OK",
onClick: async (e) => {
this.closeDialog();
// Re-run whatever step we're currently sitting on
// (which is the flow's serial-connect step). This
// re-shows the Connect to Your Board dialog so
// the user can pick the right port this time.
if (this.currentFlow && typeof this.currentFlow.steps[this.currentStep] === "function") {
await this.currentFlow.steps[this.currentStep].bind(this)();
}
},
}],
},
confirm: {
template: (data) => html`
<h3>Erase Flash</h3>
<p>Now, optionally, erase everything on the ${data.boardName}.</p>
`,
buttons: [
this.previousButton,
{
label: "Skip Erase",
onClick: async (e) => { if (confirm("Skipping the erase step may cause issues and is not recommended. Continue?")) { await this.advanceSteps(2); }},
},
{
label: "Continue",
onClick: this.nextStep,
}
],
},
// Shown by stepWelcome (in place of the normal welcome dialog)
// when the browser doesn't expose window.showDirectoryPicker
// (currently Firefox on every platform). User picks between
// switching browsers for the automated path, or staying on
// Firefox and copying the UF2 manually via
// continueManuallyHandler. Shown up front so the user finds out
// BEFORE clicking through Erase + Bootloader. (Issue #24)
fsapiUnavailable: {
closeable: true,
template: (data) => html`
<h3>Your browser can't finish automatically</h3>
<p>
Your browser doesn't support the
<strong>FileSystem API</strong>, which this installer
normally uses to copy the CircuitPython UF2 file onto
your board's bootloader drive and to write your WiFi
settings to <code>settings.toml</code>.
</p>
<p>You have a few options:</p>
<ul>
<li>
<strong>Use another browser.</strong>
Close this dialog, then re-open this page in
Chrome, Edge, or Opera (version 89 or newer).
Those browsers support the FileSystem API and
will copy CircuitPython and set up WiFi for you
automatically.
</li>
<li>
<strong>Continue here and copy manually.</strong>
We'll guide you through downloading the
CircuitPython UF2 file and dragging it onto your
board's bootloader drive yourself. WiFi setup
can't be automated this way, but we'll show you
how to edit <code>settings.toml</code> by hand
once your board is running CircuitPython.
</li>
${data && data.binAvailable ? html`
<li>
<strong>Install the .bin instead.</strong>
We can flash CircuitPython directly over USB
without using the FileSystem API at all.
<em>However</em>, this skips installing the UF2
bootloader, so you won't have the drag-and-drop
BOOT drive for future firmware updates —
you'll need to come back here (or use a browser
with the FileSystem API) every time you want to
change CircuitPython versions.
</li>
` : html``}
</ul>
`,
buttons: [{
label: "Use Another Browser",
onClick: async (e) => {
this.closeDialog();
},
}, {
label: "Install .bin Instead",
onClick: this.installBinInsteadHandler,
// Show whenever a .bin firmware file is configured for
// this board. We deliberately bypass
// binFullProgram.isEnabled() (which gates on
// !hasNativeUsb()) because this dialog is the user's
// informed-consent escape hatch: they understand the
// tradeoff (no UF2 bootloader) and want to flash
// CircuitPython anyway. The menu still uses
// isEnabled() so this option stays hidden from normal
// browsing. Display set via onUpdate because
// base_installer's isEnabled hook only toggles
// .disabled and we want the button gone, not greyed.
onUpdate: async (e) => {
e.target.style.display = !!this.binFileUrl ? "" : "none";
},
}, {
label: "Continue Manually",
onClick: this.continueManuallyHandler,
}],
},
// Manual UF2 copy step shown to Firefox users who chose
// "Continue Manually" in fsapiUnavailable. We hand them a
// direct download link to the UF2 file (we already have
// uf2FileUrl) and tell them how to drag it onto the BOOT
// drive. Advance is on a "Next" button rather than a folder
// picker, since we can't programmatically observe the copy.
manualBootCopy: {
closeable: true,
template: (data) => html`
<h3>Copy CircuitPython onto the ${data.drivename} drive</h3>
<ol>
<li>
<p>
<strong>Reset your board.</strong> Press the
RESET button once. A new drive named
<code>${data.drivename}</code> should appear
on your computer in a few seconds.
</p>
</li>
<li>
<p>
<strong>Download the CircuitPython UF2 file.</strong>
<a href="${data.uf2FileUrl}" download target="_blank" rel="noopener">
Download <code>${data.uf2FileName}</code>
</a>
</p>
</li>
<li>
<p>
<strong>Drag the downloaded UF2 file onto the
<code>${data.drivename}</code> drive.</strong>
The drive will disappear when the copy is
finished and the board reboots into
CircuitPython.
</p>
</li>
</ol>
<p>
Click <strong>Next</strong> once you've dragged the
file onto the drive.
</p>
`,
buttons: [this.previousButton, this.nextButton],
},
// Lightweight "waiting for CIRCUITPY" beat between the manual
// copy and the success screen. Pure-instructional since we
// can't actually detect the drive without FSAPI.
manualCircuitPyWait: {
closeable: true,
template: (data) => html`
<h3>Waiting for CIRCUITPY</h3>
<p>
Once your board finishes copying CircuitPython, a new
drive named <code>CIRCUITPY</code> should appear in a
few seconds.
</p>
<p>
If it doesn't appear, the drive may have been renamed
or disabled in <code>boot.py</code> on a previous
install. You can still continue — CircuitPython
is running on your board either way.
</p>
<p>
Click <strong>Next</strong> when you're ready to wrap
up.
</p>
`,
buttons: [this.previousButton, this.nextButton],
},
// Manual-mode success dialog. Replaces stepSuccess for the
// Firefox manual path since we never set up WiFi and have no
// ip / hostname info to show. Walks the user through editing
// settings.toml themselves so they're not left wondering.
manualSuccess: {
closeable: true,
template: (data) => html`
<h3>CircuitPython is installed!</h3>
<p>
Your board should now be running CircuitPython. If it
doesn't reboot automatically, press the RESET button
once.
</p>
<p>
<strong>To set up WiFi:</strong> open the
<code>CIRCUITPY</code> drive and create or edit a
file called <code>settings.toml</code> in the root.
Add lines like:
</p>
<pre style="white-space: pre; font-family: monospace;">CIRCUITPY_WIFI_SSID = "your-network"
CIRCUITPY_WIFI_PASSWORD = "your-password"
CIRCUITPY_WEB_API_PASSWORD = "passw0rd"
CIRCUITPY_WEB_API_PORT = 80</pre>
<p>
Save the file, then press RESET on your board. Once
the board reconnects to WiFi you can edit code in a
browser via the
<a href="https://code.circuitpython.org/" target="_blank" rel="noopener">CircuitPython web code editor</a>.
</p>
`,
buttons: [this.closeButton],
},
bootDriveSelect: {
closeable: true,
template: (data) => html`
<h3>Select the ${data.drivename} Drive</h3>
<ol>
<li>
<p>
<strong>Reset your board</strong> if you just installed the UF2 bootloader,
by pressing the RESET button.
If you already had the UF2 bootloader installed,
you may need to double-click the RESET button to start up the UF2 bootloader.
</p>
</li>
<li>
<p>
<button id="butSelectBootDrive" type="button" @click=${this.bootDriveSelectHandler.bind(this)}>Select ${data.drivename} Drive</button>
Select the ${data.drivename} drive where the UF2 file will be copied.
</p>
</li>
</ul>
`,
buttons: [],
},
circuitpyDriveSelect: {
closeable: true,
template: (data) => html`
<h3>Select the CIRCUITPY Drive</h3>
<ul>
<li>
<p>
<button id="butSelectCpyDrive" type="button" @click=${this.circuitpyDriveSelectHandler.bind(this)}>Select CIRCUITPY Drive</button>
Select the CIRCUITPY Drive.
You may need to wait a few seconds for it to appear.
If you don't see your CIRCUITPY drive, it may be disabled in boot.py or you may have previously renamed it.
</p>
</li>
</ul>
`,
buttons: [],
},
actionWaiting: {
template: (data) => html`
<p class="centered">${data.action}</p>
<div class="loader"><div></div><div></div><div></div><div></div></div>
`,
buttons: [],
},
actionProgress: {
template: (data) => html`
<p>${data.action}</p>
<progress id="stepProgress" max="100" value="${data.percentage}"> ${data.percentage}% </progress>
`,
buttons: [],
},
cpSerial: {
closeable: true,
template: (data) => html`
<h3>Reconnect to serial</h3>
<ul>
<li>
<button id="butConnect" type="button" @click=${this.cpSerialConnectHandler.bind(this)}>Connect</button>
Click this button to open the Web Serial connection menu.
If it is already connected, you can press it again if you need to select a different port.
</li>
</ul>
</p>
<p>${data.serialPortInstructions}</p>
`,
buttons: [this.previousButton, {
label: "Next",
onClick: this.nextStep,
isEnabled: async () => { return (this.currentStep < this.currentFlow.steps.length - 1) && !!this.replSerialDevice; },
onUpdate: async (e) => { this.currentDialogElement.querySelector("#butConnect").innerText = !!this.replSerialDevice ? "Connected" : "Connect"; },
}],
},
credentials: {
closeable: true,
template: (data) => html`
<h3>Fill in settings.toml</h3>
<p>
This step will write your network credentials to the settings.toml file on CIRCUITPY.
Make sure your board is running CircuitPython.
</p>
<p>
If you want to skip this step and fill in settings.toml later,
just close this dialog.
</p>
<fieldset>
<div class="field">
<label for="circuitpy_wifi_ssid">WiFi Network Name (SSID):</label>
<input id="circuitpy_wifi_ssid" class="setting-data" type="text" placeholder="WiFi SSID" value="${data.wifi_ssid}" />
</div>
<div class="field">
<label for="circuitpy_wifi_password">WiFi Password:</label>
<input id="circuitpy_wifi_password" class="setting-data" type="password" placeholder="WiFi Password" value="${data.wifi_password}" />
</div>
<div class="field">
<label for="circuitpy_web_api_password">Web Workflow API Password:</label>
<input id="circuitpy_web_api_password" class="setting-data" type="password" placeholder="Web Workflow API Password" value="${data.api_password}" />
</div>
<div class="field">
<label for="circuitpy_web_api_port">Web Workflow API Port:</label>
<input id="circuitpy_web_api_port" class="setting-data" type="number" min="0" max="65535" placeholder="Web Workflow API Port" value="${data.api_port}" />
</div>
${data.mass_storage_disabled === true || data.mass_storage_disabled === false ?
html`<div class="field">
<label for="circuitpy_drive"><input id="circuitpy_drive" class="setting" type="checkbox" value="disabled" ${data.mass_storage_disabled ? "checked" : ""} />Disable CIRCUITPY Drive (Required for write access)</label>
</div>` : ''}
</fieldset>
`,
buttons: [this.previousButton, {
label: "Next",
onClick: this.saveCredentials,
}]
},
success: {
closeable: true,
template: (data) => html`
<p>Successfully Completed</p>
<p>If your device doesn't reboot automatically press the reset button once.</p>
${data.ip ?
html`<p>
You can edit files by going to <a href="http://${data.ip}/code/">http://${data.ip}/code/</a>.
</p>` : ''}
`,
buttons: [this.closeButton],
},
error: {
closeable: true,
template: (data) => {
// Split the message on blank lines so callers can pass
// multi-paragraph error text (e.g. an explanation followed
// by remediation instructions) and have it render as
// separate paragraphs in the dialog rather than one wall
// of text. Single newlines are preserved as line breaks
// within a paragraph via CSS white-space: pre-line.
const paragraphs = String(data.message || "").split(/\n{2,}/);
return html`
${map(paragraphs, (p) => html`<p style="white-space: pre-line;">${p}</p>`)}
`;
},
buttons: [this.closeButton],
},
warning: {
closeable: true,
// Same paragraph-splitting behavior as the error dialog.
// Visually identical for now but kept separate so future
// styling (icon, color) can differentiate user-recoverable
// hiccups from real install errors.
template: (data) => {
const paragraphs = String(data.message || "").split(/\n{2,}/);
return html`
${map(paragraphs, (p) => html`<p style="white-space: pre-line;">${p}</p>`)}
`;
},
buttons: [this.closeButton],
},
}
getBoardName(boardId) {
if (Object.keys(this.boardDefs).includes(boardId)) {
return this.boardDefs[boardId].name;
}
return null;
}
getBoardOptions() {
let options = [];
for (let boardId of this.boardIds) {
options.push({id: boardId, name: this.getBoardName(boardId)});
}
options.sort((a, b) => {
let boardA = a.name.trim().toLowerCase();
let boardB = b.name.trim().toLowerCase();
if (boardA < boardB) {
return -1;
}
if (boardA > boardB) {
return 1;
}
return 0;
});
return options;
}
////////// STEP FUNCTIONS //////////
async stepWelcome() {
// continueManuallyHandler mutates currentFlow.steps in place to
// graft on the manual sub-flow. Since runFlow doesn't clone the
// step array, that mutation would persist across runs and break
// a subsequent automated run on Chrome. Snapshot the original
// step list the first time we see each flow and restore it on
// every welcome step so each run starts fresh. (Issue #24)
if (this.currentFlow) {
if (!this.currentFlow._originalSteps) {
this.currentFlow._originalSteps = this.currentFlow.steps.slice();
} else {
this.currentFlow.steps = this.currentFlow._originalSteps.slice();
}
// If installBinInsteadHandler set this flag on the bin flow
// and we're now running stepWelcome via Previous from
// stepSerialConnect, redirect to uf2FullProgram's welcome
// so the user lands back where they started. Clear the
// flag whether we redirect or not so that a subsequent
// fresh entry to the bin flow doesn't accidentally bounce.
if (this.currentFlow._returnToUf2Welcome) {
this.currentFlow._returnToUf2Welcome = false;
const uf2Flow = this.flows.uf2FullProgram;
if (uf2Flow) {
this.currentFlow = uf2Flow;
this.currentStep = 0;
await this.currentFlow.steps[this.currentStep].bind(this)();
return;
}
}
}
// Display Welcome Dialog
this.showDialog(this.dialogs.welcome, {boardName: this.boardName});
}
// FSAPI capability gate for uf2FullProgram, run immediately after
// stepWelcome. On browsers with the File System Access API this is
// a no-op pass-through; on Firefox (no FSAPI) it pops the
// fsapiUnavailable dialog and stops here. The user chooses Use
// Another Browser / Install .bin Instead / Continue Manually. The
// bin-based flows and the FSAPI-only flows don't include this
// step: bin flows don't touch FSAPI, and the FSAPI-only flows are
// already hidden from the menu when the API is missing. (Issue #24)
async stepFsapiCheck() {
if (this.hasFileSystemAccess) {
await this.nextStep();
return;
}
this.logMsg("FileSystem API not available; offering manual UF2 copy fallback.");
// Tell the dialog whether the .bin fallback is actually
// available for this board (i.e. a .bin URL is configured), so
// it can include the .bin bullet and button. We bypass
// binFullProgram.isEnabled() on purpose here because this
// dialog is the user's informed-consent path: even native-USB
// boards (which the menu would normally route through the UF2
// flow) get the option to flash the raw .bin when their
// browser can't drive the UF2 path. Button visibility is
// gated by the same predicate via an onUpdate hook. (Issue #24)
const binAvailable = !!this.binFileUrl;
this.showDialog(this.dialogs.fsapiUnavailable, { binAvailable });
}
async stepSerialConnect() {
// Display Serial Connect Dialog
this.showDialog(this.dialogs.espSerialConnect);
}
async stepConfirm() {
// Display Confirm Dialog
this.showDialog(this.dialogs.confirm, {boardName: this.boardName});
}
async stepEraseAll() {
// Display Erase Dialog
this.showDialog(this.dialogs.actionWaiting, {
action: "Erasing Flash...",
});
try {
await this.esploader.eraseFlash();
} catch (err) {
this.errorMsg("Unable to finish erasing Flash memory. Please try again.");
}
await this.nextStep();
}
async stepFlashBin() {
if (!this.binFileUrl) {
// We shouldn't be able to get here, but just in case
this.errorMsg("Missing bin file URL. Please make sure the installer button has this specified.");
return;
}
await this.downloadAndInstall(this.binFileUrl);
// The MD5 verification step inside downloadAndInstall reads the entire
// flash back, and stepSetupRepl below does a DTR/RTS reset + REPL wake.
// Both can take several seconds, so swap to a waiting indicator so the
// user doesn't think the wizard is stuck on "Flashing 100%".
this.showDialog(this.dialogs.actionWaiting, {
action: "Resetting the board and opening the REPL...",
});
await this.espHardReset();
await this.nextStep();
}
async stepBootloader() {
if (!this.bootloaderUrl) {
// We shouldn't be able to get here, but just in case
this.errorMsg("Missing bootloader file URL. Please make sure the installer button has this specified.");
return;
}
// Display Bootloader Dialog
await this.downloadAndInstall(this.bootloaderUrl, 'combined.bin', true);
await this.nextStep();
}
// Manual-copy variant of stepSelectBootDrive + stepCopyUf2 combined.
// Hands the user a download link for the UF2 file and instructions
// for dragging it onto the BOOT drive themselves, since we can't
// open the drive programmatically without FSAPI.
async stepManualBootCopy() {
const bootloaderVolume = await this.getBootDriveName();
// Pull a friendly filename out of the URL so the download
// button shows something more useful than just "Download".
let uf2FileName = "CircuitPython.uf2";
try {
const urlPath = new URL(this.uf2FileUrl, window.location.href).pathname;
const tail = urlPath.split("/").filter(Boolean).pop();
if (tail) {
uf2FileName = tail;
}
} catch (e) {
// Fall back to the default if URL parsing fails for any
// reason; we'd rather render a generic name than a broken
// dialog.
}
this.showDialog(this.dialogs.manualBootCopy, {
drivename: bootloaderVolume ? bootloaderVolume : "Bootloader",
uf2FileUrl: this.uf2FileUrl,
uf2FileName: uf2FileName,
});
}
// Manual-copy variant of the post-copy wait. Pure instructional;
// user clicks Next when they're ready to move on.
async stepManualCircuitPyWait() {
this.showDialog(this.dialogs.manualCircuitPyWait);
}
// Manual-copy success page. Tells the user how to set up WiFi
// by editing settings.toml themselves, since the auto-credentials
// step doesn't run in manual mode.
async stepManualSuccess() {
this.showDialog(this.dialogs.manualSuccess);
}
async stepSelectBootDrive() {
const bootloaderVolume = await this.getBootDriveName();
if (bootloaderVolume) {
this.logMsg(`Waiting for user to select a bootloader volume named ${bootloaderVolume}`);
}
// Display Select Bootloader Drive Dialog
this.showDialog(this.dialogs.bootDriveSelect, {
drivename: bootloaderVolume ? bootloaderVolume : "Bootloader",
});
}
async stepSelectCpyDrive() {
this.logMsg(`Waiting for user to select CIRCUITPY drive`);
// Display Select CIRCUITPY Drive Dialog
this.showDialog(this.dialogs.circuitpyDriveSelect);
}
async stepCopyUf2() {
if (!this.bootDriveHandle) {
this.errorMsg("No boot drive selected. stepSelectBootDrive should preceed this step.");
return;
}
// Display Progress Dialog
this.showDialog(this.dialogs.actionProgress, {
action: `Copying ${this.uf2FileUrl}...`,
});
// Do a copy and update progress along the way
await this.downloadAndCopy(this.uf2FileUrl);
// Once done, call nextstep
await this.nextStep();
}
async stepSetupRepl() {
// Don't close the SerialPort between flash and REPL. On Pi 5 + CP2104
// (and likely other USB-serial bridges) port.close() can hang
// indefinitely after esptool-js's transport.disconnect(), and even
// after a successful reopen the device often goes silent. Instead,
// release esptool-js's hold on the port (reader/writer locks) WITHOUT
// closing it, then reuse the same open port directly for REPL. The
// port is already at 115200 baud, which is what CircuitPython REPL
// uses. (Issue #22)
const reusablePort = (this.transport && this.transport.device) || this.device;
if (reusablePort) {
try {
// Release esptool-js's reader/writer locks without closing.
if (this.transport) {
try {
if (this.transport.reader) {
try { await this.transport.reader.cancel(); } catch (e) { /* ignore */ }
try { this.transport.reader.releaseLock(); } catch (e) { /* ignore */ }
this.transport.reader = undefined;
}
if (this.transport.writer) {
try { this.transport.writer.releaseLock(); } catch (e) { /* ignore */ }
this.transport.writer = undefined;
}
} catch (e) {
console.warn("Could not release esptool-js locks (continuing):", e);
}
// Drop our refs to the transport but DO NOT call its
// disconnect() method (which would close the port).
this.transport = null;
this.device = null;
this.chip = null;
this.updateEspConnected(this.connectionStates.DISCONNECTED);
}
this.replSerialDevice = reusablePort;
// The port is currently at the flash baud (e.g. 921600)
// and Web Serial doesn't support changing baud on an open
// port, so we must close and reopen at REPL baud (115200).
// close() can hang on Pi/CP2104 so we race it with a timeout
// and continue regardless.
try {
await Promise.race([
reusablePort.close(),
new Promise((_, reject) => setTimeout(() => reject(new Error("close() timeout")), 2500)),
]);
} catch (err) {
// close() can hang on CP2104; we proceed regardless.