import React, {useContext, useEffect, useLayoutEffect, useRef, useState} from 'react'; import {Route, Routes} from "react-router"; import {Checkbox, Label, Message, Select, Button as SButton, Icon as SIcon} from "semantic-ui-react"; import {ESPLoader, Transport} from "esptool-js"; import {useDropzone} from "react-dropzone"; import _ from "lodash"; import {encodeMediaPath, humanFileSize, PageContainer, useTitle} from "./Common"; import { Button, darkTheme, Divider, Form, Header, Icon, List, Loader, Modal, Progress, Segment, Tab, Table, TextArea } from "./Theme"; import {ThemeContext} from "../contexts/contexts"; import {deleteFlasherConfig, flasherSearch, getFlasherConfigs, saveFlasherConfig} from "../api"; // The suffix used to find flashable ESP32 firmware in the media directory. const FIRMWARE_SUFFIX = '.bin'; // esptool-js reports a chip description like "ESP32-S2 (revision v0.0)"; take the family before " (". export function chipFamily(description) { return (description || '').split(' (')[0].trim() || null; } // ESP image chip_id -> family name (matches esptool-js IMAGE_CHIP_ID values). const ESP_CHIP_ID_NAMES = { 0: 'ESP32', 2: 'ESP32-S2', 5: 'ESP32-C3', 9: 'ESP32-S3', 12: 'ESP32-C2', 13: 'ESP32-C6', 16: 'ESP32-H2', 17: 'ESP32-C5', 18: 'ESP32-P4', }; // Known ESP chip names, sorted so each maps to a stable color — colors survive reboots/refreshes and only shift // if a new name is added here. A chip not in this list still gets a deterministic color via hashing below. const KNOWN_ESP_CHIPS = [ 'ESP32', 'ESP32-S2', 'ESP32-S3', 'ESP32-C2', 'ESP32-C3', 'ESP32-C5', 'ESP32-C6', 'ESP32-C61', 'ESP32-H2', 'ESP32-P4', ].sort(); // Paul Tol's "bright" qualitative palette (colorblind-safe) plus black, then four more distinct colors for // headroom. A label's *width* (chip-name length) is itself a discriminator, so two chips only need distinct // colors when they render at the same width. The first eight cover today's largest same-width group (the eight // 8-character ESP32-* names); the extras let a same-width group grow past eight before colors would repeat. // (Truly colorblind-distinct qualitative colors top out around ten, so beyond that distinctness is best-effort.) const CHIP_COLORS = [ '#4477aa', '#ee6677', '#228833', '#ccbb44', '#66ccee', '#aa3377', '#bbbbbb', '#000000', '#ee7733', '#332288', '#999933', '#882255', ]; // Assign each known chip a color *index within its own name-length group*. Same-width chips therefore always get // different (colorblind-distinguishable) colors, while chips of different widths may share one — the width tells // them apart. Built once from the sorted known list. const CHIP_COLOR_INDEX = (() => { const perLength = {}; const index = {}; for (const name of KNOWN_ESP_CHIPS) { const slot = perLength[name.length] || 0; index[name] = slot; perLength[name.length] = slot + 1; } return index; })(); // Deterministic background color for a chip label (see CHIP_COLORS/CHIP_COLOR_INDEX). Unknown chips hash to a // stable slot so they still get a consistent color. export function chipColor(name) { if (!name) { return CHIP_COLORS[CHIP_COLORS.length - 1]; } if (name in CHIP_COLOR_INDEX) { return CHIP_COLORS[CHIP_COLOR_INDEX[name] % CHIP_COLORS.length]; } let hash = 0; for (let i = 0; i < name.length; i++) { hash = (hash * 31 + name.charCodeAt(i)) >>> 0; } return CHIP_COLORS[hash % CHIP_COLORS.length]; } // Black or white text for readability on a given hex background (YIQ brightness). export function chipTextColor(hex) { const c = (hex || '').replace('#', ''); if (c.length < 6) { return '#fff'; } const r = parseInt(c.slice(0, 2), 16); const g = parseInt(c.slice(2, 4), 16); const b = parseInt(c.slice(4, 6), 16); return (r * 299 + g * 587 + b * 114) / 1000 > 140 ? '#000' : '#fff'; } export function chipIdName(chipId) { return ESP_CHIP_ID_NAMES[chipId] || `chip id ${chipId}`; } // Read the chip_id from an ESP application/bootloader image header: magic byte 0xE9 at offset 0, chip_id as a // uint16 LE at offset 0x0C. Returns null for non-ESP-image files (partition tables start 0xAA, boot_app0 and // littlefs are raw, etc.) — those carry no chip_id and must never be flagged as a mismatch. export function espImageChipId(header) { if (!header || header.length < 14 || header[0] !== 0xE9) { return null; } return header[12] | (header[13] << 8); } // Flashing happens entirely in the browser using the Web Serial API; nothing is uploaded to WROLPi. esptool-js is // bundled into the frontend build, so this works fully offline once the page has loaded. const BAUD_OPTIONS = [ {key: '115200', value: 115200, text: '115200 (safe)'}, {key: '230400', value: 230400, text: '230400'}, {key: '460800', value: 460800, text: '460800'}, {key: '921600', value: 921600, text: '921600 (fast)'}, ]; // Web Serial is only available in a secure context (HTTPS or localhost) on Chromium-based browsers. export function webSerialSupported() { return typeof navigator !== 'undefined' && 'serial' in navigator; } function readFileAsUint8Array(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(new Uint8Array(reader.result)); reader.onerror = () => reject(reader.error); reader.readAsArrayBuffer(file); }); } // Load a firmware entry's bytes. Local files are read from disk; media entries are fetched from the WROLPi // media directory over HTTP. Both return a Uint8Array as esptool-js expects. async function readEntryBytes(item) { if (item.file) { return readFileAsUint8Array(item.file); } const resp = await fetch(`/media/${encodeMediaPath(item.mediaPath)}`); if (!resp.ok) { throw new Error(`Failed to fetch ${item.name} from the media directory (${resp.status})`); } const buffer = await resp.arrayBuffer(); return new Uint8Array(buffer); } // Read just the leading bytes of a firmware entry (enough for the ESP image header) without downloading the // whole file. Local files are sliced; media files use an HTTP Range request (the media server supports Range). async function readEntryHeader(item) { if (item.file) { return new Uint8Array(await item.file.slice(0, 24).arrayBuffer()); } const resp = await fetch(`/media/${encodeMediaPath(item.mediaPath)}`, {headers: {Range: 'bytes=0-23'}}); if (!resp.ok) { return null; } return new Uint8Array(await resp.arrayBuffer()).slice(0, 24); } // A flash offset must be a 0x-prefixed hex string, e.g. "0x0" or "0x10000". const HEX_OFFSET_RE = /^0x[0-9a-f]+$/i; export function isValidHexOffset(value) { return HEX_OFFSET_RE.test((value || '').trim()); } // Parse a validated hex flash offset like "0x10000" or "0x0" into a number. export function parseAddress(value) { const trimmed = (value || '').trim(); if (trimmed === '') { throw new Error('Flash offset is required'); } if (!isValidHexOffset(trimmed)) { throw new Error(`Invalid flash offset (expected a hex value like 0x10000): ${value}`); } return parseInt(trimmed, 16); } // Rough estimate of how long flashing will take, in seconds. Serial is 8N1 (10 bits per byte), so the link // carries ~baud/10 bytes/sec; esptool-js compresses the image (~0.6x), which roughly offsets SLIP framing and // flash-write overhead, making raw bytes / (baud/10) a reasonable ballpark. export function estimateFlashSeconds(totalBytes, baudrate) { if (!totalBytes || !baudrate) { return 0; } return totalBytes / (baudrate / 10); } // Format a duration in seconds as e.g. "45s" or "2m 5s". export function humanDuration(seconds) { if (!seconds || !isFinite(seconds) || seconds <= 0) { return null; } const total = Math.round(seconds); const minutes = Math.floor(total / 60); const secs = total % 60; return minutes > 0 ? `${minutes}m ${secs}s` : `${secs}s`; } // Reject if `promise` doesn't settle within `ms`. esptool-js's connect can hang indefinitely when a board is // not in download mode; this guarantees the caller always gets a result so the UI can recover. export function withTimeout(promise, ms, message) { let timer; const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); }); // Swallow a late rejection from the raced promise so it doesn't surface as an unhandled rejection. promise.catch(() => { }); return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); } // How long to wait for a device to connect before giving up (esptool-js retries can otherwise stall the UI). const CONNECT_TIMEOUT_MS = 30_000; // A read-only log TextArea that auto-scrolls to the newest output — but only when the user is already at the // bottom, so scrolling up to read earlier lines isn't yanked back down. Starts at the bottom on mount (e.g. when // a modal opens). function AutoScrollLog({value, ...props}) { const containerRef = useRef(null); const atBottomRef = useRef(true); const getTextArea = () => containerRef.current && containerRef.current.querySelector('textarea'); const handleScroll = (e) => { const el = e.target; // Treat "within a few px of the bottom" as at-bottom so it re-sticks when the user scrolls back down. atBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 20; }; useLayoutEffect(() => { const el = getTextArea(); if (el && atBottomRef.current) { el.scrollTop = el.scrollHeight; } }, [value]); return