-
Notifications
You must be signed in to change notification settings - Fork 1
/
cpinstaller.js
1356 lines (1180 loc) · 50.8 KB
/
cpinstaller.js
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 { default as CryptoJS } from "https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/+esm";
import { REPL } from 'https://cdn.jsdelivr.net/gh/adafruit/circuitpython-repl-js@3.2.1/repl.js';
import { InstallButton, ESP_ROM_BAUD } 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.updateBinaryUrl(releaseInfo.uf2file);
}
if (releaseInfo.binfile) {
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`,
steps: [this.stepWelcome, 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],
isEnabled: async () => { return this.hasNativeUsb() && !!this.uf2FileUrl },
},
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],
isEnabled: async () => { return this.hasNativeUsb() },
}
}
// 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`
<p>
Welcome to the CircuitPython Installer. This tool will install CircuitPython on your ${data.boardName}.
</p>
<p>
This tool is <strong>new</strong> and <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 somebody has already submitted the same issue you are experiencing. 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 should still work.
</p>
`
},
espSerialConnect: {
closeable: true,
template: (data) => html`
<p>
Make sure your board is plugged into this computer via a Serial connection using a USB Cable.
</p>
<ul>
<li><em><strong>NOTE:</strong> A lot of people end up using charge-only USB cables and it is very frustrating! Make sure you have a USB cable you know is good for data sync.</em></li>
</ul>
<p>
<button id="butConnect" type="button" @click=${this.espToolConnectHandler.bind(this)}>Connect</button>
Click this button to open the Web Serial connection menu.
</p>
<p>There may be many devices listed, such as your remembered Bluetooth peripherals, anything else plugged into USB, etc.</p>
<p>
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>
`,
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; },
}],
},
confirm: {
template: (data) => html`
<p>This will overwrite 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,
}
],
},
bootDriveSelect: {
closeable: true,
template: (data) => html`
<p>
Please select the ${data.drivename} Drive where the UF2 file will be copied.
</p>
<p>
If you just installed the bootloader, you may need to reset your board. If you already had the bootloader installed,
you may need to double press the reset button.
</p>
<p>
<button id="butSelectBootDrive" type="button" @click=${this.bootDriveSelectHandler.bind(this)}>Select ${data.drivename} Drive</button>
</p>
`,
buttons: [],
},
circuitpyDriveSelect: {
closeable: true,
template: (data) => html`
<p>
Please select the CIRCUITPY Drive. If you don't see your CIRCUITPY drive, it may be disabled in boot.py or you may have renamed it at some point.
</p>
<p>
<button id="butSelectCpyDrive" type="button" @click=${this.circuitpyDriveSelectHandler.bind(this)}>Select CIRCUITPY Drive</button>
</p>
`,
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`
<p>
The next step is to write your credentials to settings.toml. Make sure your board is running CircuitPython. <strong>If you just installed CircuitPython, you may to reset the board first.</strong>
</p>
<p>
<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, pressing again will allow you to select a different port.
</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`
<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>
${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) => html`
<p>Installation Error: ${data.message}</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() {
// Display Welcome Dialog
this.showDialog(this.dialogs.welcome, {boardName: this.boardName});
}
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);
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();
}
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() {
// TODO: Try and reuse the existing connection so user doesn't need to select it again
/*if (this.device) {
this.replSerialDevice = this.device;
await this.setupRepl();
}*/
const serialPortName = await this.getSerialPortName();
let serialPortInstructions ="There may be several devices listed. If you aren't sure which to choose, look for one that includes the name of your microcontroller.";
if (serialPortName) {
serialPortInstructions =`There may be several devices listed, but look for one called something like ${serialPortName}.`
}
this.showDialog(this.dialogs.cpSerial, {
serialPortInstructions: serialPortInstructions
});
}
async stepCredentials() {
// We may want to see if the board has previously been set up and fill in any values from settings.toml and boot.py
this.tomlSettings = await this.getCurrentSettings();
console.log(this.tomlSettings);
const parameters = {
wifi_ssid: this.getSetting('CIRCUITPY_WIFI_SSID'),
wifi_password: this.getSetting('CIRCUITPY_WIFI_PASSWORD'),
api_password: this.getSetting('CIRCUITPY_WEB_API_PASSWORD', 'passw0rd'),
api_port: this.getSetting('CIRCUITPY_WEB_API_PORT', 80),
}
if (this.hasNativeUsb()) {
// TODO: Currently the control is just disabled and not used because we don't have anything to modify boot.py in place.
// Setting mass_storage_disabled to true/false will display the checkbox with the appropriately checked state.
//parameters.mass_storage_disabled = true;
// This can be updated to use FileOps for ease of implementation
}
// Display Credentials Request Dialog
this.showDialog(this.dialogs.credentials, parameters);
}
async stepSuccess() {
let deviceHostInfo = {};
if (this.repl) {
await this.repl.waitForPrompt();
// If we were setting up Web Workflow, we may want to provide a link to code.circuitpython.org
if (this.currentFlow || this.currentFlow.steps.includes(this.stepCredentials)) {
deviceHostInfo = await this.getDeviceHostInfo();
}
}
// Display Success Dialog
this.showDialog(this.dialogs.success, deviceHostInfo);
}
async stepClose() {
// Close the currently loaded dialog
this.closeDialog();
}
////////// HANDLERS //////////
async bootDriveSelectHandler(e) {
const bootloaderVolume = await this.getBootDriveName();
let dirHandle;
// This will need to show a dialog selector
try {
dirHandle = await window.showDirectoryPicker({mode: 'readwrite'});
} catch (e) {
// Likely the user cancelled the dialog
return;
}
if (bootloaderVolume && bootloaderVolume != dirHandle.name) {
if (!confirm(`The selected drive named ${dirHandle.name} does not match the expected name of ${bootloaderVolume}. Continue anyways?`)) {
return;
}
}
if (!await this._verifyPermission(dirHandle)) {
alert("Unable to write to the selected folder");
return;
}
this.bootDriveHandle = dirHandle;
await this.nextStep();
}
async circuitpyDriveSelectHandler(e) {
let dirHandle;
// This will need to show a dialog selector
try {
dirHandle = await window.showDirectoryPicker({mode: 'readwrite'});
} catch (e) {
// Likely the user cancelled the dialog
return;
}
// Check if boot_out.txt exists
if (!(await this.getBootOut(dirHandle))) {
alert(`Expecting a folder with boot_out.txt. Please select the root folder of your CIRCUITPY drive.`);
return;
}
if (!await this._verifyPermission(dirHandle)) {
alert("Unable to write to the selected folder");
return;
}
this.circuitpyDriveHandle = dirHandle;
await this.nextStep();
}
async espToolConnectHandler(e) {
await this.onReplDisconnected(e);
await this.espDisconnect();
await this.setBaudRateIfChipSupports(PREFERRED_BAUDRATE);
try {
this.updateEspConnected(this.connectionStates.CONNECTING);
await this.espConnect({
log: (...args) => this.logMsg(...args),
debug: (...args) => {},
error: (...args) => this.errorMsg(...args),
});
this.updateEspConnected(this.connectionStates.CONNECTED);
} catch (err) {
// It's possible the dialog was also canceled here
this.updateEspConnected(this.connectionStates.DISCONNECTED);
this.errorMsg("Unable to open Serial connection to board. Make sure the port is not already in use by another application or in another browser tab.");
return;
}
try {
this.logMsg(`Connected to ${this.esploader.chip.CHIP_NAME}`);
// check chip compatibility
if (this.chipFamily == `${this.esploader.chip.CHIP_NAME}`.toLowerCase().replaceAll("-", "")) {
this.logMsg("This chip checks out");
// esploader-js doesn't have a disconnect event, so we can't use this
//this.esploader.addEventListener("disconnect", () => {
// this.updateEspConnected(this.connectionStates.DISCONNECTED);
//});
await this.nextStep();
return;
}
// Can't use it so disconnect now
this.errorMsg("Oops, this is the wrong firmware for your board.")
await this.espDisconnect();
} catch (err) {
if (this.transport) {
await this.transport.disconnect();
}
// Disconnection before complete
this.updateEspConnected(this.connectionStates.DISCONNECTED);
this.errorMsg("Oops, we lost connection to your board before completing the install. Please check your USB connection and click Connect again. Refresh the browser if it becomes unresponsive.")
}
}
async onSerialReceive(e) {
await this.repl.onSerialReceive(e);
}
async cpSerialConnectHandler(e) {
// Disconnect from the ESP Tool if Connected
await this.espDisconnect();
await this.onReplDisconnected(e);
// Connect to the Serial Port and interact with the REPL
try {
this.replSerialDevice = await navigator.serial.requestPort();
} catch (e) {
// Likely the user cancelled the dialog
return;
}
try {
await this.replSerialDevice.open({baudRate: ESP_ROM_BAUD});
} catch (e) {
console.error("Error. Unable to open Serial Port. Make sure it isn't already in use in another tab or application.");
}
await this.setupRepl();
this.nextStep();
}
async setupRepl() {
if (this.replSerialDevice) {
this.repl = new REPL();
this.repl.serialTransmit = this.serialTransmit.bind(this);
this.replSerialDevice.addEventListener("message", this.onSerialReceive.bind(this));
// Start the read loop
this._readLoopPromise = this._readSerialLoop().catch(
async function(error) {
await this.onReplDisconnected();
}.bind(this)
);
if (this.replSerialDevice.writable) {
this.writer = this.replSerialDevice.writable.getWriter();
await this.writer.ready;
}
}
}
async onReplDisconnected(e) {
if (this.reader) {
try {
await this.reader.cancel();
} catch(e) {
// Ignore
}
this.reader = null;
}
if (this.writer) {
await this.writer.releaseLock();
this.writer = null;
}
if (this.replSerialDevice) {
try {
await this.replSerialDevice.close();
} catch(e) {
// Ignore
}
this.replSerialDevice = null;
}
}
async buttonClickHandler(e, skipBoardSelector = false) {
if (this.boardIds.length > 1 && (!this.selectedBoardId || !skipBoardSelector)) {
this.showDialog(this.dialogs.boardSelect, {
boards: this.getBoardOptions(),
default: this.selectedBoardId,
});
this.currentDialogElement.querySelector("#availableBoards").addEventListener(
"change", this.updateButtons.bind(this)
);
return;
}
await this.loadBoard(this.selectedBoardId);
super.buttonClickHandler(e);
}
async selectBoardHandler(e) {
const selectedValue = this.currentDialogElement.querySelector("#availableBoards").value;
if (Object.keys(this.boardDefs).includes(selectedValue)) {
this.selectedBoardId = selectedValue;
this.closeDialog();
this.buttonClickHandler(null, true);
}
}
//////////////// FILE HELPERS ////////////////
async getBootDriveName() {
if (this._bootDriveName) {
return this._bootDriveName;
}
await this.extractBootloaderInfo();
return this._bootDriveName;
}
async getSerialPortName() {
if (this._serialPortName) {
return this._serialPortName;
}
await this.extractBootloaderInfo();
return this._serialPortName;
}
async _verifyPermission(folderHandle) {
const options = {mode: 'readwrite'};
if (await folderHandle.queryPermission(options) === 'granted') {
return true;
}
if (await folderHandle.requestPermission(options) === 'granted') {
return true;
}
return false;
}
async extractBootloaderInfo() {
if (!this.bootloaderUrl) {
return false;
}
// Download the bootloader zip file
let [filename, fileBlob] = await this.downloadAndExtract(this.bootloaderUrl, 'tinyuf2.bin');
const fileContents = await fileBlob.text();
const bootDriveRegex = /B\x00B\x00([A-Z0-9\x00]{11})FAT16/;
const serialNameRegex = /0123456789ABCDEF(.+)\x00UF2/;
// Not sure if manufacturer is displayed. If not, we should use this instead
// const serialNameRegex = /0123456789ABCDEF(?:.*\x00)?(.+)\x00UF2/;
let matches = fileContents.match(bootDriveRegex);
if (matches && matches.length >= 2) {
// Strip any null characters from the name
this._bootDriveName = matches[1].replace(/\0/g, '');
}
matches = fileContents.match(serialNameRegex);
if (matches && matches.length >= 2) {
// Replace any null characters with spaces
this._serialPortName = matches[1].replace(/\0/g, ' ');
}
this.removeCachedFile(this.bootloaderUrl.split("/").pop());
}
async getBootOut(dirHandle) {
return await this.readFile("boot_out.txt", dirHandle);
}
async readFile(filename, dirHandle = null) {
// Read a file from the given directory handle
if (!dirHandle) {
dirHandle = this.circuitpyDriveHandle;
}
if (!dirHandle) {
console.warn("CIRCUITPY Drive not selected and no Directory Handle provided");
return null;
}
try {
const fileHandle = await dirHandle.getFileHandle(filename);
const fileData = await fileHandle.getFile();
return await fileData.text();
} catch (e) {
return null;
}
}
async writeFile(filename, contents, dirHandle = null) {
// Write a file to the given directory handle
if (!dirHandle) {
dirHandle = this.circuitpyDriveHandle;
}
if (!dirHandle) {
console.warn("CIRCUITPY Drive not selected and no Directory Handle provided");
return null;
}
const fileHandle = await dirHandle.getFileHandle(filename, {create: true});
const writable = await fileHandle.createWritable();
await writable.write(contents);
await writable.close();
}
//////////////// DOWNLOAD HELPERS ////////////////
addCachedFile(filename, blob) {
this.fileCache.push({
filename: filename,
blob: blob
});
}
getCachedFile(filename) {
for (let file of this.fileCache) {
if (file.filename === filename) {
return file.contents;
}
}
return null;
}
removeCachedFile(filename) {
for (let file of this.fileCache) {
if (file.filename === filename) {
this.fileCache.splice(this.fileCache.indexOf(file), 1);
}
}
}
async downloadFile(url, progressElement) {
let response;
try {
response = await fetch(url);
} catch (err) {
this.errorMsg(`Unable to download file: ${url}`);
return null;
}
const body = response.body;
const reader = body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
let chunks = [];
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
progressElement.value = Math.round((receivedLength / contentLength) * 100);
this.logMsg(`Received ${receivedLength} of ${contentLength}`)
}
let chunksAll = new Uint8Array(receivedLength);
let position = 0;
for(let chunk of chunks) {
chunksAll.set(chunk, position);
position += chunk.length;
}
let result = new Blob([chunksAll]);
return result;
}
async downloadAndExtract(url, fileToExtract = null, cacheFile = false) {
// Display Progress Dialog
let filename = url.split("/").pop();
let fileBlob = this.getCachedFile(filename);
if (!fileBlob) {
this.showDialog(this.dialogs.actionProgress, {
action: `Downloading ${filename}`
});
const progressElement = this.currentDialogElement.querySelector("#stepProgress");
// Download the file at the url updating the progress in the process
fileBlob = await this.downloadFile(url, progressElement);
if (cacheFile) {
this.addCachedFile(filename, fileBlob);
}
}
// If the file is a zip file, unzip and find the file to extract
if (filename.endsWith(".zip") && fileToExtract) {
let foundFile;
// Update the Progress dialog