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, filesSearch, 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; } // 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); } // 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