-
Notifications
You must be signed in to change notification settings - Fork 1
/
base_installer.js
481 lines (409 loc) · 14.1 KB
/
base_installer.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
// SPDX-FileCopyrightText: 2023 Melissa LeBlanc-Williams for Adafruit Industries
//
// SPDX-License-Identifier: MIT
'use strict';
import {html, render} from 'https://cdn.jsdelivr.net/npm/lit-html/+esm';
import {asyncAppend} from 'https://cdn.jsdelivr.net/npm/lit-html/directives/async-append/+esm';
import { ESPLoader, Transport } from "https://unpkg.com/[email protected]/bundle.js";
export const ESP_ROM_BAUD = 115200;
export class InstallButton extends HTMLButtonElement {
static isSupported = 'serial' in navigator;
static isAllowed = window.isSecureContext;
constructor() {
super();
this.baudRate = ESP_ROM_BAUD;
this.dialogElements = {};
this.currentFlow = null;
this.currentStep = 0;
this.currentDialogElement = null;
this.device = null;
this.transport = null;
this.esploader = null;
this.chip = null;
this.dialogCssClass = "install-dialog";
this.connected = this.connectionStates.DISCONNECTED;
this.menuTitle = "Installer Menu";
}
init() {
this.preloadDialogs();
}
// Define some common buttons
/* Buttons should have a label, and a callback and optionally a condition function on whether they should be enabled */
previousButton = {
label: "Previous",
onClick: this.prevStep,
isEnabled: async () => { return this.currentStep > 0 },
}
nextButton = {
label: "Next",
onClick: this.nextStep,
isEnabled: async () => { return this.currentStep < this.currentFlow.steps.length - 1; },
}
closeButton = {
label: "Close",
onClick: async (e) => {
this.closeDialog();
},
}
// Default Buttons
defaultButtons = [this.previousButton, this.nextButton];
// States and Button Labels
connectionStates = {
DISCONNECTED: "Connect",
CONNECTING: "Connecting...",
CONNECTED: "Disconnect",
}
dialogs = {
notSupported: {
preload: false,
closeable: true,
template: (data) => html`
Sorry, <b>Web Serial</b> is not supported on your browser at this time. Browsers we expect to work:
<ul>
<li>Google Chrome 89 (and higher)</li>
<li>Microsoft Edge 89 (and higher)</li>
<li>Opera 75 (and higher)</li>
</ul>
`,
buttons: [this.closeButton],
},
menu: {
closeable: true,
template: (data) => html`
<p>${this.menuTitle}</p>
<ul class="flow-menu">
${asyncAppend(this.generateMenu(
(flowId, flow) => html`<li><a href="#" @click=${this.runFlow.bind(this)} id="${flowId}">${flow.label.replace('[version]', this.releaseVersion)}</a></li>`
))}
</ul>`,
buttons: [this.closeButton],
},
};
flows = {};
baudRates = [
115200,
128000,
153600,
230400,
460800,
921600,
1500000,
2000000,
];
connectedCallback() {
if (InstallButton.isSupported && InstallButton.isAllowed) {
this.toggleAttribute("install-supported", true);
} else {
this.toggleAttribute("install-unsupported", true);
}
this.addEventListener("click", async (e) => {
e.preventDefault();
// WebSerial feature detection
if (!InstallButton.isSupported) {
await this.showNotSupported();
} else {
await this.buttonClickHandler(e);
}
});
}
async buttonClickHandler(e) {
await this.showMenu();
}
// Parse out the url parameters from the current url
getUrlParams() {
// This should look for and validate very specific values
var hashParams = {};
if (location.hash) {
location.hash.substr(1).split("&").forEach(function(item) {hashParams[item.split("=")[0]] = item.split("=")[1];});
}
return hashParams;
}
// Get a url parameter by name and optionally remove it from the current url in the process
getUrlParam(name) {
let urlParams = this.getUrlParams();
let paramValue = null;
if (name in urlParams) {
paramValue = urlParams[name];
}
return paramValue;
}
async enabledFlowCount() {
let enabledFlowCount = 0;
for (const [flowId, flow] of Object.entries(this.flows)) {
if (await flow.isEnabled()) {
enabledFlowCount++;
}
}
return enabledFlowCount;
}
async * generateMenu(templateFunc) {
if (await this.enabledFlowCount() == 0) {
yield html`<li>No installable options available for this board.</li>`;
}
for (const [flowId, flow] of Object.entries(this.flows)) {
if (await flow.isEnabled()) {
yield templateFunc(flowId, flow);
}
}
}
preloadDialogs() {
for (const [id, dialog] of Object.entries(this.dialogs)) {
if ('preload' in dialog && !dialog.preload) {
continue;
}
this.dialogElements[id] = this.getDialogElement(dialog);
}
}
createIdFromLabel(text) {
return text.replace(/^[^a-z]+|[^\w:.-]+/gi, "");
}
createDialogElement(id, dialogData) {
// Check if an existing dialog with the same id exists and remove it if so
let existingDialog = this.querySelector(`#cp-installer-${id}`);
if (existingDialog) {
this.remove(existingDialog);
}
// Create a dialog element
let dialogElement = document.createElement("dialog");
dialogElement.id = id;
dialogElement.classList.add(this.dialogCssClass);
// Add a close button
let closeButton = document.createElement("button");
closeButton.href = "#";
closeButton.classList.add("close-button");
closeButton.addEventListener("click", (e) => {
e.preventDefault();
dialogElement.close();
});
dialogElement.appendChild(closeButton);
// Add a body element
let body = document.createElement("div");
body.classList.add("dialog-body");
dialogElement.appendChild(body);
let buttons = this.defaultButtons;
if (dialogData && dialogData.buttons) {
buttons = dialogData.buttons;
}
dialogElement.appendChild(
this.createNavigation(buttons)
);
// Return the dialog element
document.body.appendChild(dialogElement);
return dialogElement;
}
createNavigation(buttonData) {
// Add buttons according to config data
const navigation = document.createElement("div");
navigation.classList.add("dialog-navigation");
for (const button of buttonData) {
let buttonElement = document.createElement("button");
buttonElement.innerText = button.label;
buttonElement.id = this.createIdFromLabel(button.label);
buttonElement.addEventListener("click", async (e) => {
e.preventDefault();
await button.onClick.bind(this)();
});
buttonElement.addEventListener("update", async (e) => {
if ("onUpdate" in button) {
await button.onUpdate.bind(this)(e);
}
if ("isEnabled" in button) {
e.target.disabled = !(await button.isEnabled.bind(this)());
}
});
navigation.appendChild(buttonElement);
}
return navigation;
}
getDialogElement(dialog, forceReload = false) {
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
const dialogId = getKeyByValue(this.dialogs, dialog);
if (dialogId) {
if (dialogId in this.dialogElements && !forceReload) {
return this.dialogElements[dialogId];
} else {
return this.createDialogElement(dialogId, dialog);
}
}
return null;
}
updateButtons() {
// Call each button's custom update event for the current dialog
if (this.currentDialogElement) {
const navButtons = this.currentDialogElement.querySelectorAll(".dialog-navigation button");
for (const button of navButtons) {
button.dispatchEvent(new Event("update"));
}
}
}
showDialog(dialog, templateData = {}) {
if (this.currentDialogElement) {
this.closeDialog();
}
this.currentDialogElement = this.getDialogElement(dialog);
if (!this.currentDialogElement) {
console.error(`Dialog not found`);
}
if (this.currentDialogElement) {
const dialogBody = this.currentDialogElement.querySelector(".dialog-body");
if ('template' in dialog) {
render(dialog.template(templateData), dialogBody);
}
// Close button should probably hide during certain steps such as flashing and erasing
if ("closeable" in dialog && dialog.closeable) {
this.currentDialogElement.querySelector(".close-button").style.display = "block";
} else {
this.currentDialogElement.querySelector(".close-button").style.display = "none";
}
let dialogButtons = this.defaultButtons;
if ('buttons' in dialog) {
dialogButtons = dialog.buttons;
}
this.updateButtons();
this.currentDialogElement.showModal();
}
}
closeDialog() {
this.currentDialogElement.close();
this.currentDialogElement = null;
}
errorMsg(text) {
text = this.stripHtml(text);
console.error(text);
this.showError(text);
}
logMsg(text, showTrace = false) {
// TODO: Eventually add to an internal log that the user can bring up
console.info(this.stripHtml(text));
if (showTrace) {
console.trace();
}
}
updateEspConnected(connected) {
if (Object.values(this.connectionStates).includes(connected)) {
this.connected = connected;
this.updateButtons();
}
}
stripHtml(html) {
let tmp = document.createElement("div");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
formatMacAddr(macAddr) {
return macAddr.map((value) => value.toString(16).toUpperCase().padStart(2, "0")).join(":");
}
async espDisconnect() {
if (this.transport) {
await this.transport.disconnect();
await this.transport.waitForUnlock(1500);
this.updateEspConnected(this.connectionStates.DISCONNECTED);
this.transport = null;
this.device = null;
this.chip = null;
return true;
}
return false;
}
async runFlow(flow) {
if (flow instanceof Event) {
flow.preventDefault();
flow.stopImmediatePropagation();
if (flow.target.id in this.flows) {
flow = this.flows[flow.target.id];
} else {
return;
}
}
this.currentFlow = flow;
this.currentStep = 0;
await this.currentFlow.steps[this.currentStep].bind(this)();
}
async nextStep() {
if (!this.currentFlow) {
return;
}
if (this.currentStep < this.currentFlow.steps.length) {
this.currentStep++;
await this.currentFlow.steps[this.currentStep].bind(this)();
}
}
async prevStep() {
if (!this.currentFlow) {
return;
}
if (this.currentStep > 0) {
this.currentStep--;
await this.currentFlow.steps[this.currentStep].bind(this)();
}
}
async advanceSteps(stepCount) {
if (!this.currentFlow) {
return;
}
if (this.currentStep <= this.currentFlow.steps.length + stepCount) {
this.currentStep += stepCount;
await this.currentFlow.steps[this.currentStep].bind(this)();
}
}
async showMenu() {
// Display Menu
this.showDialog(this.dialogs.menu);
}
async showNotSupported() {
// Display Not Supported Message
this.showDialog(this.dialogs.notSupported);
}
async showError(message) {
// Display Menu
this.showDialog(this.dialogs.error, {message: message});
}
async setBaudRateIfChipSupports(baud) {
if (baud == this.baudRate) { return } // already the current setting
await this.changeBaudRate(baud);
}
async changeBaudRate(baud) {
if (this.baudRates.includes(baud)) {
if (this.transport == null) {
this.baudRate = baud;
} else {
this.errorMsg("Cannot change baud rate while connected.");
}
}
}
async espHardReset() {
if (this.esploader) {
await this.esploader.hardReset();
}
}
async espConnect(logger) {
logger.log("Connecting...");
if (this.device === null) {
this.device = await navigator.serial.requestPort({});
this.transport = new Transport(this.device, true);
}
const espLoaderTerminal = {
clean() {
// Clear the terminal
},
writeLine(data) {
logger.log(data);
},
write(data) {
logger.log(data);
},
};
const loaderOptions = {
transport: this.transport,
baudrate: this.baudRate,
terminal: espLoaderTerminal,
debugLogging: false,
};
this.esploader = new ESPLoader(loaderOptions);
this.chip = await this.esploader.main();
logger.log("Connected successfully.");
return this.esploader;
};
}