diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..c30cfd9 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,38 @@ +name: Web console (GitHub Pages) + +# The Emulator Console (web/): the page the firmware advertises as its WebUSB +# landing page (esp-cpp.github.io//). Needs Settings -> Pages -> Source: +# GitHub Actions. +on: + push: + branches: [main] + paths: + - 'web/**' + - '.github/workflows/pages.yml' + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: true + +jobs: + deploy: + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/checkout@v4 + - name: Check the scripts parse (as ES modules) + run: for f in web/*.js; do node --input-type=module --check < "$f" || exit 1; done + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v3 + with: + path: web + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/README.md b/README.md index 69baf79..dea863f 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,54 @@ https://github.com/user-attachments/assets/641a64b0-b3af-429b-8582-a38fc9a5cdad

+## Web Console + +Plug the Tab5 into a computer and it brings its own control panel. Chrome or +Edge pops up a notification for +**[esp-cpp.github.io/tab5-emu](https://esp-cpp.github.io/tab5-emu/)**, the +firmware's WebUSB landing page: click it, pick the Tab5, and the page talks +to the device straight from the browser. There's nothing to install and no +server in between. + +

+Web console Screen tab: a capture of Donkey Kong Country next to an on-screen controller and save-state buttons Web console Library tab: Super Nintendo games with boxart, console filters and Play / Remove buttons +

+ +- **Dashboard**: what's running (with its boxart), live frame-rate and + memory graphs, the firmware and partition, the last reset reason, and a + button that hands the SD card to the PC as a USB drive. +- **Screen**: capture the game's or the launcher's screen (or keep it + **Live**), save it as a PNG, play with the on-screen controller or the + keyboard (arrows, Z / X / A / S, Q / W for L / R, Enter = Start), save and + load states, quit. +- **Library**: the games by console with their boxart and counts. Search, + filter (the launcher too, if you like), **Play** any of them, or **Add a + game**: choose the ROM and its cover and the page uploads both and adds the + `metadata.csv` line. **Remove** undoes it. +- **Files**: browse the SD card, download, upload by drag and drop, new + folder, delete. +- **Settings**: volume, mute, brightness, video scaling and resume last save, + shown in the launcher at once and saved to the card a moment later. +- **System**: chip, memory, ESP-IDF, OTA state and the services on the link; + restart (or into download mode), and **Update firmware**, which restarts + into the updater and opens the espp OTA console for `build/tab5-emu.bin`. +- **Console**: the log over Web Serial (pick the console's port), filtered, + followed, saved to a file. + +

+Web console Dashboard: Donkey Kong Country running, with performance, memory, device and SD card panels Web console Settings tab: volume, mute, brightness, video scaling and resume last save Web console System tab: ESP32-P4 details, firmware update and restart +

+ +How it works: the composite USB device has a vendor (WebUSB) interface that +carries the same link as `tools/emulink`, and its descriptor names the +landing page, which is how the browser knows where to go. The page is plain +HTML, CSS and ES modules in [`web/`](./web) (shared with esp-box-emu, no build +step), published to GitHub Pages from `main`. One program owns the link at a +time, so close `emulink` before opening the page and the other way round. To +work on the page, `python3 -m http.server -d web 8000` and open +http://localhost:8000 (WebUSB needs https or localhost); [`web/README.md`](./web/README.md) +has the details. + ## Hardware | | | diff --git a/components/gui/include/gui.hpp b/components/gui/include/gui.hpp index 7fef744..0a70f21 100644 --- a/components/gui/include/gui.hpp +++ b/components/gui/include/gui.hpp @@ -75,6 +75,15 @@ class Gui { /// Show only `console`'s games (nullopt: every console's); false if it has none. bool set_console_filter(std::optional console); + /// The settings the launcher shows, for the USB link: {settings: {name: + /// value}, limits: {name: [min, max]}} (volume, muted, brightness, video, + /// resume). + std::string settings_json() const; + /// Change one of them as its control in the launcher does (shown, applied, + /// saved once the changes stop); false for an unknown name or a value out + /// of range. + bool set_setting(const std::string &name, int value); + /// The launcher screen (RGB565, little endian, rows packed), for the USB /// link's screenshot when no game runs; empty if it cannot be drawn. struct Snapshot { diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp index 56ff216..01cb68c 100644 --- a/components/gui/src/gui.cpp +++ b/components/gui/src/gui.cpp @@ -1,5 +1,7 @@ #include "gui.hpp" +#include + #include "lvgl_private.h" #include @@ -510,6 +512,54 @@ void Gui::picker_event(lv_event_t *e) { } } +namespace { +struct SettingLimit { + const char *name; + int min, max; +}; +// (the same ranges as the launcher's own sliders) +constexpr SettingLimit kSettingLimits[] = { + {"volume", 0, 100}, {"muted", 0, 1}, {"brightness", 5, 100}, {"video", 0, 2}, {"resume", 0, 1}}; +} // namespace + +std::string Gui::settings_json() const { + auto &emu = Tab5Emu::get(); + const auto s = AppSettings::get().get_settings(); + std::string limits; + for (const auto &l : kSettingLimits) { + limits += fmt::format("{}\"{}\":[{},{}]", limits.empty() ? "" : ",", l.name, l.min, l.max); + } + return fmt::format("{{\"settings\":{{\"volume\":{},\"muted\":{},\"brightness\":{},\"video\":{},\"resume\":{}}}," + "\"limits\":{{{}}}}}", + (int)std::lround(emu.volume()), emu.is_muted() ? 1 : 0, (int)std::lround(emu.brightness()), + (int)emu.video_setting(), + s.resume_last_save ? 1 : 0, limits); +} + +bool Gui::set_setting(const std::string &name, int value) { + const auto *limit = std::find_if(std::begin(kSettingLimits), std::end(kSettingLimits), + [&](const SettingLimit &l) { return name == l.name; }); + if (limit == std::end(kSettingLimits) || value < limit->min || value > limit->max) { + return false; + } + std::lock_guard lk(mutex_); + auto &emu = Tab5Emu::get(); + // (saved to the SD card by the main loop once the changes stop, as from the launcher) + AppSettings::get().modify([&](Settings &s) { + if (name == "volume") s.volume = value; + else if (name == "muted") s.muted = value != 0; + else if (name == "brightness") s.brightness = value; + else if (name == "video") s.video_setting = value; + else if (name == "resume") s.resume_last_save = value != 0; + }); + if (name == "volume") emu.volume(value); + else if (name == "muted") emu.mute(value != 0); + else if (name == "brightness") emu.brightness(value); + else if (name == "video") emu.video_setting(static_cast(value)); + update_shared_state(); // the launcher's controls show it + return true; +} + Gui::Snapshot Gui::snapshot() { std::lock_guard lk(mutex_); Snapshot shot; diff --git a/components/tab5-emu/src/usb_device.cpp b/components/tab5-emu/src/usb_device.cpp index c1382c7..757685f 100644 --- a/components/tab5-emu/src/usb_device.cpp +++ b/components/tab5-emu/src/usb_device.cpp @@ -87,7 +87,7 @@ bool Tab5Emu::initialize_usb_device() { espp::UsbDevice::VendorFunction vendor; vendor.interface_name = "Tab5 Emu link"; vendor.webusb = true; - vendor.landing_page_url = "esp-cpp.github.io/espp/apps/device_hub.html"; + vendor.landing_page_url = "esp-cpp.github.io/tab5-emu/"; vendor.on_receive = [this](std::span data) { if (vendor_rx_) vendor_rx_(data); }; diff --git a/docs/images/web-console-dashboard.jpg b/docs/images/web-console-dashboard.jpg new file mode 100644 index 0000000..78a8268 Binary files /dev/null and b/docs/images/web-console-dashboard.jpg differ diff --git a/docs/images/web-console-library.jpg b/docs/images/web-console-library.jpg new file mode 100644 index 0000000..dd43f93 Binary files /dev/null and b/docs/images/web-console-library.jpg differ diff --git a/docs/images/web-console-screen.jpg b/docs/images/web-console-screen.jpg new file mode 100644 index 0000000..61e4dc6 Binary files /dev/null and b/docs/images/web-console-screen.jpg differ diff --git a/docs/images/web-console-settings.jpg b/docs/images/web-console-settings.jpg new file mode 100644 index 0000000..ecdba1c Binary files /dev/null and b/docs/images/web-console-settings.jpg differ diff --git a/docs/images/web-console-system.jpg b/docs/images/web-console-system.jpg new file mode 100644 index 0000000..071a439 Binary files /dev/null and b/docs/images/web-console-system.jpg differ diff --git a/main/remote_control.hpp b/main/remote_control.hpp index 695b1bd..bad2426 100644 --- a/main/remote_control.hpp +++ b/main/remote_control.hpp @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -111,11 +112,12 @@ class RemoteControl { public: static constexpr uint8_t kModule = 0x20; static constexpr const char *kProtocol = "emu.control"; - static constexpr uint16_t kProtocolVersion = 3; // 2: in-memory screenshots, 3: console filter, launcher screenshots + // 2: in-memory screenshots, 3: console filter, launcher screenshots, 4: settings, boxart / console keys in the list + static constexpr uint16_t kProtocolVersion = 4; enum class Type : uint8_t { STATUS = 0x01, ///< () -> {state, rom, platform, console, heap, uptime, ...} - LIST_ROMS = 0x02, ///< (offset: text) -> {total, roms: [{name, path, platform, console}]} + LIST_ROMS = 0x02, ///< (offset: text) -> {total, roms: [{name, path, platform, console, key, boxart}]} LAUNCH = 0x03, ///< (rom path or part of a name / path) -> {rom} QUIT = 0x04, ///< () BUTTONS = 0x05, ///< (u16 buttons, u16 hold ms; 0 = until the next BUTTONS) @@ -136,6 +138,10 @@ class RemoteControl { /// consoles: [keys]}: the launcher's list shows only that console's games. /// An empty payload only reports them (nothing changes on the device). CONSOLE_FILTER = 0x0D, + /// (empty, or "name=value" to change one) -> {settings: {name: value}, + /// limits: {name: [min, max]}}: the launcher's settings (volume, + /// brightness, ...), applied and saved like the launcher's own controls + SETTINGS = 0x0E, FILE_LIST = 0x10, ///< (path[\0offset]) -> {entries: [{name, dir, size}], truncated?, next?} FILE_READ = 0x11, ///< (u32 offset, u16 length, path) -> raw bytes (short at the end) FILE_WRITE = 0x12, ///< (u32 offset, path_len u16, path, data); offset 0 truncates @@ -234,9 +240,11 @@ class RemoteControl { size_t i = offset; for (; i < roms.size(); i++) { const auto &r = roms[i]; - auto e = fmt::format("{}{{\"name\":{},\"path\":{},\"platform\":\"{}\",\"console\":{}}}", - i > offset ? "," : "", quote(r.name), quote(r.rom_path), r.platform, - quote(console_info(console_of(r.platform)).name)); + const auto &console = console_info(console_of(r.platform)); + auto e = fmt::format( + "{}{{\"name\":{},\"path\":{},\"platform\":\"{}\",\"console\":{},\"key\":{},\"boxart\":{}}}", + i > offset ? "," : "", quote(r.name), quote(r.rom_path), r.platform, quote(console.name), + quote(console.key), quote(r.boxart_path)); // (room for the trailer, `],"next":N}`, and reply()'s status byte) if (j.size() + e.size() + 24 > espp::stream_frame::kMaxPayloadSize) break; // the host asks for the rest j += e; @@ -498,6 +506,29 @@ class RemoteControl { else json(filter_json()); break; } + case Type::SETTINGS: { + if (!text.empty()) { + const auto eq = text.find('='); + if (eq == std::string_view::npos) { + fail("payload: name=value"); + break; + } + const std::string name(text.substr(0, eq)); + const std::string value(text.substr(eq + 1)); + int v = 0; + const auto [end, ec] = std::from_chars(value.data(), value.data() + value.size(), v); + if (value.empty() || ec != std::errc() || end != value.data() + value.size()) { + fail(fmt::format("{}: '{}' is not a number", name, value)); + break; + } + if (!gui_.set_setting(name, v)) { + fail(fmt::format("unknown setting '{}' (or {} is out of range)", name, v)); + break; + } + } + json(gui_.settings_json()); + break; + } case Type::FILE_LIST: { // path, optionally followed by '\0' and the index to start at (the "next" of a truncated // reply) @@ -592,10 +623,14 @@ class RemoteControl { write_pos_ = offset + n; break; } - case Type::FILE_CLOSE: - // (a buffered write that fails shows up here) - if (!close_file()) fail("closing the file failed (card full?)"); + case Type::FILE_CLOSE: { + // (a buffered write that fails shows up here, also one closed earlier + // by a read of the file or the card handover) + const bool closed = close_file(); + if (!closed || write_lost_) fail("closing the file failed (card full?)"); + write_lost_ = false; break; + } case Type::FILE_DELETE: { const std::string path(text); close_file(path); @@ -816,6 +851,7 @@ class RemoteControl { } if (!close_file()) return false; // (the previous file's last data did not land) if (offset == 0) { + write_lost_ = false; // (a new file: an older one's failure is not its) std::error_code ec; std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); write_file_ = fopen(path.c_str(), "wb"); @@ -838,6 +874,7 @@ class RemoteControl { const bool ok = fclose(write_file_) == 0; write_file_ = nullptr; write_path_.clear(); + if (!ok) write_lost_ = true; // (told by the next FILE_CLOSE) return ok; } return true; @@ -875,4 +912,5 @@ class RemoteControl { FILE *write_file_{nullptr}; std::string write_path_; uint32_t write_pos_{0}; + bool write_lost_{false}; ///< an implicit close_file() lost buffered data }; diff --git a/tools/emulink/emulink/cli.py b/tools/emulink/emulink/cli.py index ba9498a..d923228 100644 --- a/tools/emulink/emulink/cli.py +++ b/tools/emulink/emulink/cli.py @@ -147,6 +147,18 @@ def cmd_filter(args) -> int: return 0 +def cmd_settings(args) -> int: + with _open(args) as link: + c = Control(link) + r = None + for change in args.change or [None]: + r = c.settings(change) + for name, value in r["settings"].items(): + lo, hi = r["limits"].get(name, ("", "")) + print(f"{name:<11} {value:>4} ({lo}..{hi})") + return 0 + + def cmd_ls(args) -> int: with _open(args) as link: for e in Control(link).ls(args.path): @@ -497,6 +509,9 @@ def build_parser() -> argparse.ArgumentParser: s.add_argument("--delete", action="store_true", help="also delete the file") s.set_defaults(fn=cmd_remove_rom) sub.add_parser("reload", help="re-read metadata.csv").set_defaults(fn=cmd_reload) + s = sub.add_parser("settings", help="the launcher's settings; name=value changes one (volume=40, muted=1, ...)") + s.add_argument("change", nargs="*", help="name=value") + s.set_defaults(fn=cmd_settings) s = sub.add_parser("filter", help="show only one console's games in the launcher (a key such as snes, or all)") s.add_argument("console", nargs="?", help="console key, or all (default: show the current filter)") s.set_defaults(fn=cmd_filter) diff --git a/tools/emulink/emulink/control.py b/tools/emulink/emulink/control.py index 36e3caf..ad390b6 100644 --- a/tools/emulink/emulink/control.py +++ b/tools/emulink/emulink/control.py @@ -18,6 +18,7 @@ STATUS, LIST_ROMS, LAUNCH, QUIT, BUTTONS, SAVE, LOAD, SCREENSHOT, USB_DRIVE, RELOAD_ROMS, ENTER_UPDATER = range(1, 12) SCREENSHOT_READ = 0x0C CONSOLE_FILTER = 0x0D +SETTINGS = 0x0E FILE_LIST, FILE_READ, FILE_WRITE, FILE_DELETE, MKDIR, FILE_STAT, FILE_CLOSE = range(0x10, 0x17) #: one FILE_WRITE: the frame payload is at most 4096 bytes, of which 6 + the path are the header @@ -209,6 +210,11 @@ def console_filter(self, console: str | None = None) -> dict: return self._call(CONSOLE_FILTER, b"") return self._call(CONSOLE_FILTER, (console or "all").encode()) + def settings(self, change: str | None = None) -> dict: + """The launcher's settings ({settings, limits}); `change` ("name=value") + sets one first (protocol 4).""" + return self._call(SETTINGS, (change or "").encode()) + def reload_roms(self) -> int: return self._call(RELOAD_ROMS)["total"] diff --git a/web/README.md b/web/README.md new file mode 100644 index 0000000..0b424c4 --- /dev/null +++ b/web/README.md @@ -0,0 +1,33 @@ +# Emulator Console (web) + +The page esp-box-emu and tab5-emu advertise as their WebUSB landing page +(`esp-cpp.github.io/esp-box-emu/`, `esp-cpp.github.io/tab5-emu/`): Chrome or +Edge offers it when the emulator is plugged in. It talks to the device's link +(the vendor interface, the same protocol as `tools/emulink`) and its console +(the CDC port, with Web Serial). + +- **Dashboard**: what runs, frame rate, memory, firmware, uptime, last crash, + and the SD card's USB drive mode. +- **Screen**: the game's (or the launcher's) screen, live, with an on-screen + controller (or the keyboard), save states and quit. +- **Library**: the games by console with their boxart; play, filter (the + launcher too), add a game (ROM + boxart + metadata.csv), remove one. +- **Files**: browse the SD card, download, upload (drag and drop), new + folder, delete. +- **Settings**: volume, mute, brightness, video scaling, resume last save + (haptics on the box), as in the launcher. +- **System**: chip, partitions, reset reason, the services on the link, + restart (or into download mode), and the firmware update (the updater with + the espp OTA console). The generic services open in their espp web apps. +- **Console**: the console log, filtered, saved. + +Plain HTML / CSS / ES modules, no build step. `link.js` is the protocol +(stream_frame frames, emu.control, the espp system service), `app.js` the +page. The files are the same in both repositories (like `tools/emulink`). + +Try it locally: `python3 -m http.server -d web 8000`, then open +http://localhost:8000 (WebUSB needs https or localhost). Only one program can +use the link at a time: close `emulink` first. + +The pages workflow (`.github/workflows/pages.yml`) publishes this folder +on a push to main. diff --git a/web/app.css b/web/app.css new file mode 100644 index 0000000..35daada --- /dev/null +++ b/web/app.css @@ -0,0 +1,196 @@ +:root { + --bg: #0f1216; + --bg2: #161b21; + --card: #1b2129; + --line: #2a323c; + --text: #e8ecf1; + --muted: #93a0ae; + --accent: #e5484d; + --accent2: #3e8ef7; + --ok: #30a46c; + --warn: #f5a524; + --bad: #e5484d; + --radius: 12px; + color-scheme: dark; +} +@media (prefers-color-scheme: light) { + :root:not([data-theme="dark"]) { + --bg: #f4f6f8; --bg2: #ffffff; --card: #ffffff; --line: #dde3ea; --text: #15191e; --muted: #5d6874; + color-scheme: light; + } +} +* { box-sizing: border-box; } +html, body { margin: 0; background: var(--bg); color: var(--text); } +body { font: 15px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; min-height: 100vh; display: flex; flex-direction: column; } +code, pre, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; } +a { color: var(--accent2); } +[hidden] { display: none !important; } + +.topbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 20px; background: var(--bg2); border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 5; flex-wrap: wrap; } +.brand { display: flex; align-items: center; gap: 12px; } +.brand-icon { width: 40px; height: 40px; fill: var(--accent); } +.brand-icon .hole { fill: #fff; } +.brand-title { font-weight: 700; font-size: 17px; } +.brand-sub { color: var(--muted); font-size: 13px; } +.topbar-right { display: flex; align-items: center; gap: 10px; } + +.pill { flex-shrink: 0; display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border-radius: 999px; background: var(--card); border: 1px solid var(--line); color: var(--muted); font-size: 13px; white-space: nowrap; } +.pill::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); } +.pill.ok { color: var(--text); } .pill.ok::before { background: var(--ok); } +.pill.playing::before { background: var(--accent2); } +.pill.warn::before { background: var(--warn); } +.pill.bad::before { background: var(--bad); } + +.btn { appearance: none; border: 1px solid var(--line); background: var(--card); color: var(--text); padding: 7px 14px; border-radius: 8px; font: inherit; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } +.btn:hover:not(:disabled) { border-color: var(--muted); } +.btn:disabled { opacity: .5; cursor: default; } +.btn.primary { background: var(--accent2); border-color: var(--accent2); color: #fff; } +.btn.danger { background: var(--bad); border-color: var(--bad); color: #fff; } +.btn.big { padding: 12px 22px; font-size: 16px; } +.btn.small { padding: 3px 9px; font-size: 13px; } + +.tabs { display: flex; gap: 2px; padding: 0 16px; background: var(--bg2); border-bottom: 1px solid var(--line); overflow-x: auto; } +.tabs button { appearance: none; background: none; border: 0; color: var(--muted); font: inherit; padding: 11px 14px; cursor: pointer; border-bottom: 2px solid transparent; white-space: nowrap; } +.tabs button.active { color: var(--text); border-bottom-color: var(--accent); } +.tabs button:disabled { opacity: .4; cursor: default; } + +main { flex: 1; padding: 20px; max-width: 1320px; width: 100%; margin: 0 auto; } +.notice { background: #3a2a12; border: 1px solid var(--warn); padding: 12px 16px; border-radius: var(--radius); margin-bottom: 16px; } +.welcome { max-width: 640px; margin: 8vh auto; text-align: center; } +.welcome h1 { font-size: 28px; margin-bottom: 8px; } +.muted { color: var(--muted); } +.small { font-size: 13px; } +.hint { color: var(--muted); font-size: 13px; margin: 8px 0 0; } +.row { display: flex; align-items: center; flex-wrap: wrap; } +.col { display: flex; flex-direction: column; align-items: flex-start; } +.gap { gap: 8px; } +.end { justify-content: flex-end; } + +.grid.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); gap: 16px; } +.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 16px 18px; min-width: 0; } +.card.wide { grid-column: 1 / -1; } +.card.slim { padding: 12px 14px; margin-top: 14px; } +.card.danger { border-color: var(--bad); } +.card h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 0 0 12px; font-weight: 600; } +.card h3 { margin: 0 0 10px; font-size: 15px; } +.kv { display: grid; grid-template-columns: auto 1fr; gap: 4px 14px; margin: 0; } +.kv dt { color: var(--muted); } +.kv dd { margin: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } +.kv.two { grid-template-columns: auto 1fr auto 1fr; } +@media (max-width: 720px) { .kv.two { grid-template-columns: auto 1fr; } } +pre { white-space: pre-wrap; margin: 0; } +.spark { width: 100%; height: 56px; margin-top: 10px; display: block; } + +.now { display: flex; gap: 18px; align-items: center; } +.now-art { width: 92px; height: 92px; border-radius: 10px; background: var(--bg); display: flex; align-items: center; justify-content: center; overflow: hidden; flex: none; } +.now-art img { max-width: 100%; max-height: 100%; } +.now-art img:not([src]) { display: none; } +.now-state { color: var(--muted); font-size: 13px; text-transform: uppercase; letter-spacing: .05em; } +.now-game { font-size: 22px; font-weight: 650; margin: 2px 0 6px; } +.now-console { margin-bottom: 10px; } + +.badge { display: inline-flex; align-items: center; padding: 2px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; color: #fff; background: #606060; white-space: nowrap; } + +.mem { display: grid; gap: 8px; } +.mem-row { display: grid; grid-template-columns: 64px auto 1fr; gap: 10px; align-items: baseline; font-size: 13px; } +.mem-row .strong { color: var(--text); font-weight: 600; } +.mem-legend { display: flex; gap: 14px; font-size: 12px; color: var(--muted); margin-top: 6px; } +.mem-legend i { display: inline-block; width: 10px; height: 3px; vertical-align: middle; margin-right: 5px; } +.bar { height: 8px; border-radius: 4px; background: var(--bg); overflow: hidden; } +.bar > i { display: block; height: 100%; background: var(--accent2); } +.mem-row .num { font-variant-numeric: tabular-nums; color: var(--muted); } + +/* screen */ +.screen-layout { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 20px; align-items: start; } +@media (max-width: 900px) { .screen-layout { grid-template-columns: 1fr; } } +.screen-wrap { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; } +#screen { max-width: 100%; max-height: 68vh; width: auto; height: auto; aspect-ratio: auto; background: #000; border-radius: 6px; image-rendering: pixelated; display: block; margin: 0 auto; min-width: min(100%, 480px); object-fit: contain; } +.screen-bar { display: flex; justify-content: space-between; align-items: center; margin: 8px 0; gap: 10px; min-height: 22px; } +.screen-bar progress { width: 160px; } +.toggle { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; } + +.pad { background: var(--card); border: 1px solid var(--line); border-radius: 28px; padding: 14px 18px; user-select: none; touch-action: none; } +.pad button { appearance: none; border: 0; font: inherit; color: #fff; cursor: pointer; } +.pad button.down-now { filter: brightness(1.5); transform: scale(.95); } +.shoulders, .meta { display: flex; justify-content: space-between; gap: 10px; } +.shoulders button { flex: 1; background: #3a434e; border-radius: 10px; padding: 6px; } +.meta { justify-content: center; margin-top: 8px; } +.meta button { background: #3a434e; border-radius: 999px; padding: 4px 14px; font-size: 12px; } +.pad-main { display: flex; justify-content: space-between; align-items: center; margin: 12px 0 4px; } +.dpad { display: grid; grid-template: repeat(3, 38px) / repeat(3, 38px); } +.dpad button { background: #3a434e; } +.dpad .up { grid-area: 1 / 2; border-radius: 8px 8px 0 0; } +.dpad .left { grid-area: 2 / 1; border-radius: 8px 0 0 8px; } +.dpad .right { grid-area: 2 / 3; border-radius: 0 8px 8px 0; } +.dpad .down { grid-area: 3 / 2; border-radius: 0 0 8px 8px; } +.face { display: grid; grid-template: repeat(3, 38px) / repeat(3, 38px); } +.face button { border-radius: 50%; font-weight: 700; } +.face .x { grid-area: 1 / 2; background: #3e8ef7; } +.face .y { grid-area: 2 / 1; background: #30a46c; } +.face .a { grid-area: 2 / 3; background: #e5484d; } +.face .b { grid-area: 3 / 2; background: #f5a524; } +select, input:not([type]), input[type=search], input[type=text], input[type=number] { background: var(--bg); color: var(--text); border: 1px solid var(--line); border-radius: 8px; padding: 7px 10px; font: inherit; min-width: 0; } + +/* library */ +.lib-tools, .files-tools, .console-tools { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; } +.lib-tools input[type=search] { flex: 1; min-width: 180px; } +.chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; } +.chip { appearance: none; border: 1px solid var(--line); background: var(--card); color: var(--text); border-radius: 999px; padding: 5px 12px; font: inherit; font-size: 13px; cursor: pointer; display: inline-flex; gap: 8px; align-items: center; } +.chip .dot { width: 10px; height: 10px; border-radius: 50%; } +.chip .n { color: var(--muted); } +.chip.active { border-color: var(--text); background: var(--bg2); } +.lib-group h3 { display: flex; align-items: center; gap: 10px; margin: 22px 0 10px; font-size: 16px; } +.lib-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 14px; } +.game { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; display: flex; flex-direction: column; } +.game.playing { border-color: var(--accent2); box-shadow: 0 0 0 1px var(--accent2); } +.game .art { aspect-ratio: 3 / 4; background: var(--bg); display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 12px; overflow: hidden; } +.game .art img { width: 100%; height: 100%; object-fit: contain; } +.game .body { padding: 9px 10px 10px; display: flex; flex-direction: column; gap: 8px; flex: 1; } +.game .title { font-size: 13px; font-weight: 600; line-height: 1.3; } +.game .actions { display: flex; gap: 6px; margin-top: auto; } +.game .actions .btn { flex: 1; justify-content: center; } +.add-game { margin-bottom: 16px; } +.form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; margin-bottom: 12px; } +.form-grid label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; color: var(--muted); } + +/* files */ +.crumbs { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; flex: 1; } +.crumbs button { appearance: none; background: none; border: 0; color: var(--accent2); font: inherit; cursor: pointer; padding: 2px 4px; } +.crumbs span { color: var(--muted); } +.drop { position: relative; background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; } +.drop.over { border-color: var(--accent2); } +.drop-hint { display: none; position: absolute; inset: 0; align-items: center; justify-content: center; background: rgba(62, 142, 247, .15); font-weight: 600; } +.drop.over .drop-hint { display: flex; } +table { width: 100%; border-collapse: collapse; } +th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid var(--line); } +th { color: var(--muted); font-weight: 500; font-size: 13px; } +td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } +td.acts { text-align: right; white-space: nowrap; } +.files tr:last-child td { border-bottom: 0; } +.file-name { appearance: none; background: none; border: 0; color: inherit; font: inherit; cursor: pointer; padding: 0; text-align: left; } +.file-name.dir { color: var(--accent2); } +.transfer { display: flex; gap: 12px; align-items: center; margin-top: 10px; } +.transfer progress { flex: 1; } + +/* settings */ +.settings { max-width: 640px; } +.settings-form { display: grid; gap: 18px; } +.setting { display: grid; grid-template-columns: 170px 1fr 48px; gap: 12px; align-items: center; } +.setting label { font-weight: 550; } +.setting output { text-align: right; font-variant-numeric: tabular-nums; color: var(--muted); } +.setting input[type=range] { width: 100%; accent-color: var(--accent2); } + +/* system */ +.modules td code { font-size: 13px; } + +/* console */ +.console-tools input[type=search] { flex: 1; min-width: 160px; } +.log { background: #0a0c0f; color: #cfd6de; border: 1px solid var(--line); border-radius: var(--radius); padding: 12px; height: 62vh; overflow: auto; font-size: 12.5px; line-height: 1.4; white-space: pre-wrap; overflow-wrap: anywhere; } +.log .I { color: #6fd08c; } .log .W { color: #f5c451; } .log .E { color: #ff7b7b; } .log .D, .log .V { color: #8a96a3; } + +.modal { position: fixed; inset: 0; background: rgba(0, 0, 0, .55); display: flex; align-items: center; justify-content: center; z-index: 20; padding: 16px; } +.modal-box { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 20px; max-width: 460px; width: 100%; } +.modal-box h3 { margin-top: 0; } +.toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: var(--card); border: 1px solid var(--line); padding: 10px 16px; border-radius: 10px; z-index: 30; max-width: calc(100% - 32px); box-shadow: 0 8px 24px rgba(0, 0, 0, .35); } +.toast.err { border-color: var(--bad); } +.foot { text-align: center; color: var(--muted); font-size: 13px; padding: 18px; } diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..576c379 --- /dev/null +++ b/web/app.js @@ -0,0 +1,868 @@ +// Emulator Console: the web app the emulators advertise as their WebUSB +// landing page. Shared, byte for byte, by esp-box-emu and tab5-emu. +import { BUTTONS, Control, ControlError, DEVICES, MODULE, PID, ROOT, UsbLink, VID, rgb565ToImageData } from "./link.js"; + +const $ = (id) => document.getElementById(id); +const h = (tag, attrs = {}, ...kids) => { + const e = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; + if (k === "class") e.className = v; + else if (k.startsWith("on")) e.addEventListener(k.slice(2), v); + else if (k === "style") e.style.cssText = v; + else e.setAttribute(k, v === true ? "" : v); + } + for (const kid of kids.flat()) if (kid != null && kid !== false) e.append(kid.nodeType ? kid : String(kid)); + return e; +}; + +// the consoles' accent colors (rom_info.cpp, both firmwares) +const CONSOLE_COLORS = { + nes: "#B22222", snes: "#6A5ACD", gb: "#5B7F3A", gbc: "#8E44AD", sms: "#1F5FAF", gg: "#4F6D8F", + genesis: "#C8102E", msx: "#3A7D7D", pc: "#5A6B7B", pico8: "#FF004D", gba: "#4B3FA8", playstation: "#2E6DB4", + other: "#606060", +}; +const ESPP_APPS = "https://esp-cpp.github.io/espp/apps/"; + +const state = { + link: null, ctl: null, discovery: null, status: null, roms: [], romsLoaded: false, + tab: "dashboard", statusTimer: null, lastFrames: null, fpsHistory: [], memHistory: [], + filter: "", search: "", cwd: ROOT, files: [], live: false, lastShot: null, slot: 1, + boxart: new Map(), boxartQueue: [], boxartBusy: false, settings: null, serial: null, + // a device that comes back is opened again without the chooser, unless the + // page let go of it on purpose (Disconnect, or a hand-off to another app) + autoReconnect: true, + session: 0, // bumped on every disconnect: replies for an older one are dropped +}; + +// ------------------------------------------------------------------ helpers -- +function toast(text, err = false) { + const t = $("toast"); + t.textContent = text; t.className = "toast" + (err ? " err" : ""); t.hidden = false; + clearTimeout(toast.timer); + toast.timer = setTimeout(() => (t.hidden = true), err ? 6000 : 3000); +} + +function confirmModal(title, text, ok = "OK") { + return new Promise((resolve) => { + $("modalTitle").textContent = title; $("modalText").textContent = text; $("modalOk").textContent = ok; + // the page behind is inert (no Tab or clicks into it) until the answer + confirmModal.pending?.(false); // (a question still open is answered "no") + const back = [...document.body.children].filter((e) => e !== $("modal") && e !== $("toast") && !e.inert); + const opener = document.activeElement; + for (const e of back) e.inert = true; + $("modal").hidden = false; $("modalOk").focus(); + const done = (v) => { + confirmModal.pending = null; + $("modal").hidden = true; $("modalOk").onclick = $("modalCancel").onclick = $("modal").onkeydown = null; + for (const e of back) e.inert = false; + opener?.focus?.(); + resolve(v); + }; + $("modalOk").onclick = () => done(true); + $("modalCancel").onclick = () => done(false); + confirmModal.pending = done; + $("modal").onkeydown = (ev) => { + if (ev.key === "Escape") { ev.preventDefault(); done(false); } + // Tab stays on the two buttons + if (ev.key === "Tab") { ev.preventDefault(); (document.activeElement === $("modalOk") ? $("modalCancel") : $("modalOk")).focus(); } + }; + }); +} + +const fmtBytes = (n) => n == null ? "—" : n >= 1 << 20 ? (n / (1 << 20)).toFixed(2) + " MB" : n >= 1024 ? (n / 1024).toFixed(1) + " KB" : n + " B"; +const fmtUptime = (ms) => { + if (ms == null) return "—"; + const s = Math.floor(ms / 1000), d = Math.floor(s / 86400), hh = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60); + return (d ? d + "d " : "") + (d || hh ? hh + "h " : "") + m + "m " + (s % 60) + "s"; +}; +const basename = (p) => p.split("/").filter(Boolean).pop() || p; +const dirname = (p) => p.replace(/\/[^/]*\/?$/, "") || ROOT; +const badge = (key, name) => h("span", { class: "badge", style: `background:${CONSOLE_COLORS[key] || CONSOLE_COLORS.other}` }, name || key); + +async function guarded(fn, okText) { + try { + const r = await fn(); + if (okText) toast(okText); + return r; + } catch (e) { + toast(e.message || String(e), true); + return undefined; + } +} + +function download(name, data, type = "application/octet-stream") { + const url = URL.createObjectURL(new Blob([data], { type })); + const a = h("a", { href: url, download: name }); + document.body.append(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 5000); +} + +// -------------------------------------------------------------- connection -- +async function connect(device) { + if (state.link) await disconnect(); + setPill("", "Connecting…"); + let link; + try { + link = device ? new UsbLink(device) : await UsbLink.request(); + await link.open(); + } catch (e) { + setPill("", "Not connected"); + if (e && e.name === "NotFoundError") return; // the chooser was closed + const busy = /claim|access|busy|in use/i.test(String(e.message || e)); + toast(busy ? "The link is in use: close emulink (or another tab using it) and connect again." : (e.message || String(e)), true); + try { await link?.close(); } catch (_) {} + return; + } + state.link = link; + state.ctl = new Control(link); + state.autoReconnect = true; + // input a page lost track of (its link died with a button held) is let go + state.ctl.buttons(0, 0).catch(() => {}); + link.onclose = () => onLinkLost(); + try { state.discovery = await link.discover(); } catch (_) { state.discovery = null; } + if (state.link !== link) return; // (lost while discovering: already shown as disconnected) + try { localStorage.setItem("emu-console-serial", link.serial); } catch (_) {} + $("connectBtn").hidden = true; $("disconnectBtn").hidden = false; + $("welcome").hidden = true; + $("deviceSub").textContent = `${link.known.name} · ${link.serial || "?"}`; + document.title = `${link.known.name} · Emulator Console`; + const control = state.discovery?.modules.find((m) => m.id === MODULE.CONTROL); + if (state.discovery && !control) toast("This device has no emulator control module", true); + else if (control && control.version < 4) toast(`Firmware speaks control protocol ${control.version}: update it for every feature here (4).`, true); + showTab(state.tab); + if (state.tab !== "library") loadLibrary().catch(() => {}); // (the names for the status) + pollStatus(); + state.statusTimer = setInterval(pollStatus, 1000); +} + +async function disconnect() { + clearInterval(state.statusTimer); state.statusTimer = null; + stopLive(); + const link = state.link, ctl = state.ctl; + state.session++; + state.link = null; state.ctl = null; state.status = null; state.romsLoaded = false; state.settings = null; + // a button held from this page would stay pressed in the game + if (heldMask && ctl) { + await Promise.race([ctl.buttons(0, 0).catch(() => {}), new Promise((r) => setTimeout(r, 500))]); + } + releasePad(); + clearDeviceCaches(); + if (link) { link.onclose = null; await link.close(); } + $("connectBtn").hidden = false; $("disconnectBtn").hidden = true; + $("welcome").hidden = false; + for (const p of document.querySelectorAll("[data-panel]")) p.hidden = true; + setPill("", "Not connected"); + $("deviceSub").textContent = "esp-box-emu · tab5-emu over USB"; +} + +function onLinkLost() { + const serial = state.link?.serial; + disconnect().then(() => { + setPill("warn", "Disconnected"); + if (!state.autoReconnect) return; // (handed off: the updater went down with it) + toast("The device went away (restarted or unplugged); it reconnects when it is back."); + state.waitingFor = serial; + }); +} + +// Images and the last screenshot belong to the device (and SD card) they came +// from: another board can have the same paths. +function clearDeviceCaches() { + for (const url of state.boxart.values()) if (url) URL.revokeObjectURL(url); + state.boxart.clear(); + for (const { done } of state.boxartQueue.splice(0)) done(null); + state.lastShot = null; + const c = $("screen"); c.getContext("2d").clearRect(0, 0, c.width, c.height); + $("screenInfo").textContent = ""; $("savePngBtn").disabled = true; +} + +// a device that comes back (after a restart) is opened again without the chooser +if (navigator.usb) { + navigator.usb.addEventListener("connect", (ev) => { + const ok = () => state.autoReconnect && !state.link && DEVICES[ev.device.serialNumber] && + (!state.waitingFor || ev.device.serialNumber === state.waitingFor); + if (ok()) setTimeout(() => { if (ok()) connect(ev.device); }, 1200); + }); +} + +function setPill(cls, text) { + const p = $("statusPill"); + p.className = "pill" + (cls ? " " + cls : ""); p.textContent = text; +} + +async function autoConnect() { + const q = new URLSearchParams(location.search); + const wanted = q.get("serial") || (() => { try { return localStorage.getItem("emu-console-serial"); } catch (_) { return null; } })(); + const devs = await UsbLink.permitted(); + const dev = devs.find((d) => d.serialNumber === wanted) || devs.find((d) => DEVICES[d.serialNumber]); + if (dev && (q.get("autoconnect") || DEVICES[dev.serialNumber])) connect(dev); +} + +// ----------------------------------------------------------------- status -- +async function pollStatus() { + if (!state.ctl || pollStatus.busy) return; + pollStatus.busy = true; + try { + const st = await state.ctl.status(); + const now = performance.now(); + if (state.lastFrames) { + const dt = (now - state.lastFrames.t) / 1000; + const fps = dt > 0 ? (st.frames_presented - state.lastFrames.n) / dt : 0; + state.fpsHistory.push(Math.max(0, fps)); + if (state.fpsHistory.length > 120) state.fpsHistory.shift(); + } + state.lastFrames = { t: now, n: st.frames_presented }; + state.memHistory.push([st.internal_free, st.psram_free]); + if (state.memHistory.length > 120) state.memHistory.shift(); + const prev = state.status; + state.status = st; + renderStatus(prev); + } catch (e) { + if (state.link) setPill("warn", "Busy"); + } finally { + pollStatus.busy = false; + } +} + +function renderStatus(prev) { + const st = state.status; + if (!st) return; + const rom = state.roms.find((r) => r.path === st.rom); + if (st.usb_drive) setPill("warn", "SD card on the PC"); + else if (st.state === "game") setPill("playing", "Playing " + (rom?.name || basename(st.rom))); + else setPill("ok", "In the launcher"); + + $("nowState").textContent = st.state === "game" ? "Playing" : "In the launcher"; + $("nowGame").textContent = st.state === "game" ? (rom?.name || basename(st.rom)) : "No game running"; + $("nowConsole").replaceChildren(st.state === "game" && st.console ? badge(rom?.key, st.console) : ""); + $("nowQuitBtn").hidden = st.state !== "game"; + const art = st.state === "game" && rom?.boxart ? state.boxart.get(rom.boxart) : null; + if (art) $("nowArt").src = art; else $("nowArt").removeAttribute("src"); + if (st.state === "game" && rom?.boxart && !state.boxart.has(rom.boxart)) queueBoxart(rom.boxart, () => renderStatus()); + + const fps = state.fpsHistory.at(-1); + $("fps").textContent = fps == null ? "—" : fps.toFixed(1) + " / s"; + $("dropped").textContent = st.frames_dropped; + $("gameFrames").textContent = st.state === "game" ? st.game_frames : "—"; + drawSpark($("fpsSpark"), [state.fpsHistory], ["#3e8ef7"]); + const memRow = (label, free, largest, min) => h("div", { class: "mem-row" }, + h("span", {}, label), + h("span", { class: "num strong" }, fmtBytes(free) + " free"), + h("span", { class: "num" }, `largest ${fmtBytes(largest)}` + (min != null ? ` · lowest ${fmtBytes(min)}` : ""))); + $("memRows").replaceChildren( + memRow("Internal", st.internal_free, st.internal_largest, st.internal_min_free), + memRow("PSRAM", st.psram_free, st.psram_largest, st.psram_min_free), + memRow("DMA", st.dma_free, st.dma_largest, null)); + drawSpark($("memSpark"), [state.memHistory.map((m) => m[0]), state.memHistory.map((m) => m[1])], ["#30a46c", "#f5a524"]); + $("fw").textContent = st.firmware; $("built").textContent = st.built; + $("partition").textContent = st.partition + (st.elf_sha256 ? ` · ${st.elf_sha256}` : ""); + $("uptime").textContent = fmtUptime(st.uptime_ms); + $("reset").textContent = ({ 1: "power-on", 3: "software", 4: "panic", 5: "interrupt WDT", 6: "task WDT", 7: "other WDT", 9: "brownout", 11: "USB" })[st.reset_reason] || `#${st.reset_reason}`; + $("driveText").textContent = st.usb_drive ? "The PC has the SD card (a USB drive)." : "The emulator has the SD card."; + $("driveBtn").textContent = st.usb_drive ? "Take the SD card back" : "Give the SD card to this PC"; + $("panicCard").hidden = !st.last_panic; + $("panicText").textContent = st.last_panic || ""; + $("coredumpLink").href = handoffUrl("coredump_console.html", MODULE.COREDUMP); + // the game started or ended: the list, the screen and the buttons follow + if (prev && (prev.state !== st.state || prev.rom !== st.rom)) { + if (state.tab === "library") renderLibrary(); + if (state.tab === "screen" && !state.live) capture(); + } + if (prev?.usb_drive && !st.usb_drive) forgetBoxartFailures(); + if (prev && prev.filter !== st.filter && state.tab === "library") { state.filter = st.filter || ""; renderLibrary(); } +} + +function drawSpark(canvas, series, colors) { + const dpr = window.devicePixelRatio || 1, w = canvas.clientWidth || 300, hh = canvas.clientHeight || 56; + if (canvas.width !== w * dpr) { canvas.width = w * dpr; canvas.height = hh * dpr; } + const g = canvas.getContext("2d"); + g.setTransform(dpr, 0, 0, dpr, 0, 0); + g.clearRect(0, 0, w, hh); + series.forEach((s, k) => { + if (s.length < 2) return; + const max = Math.max(...s) * 1.1 || 1, min = 0; + g.strokeStyle = colors[k]; g.lineWidth = 1.5; g.beginPath(); + s.forEach((v, i) => { + const x = (i / (s.length - 1)) * w, y = hh - 2 - ((v - min) / (max - min)) * (hh - 4); + i ? g.lineTo(x, y) : g.moveTo(x, y); + }); + g.stroke(); + }); +} + +// ------------------------------------------------------------------- tabs -- +function showTab(tab) { + state.tab = tab; + for (const b of document.querySelectorAll("#tabs button")) b.classList.toggle("active", b.dataset.tab === tab); + if (!state.link) return; + for (const p of document.querySelectorAll("[data-panel]")) p.hidden = p.dataset.panel !== tab; + if (tab !== "screen") stopLive(); + if (tab === "library") loadLibrary(); + if (tab === "files") loadFiles(state.cwd); + if (tab === "settings") loadSettings(); + if (tab === "system") loadSystem(); + if (tab === "screen" && !state.lastShot) capture(); +} + +// ----------------------------------------------------------------- screen -- +async function capture() { + if (!state.ctl || capture.busy) return; + capture.busy = true; + const prog = $("screenProgress"); + const t0 = performance.now(), session = state.session; + try { + const f = await state.ctl.frame((n, total) => { prog.hidden = false; prog.max = total; prog.value = n; }); + if (session !== state.session) return; // (disconnected meanwhile) + const c = $("screen"); + c.width = f.width; c.height = f.height; + c.getContext("2d").putImageData(rgb565ToImageData(f.data, f.width, f.height, f.format === "rgb565be"), 0, 0); + state.lastShot = f; + $("screenInfo").textContent = `${f.source === "launcher" ? "Launcher" : "Game"} · ${f.width}×${f.height} · ${Math.round(performance.now() - t0)} ms`; + $("savePngBtn").disabled = false; + } catch (e) { + $("screenInfo").textContent = e.message || String(e); + } finally { + prog.hidden = true; + capture.busy = false; + } +} + +async function liveLoop() { + while (state.live && state.ctl && state.tab === "screen") { + await capture(); + await new Promise((r) => setTimeout(r, 150)); + } +} +function stopLive() { state.live = false; $("liveToggle").checked = false; } + +let heldMask = 0; +const setButtons = (mask) => { + heldMask = mask; + if (state.ctl) state.ctl.buttons(mask, 0).catch((e) => toast("Buttons: " + (e.message || e), true)); +}; +// forget the held buttons (the link is going: the device side is released by the caller) +function releasePad() { + heldMask = 0; + for (const b of document.querySelectorAll("#pad .down-now")) b.classList.remove("down-now"); +} +function initPad() { + for (const b of document.querySelectorAll("#pad [data-btn]")) { + const bit = BUTTONS[b.dataset.btn]; + const down = (ev) => { ev.preventDefault(); b.classList.add("down-now"); b.setPointerCapture?.(ev.pointerId); setButtons(heldMask | bit); }; + const up = () => { if (!(heldMask & bit)) return; b.classList.remove("down-now"); setButtons(heldMask & ~bit); }; + b.addEventListener("pointerdown", down); + b.addEventListener("pointerup", up); + b.addEventListener("pointercancel", up); + b.addEventListener("lostpointercapture", up); + // the keyboard's activation keys on a focused pad button press that button + const activate = (ev) => ev.key === "Enter" || ev.key === " "; + b.addEventListener("keydown", (ev) => { + if (!activate(ev)) return; + ev.preventDefault(); ev.stopPropagation(); + if (!ev.repeat) { b.classList.add("down-now"); setButtons(heldMask | bit); } + }); + b.addEventListener("keyup", (ev) => { if (activate(ev)) { ev.stopPropagation(); up(); } }); + b.addEventListener("blur", up); + } + const keys = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right", z: "a", x: "b", a: "x", s: "y", q: "l", w: "r", Enter: "start", Shift: "select" }; + const keyBit = (ev) => BUTTONS[keys[ev.key] || keys[ev.key.toLowerCase()]]; + addEventListener("keydown", (ev) => { + if (state.tab !== "screen" || (ev.target instanceof Element && ev.target.matches("input, select, textarea")) || ev.repeat) return; + // (Enter / Space on a focused control activate it: Save, Load, Capture...) + if ((ev.key === "Enter" || ev.key === " ") && ev.target instanceof Element && ev.target.closest("button, a")) return; + const bit = keyBit(ev); + if (!bit) return; + ev.preventDefault(); setButtons(heldMask | bit); + }); + addEventListener("keyup", (ev) => { + const bit = keyBit(ev); + if (bit && heldMask & bit) setButtons(heldMask & ~bit); + }); + addEventListener("blur", () => { if (heldMask) setButtons(0); }); +} + +// ---------------------------------------------------------------- library -- +async function loadLibrary(force = false) { + if (!state.ctl) return; + if (!state.romsLoaded || force) { + const roms = await guarded(() => state.ctl.roms()); + if (!roms) return; + state.roms = roms; state.romsLoaded = true; + forgetBoxartFailures(); + state.filter = state.status?.filter || ""; + const folders = [...new Set(roms.map((r) => dirname(r.path).slice(ROOT.length + 1)).filter(Boolean))].sort(); + $("folders").replaceChildren(...folders.map((f) => h("option", { value: f }))); + } + renderLibrary(); +} + +function renderLibrary() { + const consoles = []; + for (const r of state.roms) { + let c = consoles.find((x) => x.key === r.key); + if (!c) consoles.push(c = { key: r.key, name: r.console, n: 0 }); + c.n++; + } + const chip = (key, name, n) => h("button", { class: "chip" + (state.filter === key ? " active" : ""), onclick: () => pickFilter(key) }, + key ? h("span", { class: "dot", style: `background:${CONSOLE_COLORS[key] || CONSOLE_COLORS.other}` }) : null, name, h("span", { class: "n" }, n)); + $("chips").replaceChildren(chip("", "All consoles", state.roms.length), ...consoles.map((c) => chip(c.key, c.name, c.n))); + + const q = state.search.trim().toLowerCase(); + const playing = state.status?.state === "game" ? state.status.rom : null; + const groups = consoles.filter((c) => !state.filter || c.key === state.filter).map((c) => { + const games = state.roms.filter((r) => r.key === c.key && (!q || r.name.toLowerCase().includes(q) || r.path.toLowerCase().includes(q))); + if (!games.length) return null; + return h("section", { class: "lib-group" }, + h("h3", {}, badge(c.key, c.name), h("span", { class: "muted small" }, games.length + (games.length === 1 ? " game" : " games"))), + h("div", { class: "lib-grid" }, games.map((r) => gameCard(r, playing)))); + }).filter(Boolean); + $("lib").replaceChildren(...(groups.length ? groups : [h("p", { class: "muted" }, state.roms.length ? "No game matches." : "No games: add metadata.csv to the SD card, or add a game above.")])); + observeArt(); +} + +function gameCard(r, playing) { + const isPlaying = playing === r.path; + const img = h("img", { alt: "", "data-art": r.boxart || null }); + const cached = r.boxart && state.boxart.get(r.boxart); + if (cached) img.src = cached; + return h("article", { class: "game" + (isPlaying ? " playing" : ""), title: r.path }, + h("div", { class: "art" }, r.boxart ? img : "no boxart"), + h("div", { class: "body" }, + h("div", { class: "title" }, r.name), + h("div", { class: "actions" }, + isPlaying + ? h("button", { class: "btn small", onclick: () => guarded(() => state.ctl.quit(), "Quit") }, "Quit") + : h("button", { class: "btn small primary", disabled: !!playing || state.status?.usb_drive, onclick: () => launch(r) }, "Play"), + h("button", { class: "btn small", title: "Take it out of metadata.csv (the file stays on the card)", onclick: () => removeGame(r) }, "Remove")))); +} + +async function launch(r) { + await guarded(() => state.ctl.launch(r.path), "Starting " + r.name); + pollStatus(); +} + +async function removeGame(r) { + if (!(await confirmModal("Remove " + r.name + "?", "It is taken out of metadata.csv; the ROM stays on the SD card.", "Remove"))) return; + if (await guarded(() => state.ctl.addRom(r.path, r.name, "", true), "Removed " + r.name) !== undefined) loadLibrary(true); +} + +async function pickFilter(key) { + state.filter = key; + renderLibrary(); + if ($("syncFilter").checked) await guarded(() => state.ctl.consoleFilter(key)); +} + +let artObserver = null; +function observeArt() { + artObserver?.disconnect(); + artObserver = new IntersectionObserver((entries) => { + for (const e of entries) { + if (!e.isIntersecting) continue; + const img = e.target, path = img.dataset.art; + artObserver.unobserve(img); + if (!path || img.src) continue; + queueBoxart(path, (url) => { if (url) img.src = url; }); + } + }, { rootMargin: "200px" }); + for (const img of document.querySelectorAll("#lib img[data-art]")) if (!img.src) artObserver.observe(img); +} + +// Missing box art is not asked for again on every status poll, only once the +// card may have changed: the library reloaded, or the card back from the PC. +function forgetBoxartFailures() { + for (const [path, url] of state.boxart) if (!url) state.boxart.delete(path); +} + +function queueBoxart(path, done) { + if (state.boxart.has(path)) { done(state.boxart.get(path)); return; } + state.boxartQueue.push({ path, done }); + pumpBoxart(); +} +async function pumpBoxart() { + if (state.boxartBusy) return; + state.boxartBusy = true; + while (state.boxartQueue.length && state.ctl) { + const { path, done } = state.boxartQueue.shift(); + if (state.boxart.has(path)) { done(state.boxart.get(path)); continue; } + const session = state.session; + try { + const data = await state.ctl.readFile(path); + if (session !== state.session) { done(null); continue; } // (another connection's now) + const url = URL.createObjectURL(new Blob([data], { type: "image/jpeg" })); + state.boxart.set(path, url); + done(url); + } catch (_) { + if (session === state.session) state.boxart.set(path, null); + done(null); + } + } + state.boxartBusy = false; +} + +async function addGame(ev) { + ev.preventDefault(); + const rom = $("addRomFile").files[0], art = $("addArt").files[0]; + const folder = $("addFolder").value.trim().replace(/^\/+|\/+$/g, "").replace(/^sdcard\//, ""); + const name = $("addName").value.trim(); + if (!rom || !folder || !name) return; + const romPath = `${ROOT}/${folder}/${rom.name}`; + const artPath = art ? `${ROOT}/boxart/${art.name}` : ""; + const msg = $("addMsg"); + // every step on the board it started on (see uploadFiles) + const ctl = state.ctl; + const still = () => { if (state.ctl !== ctl) throw new Error("Disconnected: the game was not added"); }; + try { + msg.textContent = "Copying the ROM…"; + const romData = new Uint8Array(await rom.arrayBuffer()); + still(); + await ctl.writeFile(romPath, romData, (n, t) => (msg.textContent = `ROM ${Math.round((n / t) * 100)}%`)); + if (art) { + msg.textContent = "Copying the boxart…"; + const artData = new Uint8Array(await art.arrayBuffer()); + still(); + await ctl.writeFile(artPath, artData); + } + still(); + msg.textContent = "Adding to metadata.csv…"; + const total = await ctl.addRom(romPath, name, artPath ? artPath.slice(ROOT.length + 1) : ""); + msg.textContent = `Added: ${total} games now.`; + $("addGame").reset(); + loadLibrary(true); + } catch (e) { + msg.textContent = ""; + toast(e.message || String(e), true); + } +} + +// ------------------------------------------------------------------ files -- +async function loadFiles(path) { + const entries = await guarded(() => state.ctl.ls(path)); + if (!entries) return; + state.cwd = path; + state.files = entries.sort((a, b) => (b.dir - a.dir) || a.name.localeCompare(b.name)); + renderFiles(); +} + +function renderFiles() { + const parts = state.cwd.slice(ROOT.length).split("/").filter(Boolean); + const crumbs = [h("button", { onclick: () => loadFiles(ROOT) }, "SD card")]; + parts.forEach((p, i) => { + crumbs.push(h("span", {}, "/")); + crumbs.push(h("button", { onclick: () => loadFiles(ROOT + "/" + parts.slice(0, i + 1).join("/")) }, p)); + }); + $("crumbs").replaceChildren(...crumbs); + const rows = state.files.map((e) => { + const path = state.cwd + "/" + e.name; + return h("tr", {}, + h("td", {}, h("button", { class: "file-name" + (e.dir ? " dir" : ""), onclick: () => (e.dir ? loadFiles(path) : downloadFile(path, e.size)) }, (e.dir ? "📁 " : "") + e.name)), + h("td", { class: "num" }, e.dir ? "" : fmtBytes(e.size)), + h("td", { class: "acts" }, + e.dir ? null : h("button", { class: "btn small", onclick: () => downloadFile(path, e.size) }, "Download"), + " ", + h("button", { class: "btn small", onclick: () => deletePath(path, e.dir) }, "Delete"))); + }); + if (state.cwd !== ROOT) rows.unshift(h("tr", {}, h("td", { colspan: 3 }, h("button", { class: "file-name dir", onclick: () => loadFiles(dirname(state.cwd)) }, "⬑ up")))); + if (!state.files.length) rows.push(h("tr", {}, h("td", { colspan: 3, class: "muted" }, "Empty folder"))); + $("files").tBodies[0].replaceChildren(...rows); +} + +function transfer(text, n, total) { + $("transfer").hidden = !text; + $("transferText").textContent = text || ""; + $("transferProgress").max = total || 1; $("transferProgress").value = n || 0; +} + +async function downloadFile(path, size) { + try { + transfer("Downloading " + basename(path), 0, size); + const data = await state.ctl.readFile(path, (n, t) => transfer(`Downloading ${basename(path)} (${fmtBytes(n)} of ${fmtBytes(t)})`, n, t)); + download(basename(path), data); + } catch (e) { + toast(e.message || String(e), true); + } finally { + transfer(""); + } +} + +async function uploadFiles(files) { + // where they were dropped, on the device they were dropped on (the folder + // shown can change while they are copied) + const dir = state.cwd, ctl = state.ctl; + for (const f of files) { + if (state.ctl !== ctl) break; // (disconnected) + try { + const data = new Uint8Array(await f.arrayBuffer()); + if (state.ctl !== ctl) break; + await ctl.writeFile(dir + "/" + f.name, data, (n, t) => transfer(`Copying ${f.name} (${fmtBytes(n)} of ${fmtBytes(t)})`, n, t)); + } catch (e) { + toast(`${f.name}: ${e.message || e}`, true); + break; + } + } + transfer(""); + if (state.ctl === ctl) loadFiles(state.cwd); +} + +async function deletePath(path, dir) { + if (!(await confirmModal("Delete " + basename(path) + "?", dir ? "The folder and everything in it are deleted from the SD card." : "The file is deleted from the SD card.", "Delete"))) return; + await guarded(() => state.ctl.rm(path), "Deleted " + basename(path)); + loadFiles(state.cwd); +} + +// --------------------------------------------------------------- settings -- +const SETTING_INFO = { + volume: { label: "Volume", unit: "%" }, + muted: { label: "Mute", bool: true }, + brightness: { label: "Brightness", unit: "%" }, + video: { label: "Video scaling", options: ["Original", "Fit", "Fill"] }, + resume: { label: "Resume last save", bool: true }, + haptic: { label: "Haptic effect" }, +}; + +async function loadSettings() { + const r = await guarded(() => state.ctl.settings()); + if (!r) { $("settingsForm").replaceChildren(h("p", { class: "muted" }, "This firmware has no settings over USB (control protocol 4).")); return; } + state.settings = r; + // (a change still waiting when this connection ends is dropped, not sent to the next one) + const ctl = state.ctl, session = state.session; + const send = debounce((name, value) => { + if (state.session === session) guarded(() => ctl.settings(`${name}=${value}`)); + }, 250); + $("settingsForm").replaceChildren(...Object.entries(r.settings).map(([name, value]) => { + const info = SETTING_INFO[name] || { label: name }; + const [min, max] = r.limits[name] || [0, 100]; + const id = "set-" + name; + let input, out = h("output", { for: id }); + if (info.bool) { + input = h("input", { type: "checkbox", id, checked: !!value, onchange: (e) => send(name, e.target.checked ? 1 : 0) }); + input = h("label", { class: "toggle" }, input, value ? "On" : "Off"); + input.querySelector("input").addEventListener("change", (e) => (input.lastChild.textContent = e.target.checked ? "On" : "Off")); + } else if (info.options) { + input = h("select", { id, onchange: (e) => send(name, e.target.value) }, info.options.map((o, i) => h("option", { value: i, selected: i === value }, o))); + } else { + out.textContent = value + (info.unit || ""); + input = h("input", { type: "range", id, min, max, value, oninput: (e) => { out.textContent = e.target.value + (info.unit || ""); send(name, e.target.value); } }); + } + return h("div", { class: "setting" }, h("label", { for: id }, info.label), input, out); + })); +} + +function debounce(fn, ms) { + const timers = {}; + return (key, ...args) => { clearTimeout(timers[key]); timers[key] = setTimeout(() => fn(key, ...args), ms); }; +} + +// ----------------------------------------------------------------- system -- +async function loadSystem() { + const info = await guarded(() => state.ctl.info()); + const rows = []; + const add = (k, v) => { if (v != null && v !== "") rows.push(h("dt", {}, k), h("dd", {}, v)); }; + if (info) { + add("Chip", `${info.chip}${info.chip_revision != null ? " rev " + info.chip_revision : ""}${info.cores ? ", " + info.cores + " cores" : ""}${info.cpu_mhz ? " @ " + info.cpu_mhz + " MHz" : ""}`); + add("Project", info.project); add("Firmware", info.firmware); add("ESP-IDF", info.idf); + add("Built", [info.build_date, info.build_time].filter(Boolean).join(" ")); + add("Running from", info.running_partition); add("Boots from", info.boot_partition); add("OTA state", info.ota_state); + add("Flash", fmtBytes(info.flash_size)); add("PSRAM", fmtBytes(info.psram_size)); + add("Free heap", fmtBytes(info.free_heap)); add("Lowest free heap", fmtBytes(info.min_free_heap)); + add("Last reset", info.reset_reason); add("Uptime", fmtUptime(info.uptime_ms)); add("MAC", info.mac); + add("ELF SHA-256", info.elf_sha256 ? h("code", {}, info.elf_sha256.slice(0, 16) + "…") : null); + } + $("infoList").replaceChildren(...rows); + const mods = state.discovery?.modules || []; + const registry = await loadRegistry(); + $("modules").tBodies[0].replaceChildren(...mods.map((m) => { + const app = m.id === MODULE.CONTROL ? null : appFor(registry, m); + return h("tr", {}, + h("td", {}, `${m.name} `, h("span", { class: "muted small" }, `0x${m.id.toString(16).padStart(2, "0")}`)), + h("td", {}, h("code", {}, m.protocol ? `${m.protocol} v${m.version}` : "—")), + h("td", { class: "acts" }, app ? h("button", { class: "btn small", title: app, onclick: () => handOff(app, m.id) }, "Open app") + : m.id === MODULE.CONTROL ? h("span", { class: "muted small" }, "this page") : null)); + })); +} + +// espp's hosted apps and the protocols each speaks (the Device Hub's +// registry.js); a built-in table when it cannot be loaded +const FALLBACK_APPS = { "espp.ota": "ota_console.html", "espp.coredump": "coredump_console.html", "espp.system": "system_console.html", "espp.monitor": "system_console.html" }; +function loadRegistry() { + if (!loadRegistry.p) { + loadRegistry.p = new Promise((resolve) => { + if (window.ESPP_APPS) { resolve(window.ESPP_APPS); return; } + const s = h("script", { src: ESPP_APPS + "registry.js" }); + s.onload = () => resolve(window.ESPP_APPS || null); + s.onerror = () => resolve(null); + document.head.append(s); + setTimeout(() => resolve(window.ESPP_APPS || null), 4000); + }); + } + return loadRegistry.p; +} +function appFor(registry, m) { + const ok = (f) => typeof f === "string" && /^[\w.-]+\.html$/.test(f); + if (registry?.apps && m.protocol) { + const app = registry.apps.find((a) => (a.protocols || []).some((p) => p.id === m.protocol && !p.optional)) + || registry.apps.find((a) => (a.protocols || []).some((p) => p.id === m.protocol)); + if (app && ok(app.file)) return app.file; + } + if (FALLBACK_APPS[m.protocol]) return FALLBACK_APPS[m.protocol]; + return ok(m.app) ? m.app : null; +} + +function handoffUrl(app, moduleId) { + const q = new URLSearchParams({ module: String(moduleId), autoconnect: "1", transport: "usb", vid: "0x" + VID.toString(16).padStart(4, "0"), pid: "0x" + PID.toString(16).padStart(4, "0") }); + if (state.link?.serial) q.set("serial", state.link.serial); + return ESPP_APPS + app + "?" + q; +} + +// an espp app opens the device itself: let go of it first +async function handOff(app, moduleId) { + const tab = window.open("about:blank", "_blank"); + if (!tab) { toast("Allow pop-ups for this page to open the app", true); return; } + const url = handoffUrl(app, moduleId); + state.autoReconnect = false; // (the app has it now) + await disconnect(); + tab.location.href = url; + toast("The device was handed to " + app + "; connect again here when you are done."); +} + +async function updateFirmware() { + if (!(await confirmModal("Update the firmware?", "The emulator restarts into its updater (a running game is left without saving). The espp OTA console then opens in a new tab: pick build/.bin there.", "Restart into the updater"))) return; + const tab = window.open("about:blank", "_blank"); + if (!tab) { toast("Allow pop-ups for this page to open the OTA console", true); return; } + const url = handoffUrl("ota_console.html", MODULE.OTA); + // the updater comes up with the same serial: it is the OTA console's to open + state.autoReconnect = false; + try { await state.ctl.enterUpdater(); } catch (e) { state.autoReconnect = true; tab.close(); toast(e.message || String(e), true); return; } + await disconnect(); + tab.location.href = url; +} + +async function reboot(bootloader) { + const text = bootloader ? "The emulator restarts into the ROM download mode, for idf.py flash. It comes back after a flash or a reset." : "The emulator restarts (a running game is left without saving)."; + if (!(await confirmModal(bootloader ? "Restart into download mode?" : "Restart the emulator?", text, "Restart"))) return; + await guarded(() => state.ctl.reboot(bootloader)); +} + +// ---------------------------------------------------------------- console -- +const ANSI = /\x1b\[[0-9;]*m/g; +let logLines = []; +async function openSerial() { + if (!navigator.serial) { toast("This browser has no Web Serial", true); return; } + if (state.serial) { await closeSerial(); return; } + let port; + try { + port = await navigator.serial.requestPort({ filters: [{ usbVendorId: VID, usbProductId: PID }] }); + await port.open({ baudRate: 115200 }); + } catch (e) { + if (e.name !== "NotFoundError") toast(e.message || String(e), true); + return; + } + state.serial = { port, reader: null }; + $("serialBtn").textContent = "Close the console port"; + const decoder = new TextDecoder(); + let partial = ""; + try { + while (state.serial && port.readable) { + const reader = port.readable.getReader(); + state.serial.reader = reader; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + partial += decoder.decode(value, { stream: true }); + const lines = partial.split(/\r?\n/); + partial = lines.pop(); + if (lines.length) appendLog(lines); + } + } finally { + reader.releaseLock(); + } + } + } catch (e) { + if (state.serial) toast("Console: " + (e.message || e), true); + } + await closeSerial(); +} +async function closeSerial() { + const s = state.serial; + state.serial = null; + $("serialBtn").textContent = "Open the console port"; + if (!s) return; + try { await s.reader?.cancel(); } catch (_) {} + try { await s.port.close(); } catch (_) {} +} +function appendLog(lines) { + for (const raw of lines) logLines.push(raw.replace(ANSI, "")); + if (logLines.length > 5000) logLines = logLines.slice(-5000); + renderLog(lines.map((l) => l.replace(ANSI, ""))); +} +function logLine(text) { + const m = /^(?:\[[^\]]*\/)?([IWEDV])[\] (]/.exec(text) || /^\[[^/\]]*\/([IWEDV])\]/.exec(text); + return h("div", { class: m ? m[1] : null }, text); +} +function renderLog(fresh) { + const log = $("log"), f = $("logFilter").value.toLowerCase(); + if (fresh && !f) { + log.append(...fresh.map(logLine)); + while (log.childElementCount > 5000) log.firstElementChild.remove(); + } else { + log.replaceChildren(...logLines.filter((l) => !f || l.toLowerCase().includes(f)).slice(-2000).map(logLine)); + } + if ($("autoscroll").checked) log.scrollTop = log.scrollHeight; +} + +// ------------------------------------------------------------------- init -- +function init() { + if (!navigator.usb) { $("unsupported").hidden = false; $("connectBtn").disabled = true; $("welcomeConnectBtn").disabled = true; } + $("connectBtn").onclick = $("welcomeConnectBtn").onclick = () => connect(); + $("disconnectBtn").onclick = () => { state.autoReconnect = false; disconnect(); }; + // (as the System tab's Open app buttons: the core dump console needs the device) + $("coredumpLink").onclick = (e) => { e.preventDefault(); handOff("coredump_console.html", MODULE.COREDUMP); }; + for (const b of document.querySelectorAll("#tabs button")) b.onclick = () => showTab(b.dataset.tab); + for (const b of document.querySelectorAll("[data-goto]")) b.onclick = () => showTab(b.dataset.goto); + $("nowQuitBtn").onclick = $("quitBtn").onclick = () => guarded(() => state.ctl.quit(), "Quit"); + $("driveBtn").onclick = () => guarded(async () => { + const host = !state.status?.usb_drive; + await state.ctl.usbDrive(host); + pollStatus(); + }, state.status?.usb_drive ? "The emulator has the SD card again" : "The PC has the SD card"); + $("captureBtn").onclick = () => capture(); + $("liveToggle").onchange = (e) => { state.live = e.target.checked; if (state.live) liveLoop(); }; + $("savePngBtn").onclick = () => $("screen").toBlob((b) => { + if (b) download(`screenshot-${Date.now()}.png`, b, "image/png"); + else toast("The PNG could not be made", true); + }, "image/png"); + $("slot").replaceChildren(...[0, 1, 2, 3, 4, 5].map((s) => h("option", { value: s, selected: s === 1 }, "Slot " + s))); + $("saveBtn").onclick = () => guarded(() => state.ctl.save(Number($("slot").value)), "Saved to slot " + $("slot").value); + $("loadBtn").onclick = () => guarded(() => state.ctl.load(Number($("slot").value)), "Loaded slot " + $("slot").value); + initPad(); + $("libSearch").oninput = (e) => { state.search = e.target.value; renderLibrary(); }; + $("reloadRomsBtn").onclick = async () => { await guarded(() => state.ctl.reloadRoms()); loadLibrary(true); }; + $("addGameToggle").onclick = () => ($("addGame").hidden = !$("addGame").hidden); + $("addGame").onsubmit = addGame; + $("refreshFilesBtn").onclick = () => loadFiles(state.cwd); + $("mkdirBtn").onclick = async () => { + const name = $("newFolder").value.trim(); + if (!name || name.includes("/")) return; + if (await guarded(() => state.ctl.mkdir(state.cwd + "/" + name)) !== undefined) { $("newFolder").value = ""; loadFiles(state.cwd); } + }; + $("uploadInput").onchange = (e) => { uploadFiles([...e.target.files]); e.target.value = ""; }; + const drop = $("drop"); + drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); }); + drop.addEventListener("dragleave", () => drop.classList.remove("over")); + drop.addEventListener("drop", (e) => { e.preventDefault(); drop.classList.remove("over"); if (state.ctl) uploadFiles([...e.dataTransfer.files]); }); + $("infoBtn").onclick = () => loadSystem(); + $("updateBtn").onclick = () => updateFirmware(); + $("rebootBtn").onclick = () => reboot(false); + $("bootloaderBtn").onclick = () => reboot(true); + $("serialBtn").onclick = () => openSerial(); + $("logFilter").oninput = () => renderLog(); + $("clearLogBtn").onclick = () => { logLines = []; $("log").replaceChildren(); }; + $("saveLogBtn").onclick = () => download(`console-${Date.now()}.log`, logLines.join("\n"), "text/plain"); + addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("modal").hidden) $("modalCancel").click(); }); + autoConnect(); +} + +init(); +// (for the browser console: emuConsole.ctl.status() and so on) +window.emuConsole = state; diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..ef566a3 --- /dev/null +++ b/web/index.html @@ -0,0 +1,267 @@ + + + + + + Emulator Console + + + + + +
+
+ +
+
Emulator Console
+
esp-box-emu · tab5-emu over USB
+
+
+
+ Not connected + + +
+
+ + + +
+ + +
+

Plug in the emulator and connect

+

Connect over the USB-C port to see what the emulator is doing, browse and start games, watch and play + the screen, move files to and from the SD card, change the settings and inspect the system.

+

Nothing to install: the page talks to the device's link interface (WebUSB). Close + emulink first, only one program can use the link at a time.

+ +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + diff --git a/web/link.js b/web/link.js new file mode 100644 index 0000000..b8f70f8 --- /dev/null +++ b/web/link.js @@ -0,0 +1,478 @@ +// The emulator link in the browser: espp stream_frame frames over the +// device's vendor (WebUSB) interface, routed by module, the same protocol as +// tools/emulink (frame.py, link.py, control.py). Shared, byte for byte, by +// esp-box-emu and tab5-emu. + +export const VID = 0x1209; +export const PID = 0x0d32; +/** The USB serial numbers of the emulators, and what to call them. */ +export const DEVICES = { + "esp-box-emu": { name: "ESP-Box-Emu", site: "https://esp-cpp.github.io/esp-box-emu/" }, + "tab5-emu": { name: "Tab5 Emu", site: "https://esp-cpp.github.io/tab5-emu/" }, +}; + +export const MODULE = { OTA: 0x00, COREDUMP: 0x04, SYSTEM: 0x07, MONITOR: 0x08, CONTROL: 0x20, DISCOVERY: 0xff }; + +// emu.control request types (main/remote_control.hpp) +export const T = { + STATUS: 0x01, LIST_ROMS: 0x02, LAUNCH: 0x03, QUIT: 0x04, BUTTONS: 0x05, SAVE: 0x06, LOAD: 0x07, + SCREENSHOT: 0x08, USB_DRIVE: 0x09, RELOAD_ROMS: 0x0a, ENTER_UPDATER: 0x0b, SCREENSHOT_READ: 0x0c, + CONSOLE_FILTER: 0x0d, SETTINGS: 0x0e, + FILE_LIST: 0x10, FILE_READ: 0x11, FILE_WRITE: 0x12, FILE_DELETE: 0x13, MKDIR: 0x14, FILE_STAT: 0x15, + FILE_CLOSE: 0x16, +}; + +/** GamepadState::buttons bits. */ +export const BUTTONS = { + a: 1 << 0, b: 1 << 1, x: 1 << 2, y: 1 << 3, select: 1 << 4, start: 1 << 5, + up: 1 << 6, down: 1 << 7, left: 1 << 8, right: 1 << 9, l: 1 << 10, r: 1 << 11, l2: 1 << 12, r2: 1 << 13, +}; + +export const ROOT = "/sdcard"; + +// ---------------------------------------------------------------- framing -- +// [magic u16 = 0x4F54][flags u8][module u8][type u8]{[correlation u16]}[len u32][payload][crc32 u32] +const MAGIC0 = 0x54, MAGIC1 = 0x4f; +const VERSION = 1, FLAG_REPLY = 0x01, FLAG_CORRELATION = 0x02; +export const MAX_PAYLOAD = 4096; + +const CRC_TABLE = (() => { + const t = new Uint32Array(256); + for (let i = 0; i < 256; i++) { + let c = i; + for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xedb88320 : c >>> 1; + t[i] = c >>> 0; + } + return t; +})(); + +export function crc32(bytes, end = bytes.length) { + let c = 0xffffffff; + for (let i = 0; i < end; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8); + return ~c >>> 0; +} + +export function buildFrame(module, type, payload = new Uint8Array(0), correlation = null) { + if (payload.length > MAX_PAYLOAD) throw new Error(`payload too large (${payload.length} > ${MAX_PAYLOAD})`); + const hdr = 5 + (correlation !== null ? 2 : 0) + 4; + const out = new Uint8Array(hdr + payload.length + 4); + const v = new DataView(out.buffer); + out[0] = MAGIC0; out[1] = MAGIC1; + out[2] = (VERSION << 4) | (correlation !== null ? FLAG_CORRELATION : 0); + out[3] = module & 0xff; out[4] = type & 0xff; + if (correlation !== null) v.setUint16(5, correlation & 0xffff, true); + v.setUint32(hdr - 4, payload.length, true); + out.set(payload, hdr); + v.setUint32(hdr + payload.length, crc32(out, hdr + payload.length), true); + return out; +} + +/** Incremental, resynchronizing frame parser. */ +export class Parser { + constructor() { this.buf = new Uint8Array(0); } + reset() { this.buf = new Uint8Array(0); } + feed(data) { + const joined = new Uint8Array(this.buf.length + data.length); + joined.set(this.buf); joined.set(data, this.buf.length); + let b = joined, frames = []; + for (;;) { + let i = 0; + while (i + 1 < b.length && !(b[i] === MAGIC0 && b[i + 1] === MAGIC1)) i++; + if (i + 1 >= b.length) { this.buf = b.slice(b.length ? b.length - 1 : 0); return frames; } + b = b.subarray(i); + if (b.length < 5) break; + const flags = b[2]; + const hdr = 5 + (flags & FLAG_CORRELATION ? 2 : 0) + 4; + if (b.length < hdr) break; + const v = new DataView(b.buffer, b.byteOffset, b.length); + const corr = flags & FLAG_CORRELATION ? v.getUint16(5, true) : null; + const len = v.getUint32(hdr - 4, true); + if (len > MAX_PAYLOAD) { b = b.subarray(2); continue; } // not a frame: resync past this magic + const total = hdr + len + 4; + if (b.length < total) break; + if (crc32(b, hdr + len) !== v.getUint32(hdr + len, true)) { b = b.subarray(2); continue; } + frames.push({ flags, module: b[3], type: b[4], correlation: corr, payload: b.slice(hdr, hdr + len), + isReply: !!(flags & FLAG_REPLY) }); + b = b.subarray(total); + } + this.buf = b.slice(); + return frames; + } +} + +export class LinkError extends Error {} + +// -------------------------------------------------------------- transport -- +/** The vendor interface of one USB device. */ +export class UsbLink { + constructor(device) { + this.device = device; + this.iface = null; this.epIn = null; this.epOut = null; + this.parser = new Parser(); + this.waiters = new Map(); // correlation -> {module, resolve, reject, timer, types} + this.corr = 1; + this.reading = false; + this.onclose = null; + this.sendQueue = Promise.resolve(); // frames go out whole, in order + } + + get serial() { return this.device.serialNumber || ""; } + get product() { return this.device.productName || "USB device"; } + get known() { return DEVICES[this.serial] || { name: this.product, site: "" }; } + + /** Ask for a device (the browser's chooser: needs a click). */ + static async request() { + const device = await navigator.usb.requestDevice({ filters: [{ vendorId: VID, productId: PID }] }); + return new UsbLink(device); + } + + /** Devices this page may already open (no chooser), the emulators first. */ + static async permitted() { + if (!navigator.usb) return []; + const devs = await navigator.usb.getDevices(); + return devs.filter((d) => d.vendorId === VID).sort((a, b) => (DEVICES[b.serialNumber] ? 1 : 0) - (DEVICES[a.serialNumber] ? 1 : 0)); + } + + async open() { + const d = this.device; + await d.open(); + if (d.configuration === null) await d.selectConfiguration(1); + let found = null; + for (const itf of d.configuration.interfaces) { + for (const alt of itf.alternates) { + if (alt.interfaceClass !== 0xff) continue; + const inEp = alt.endpoints.find((e) => e.type === "bulk" && e.direction === "in"); + const outEp = alt.endpoints.find((e) => e.type === "bulk" && e.direction === "out"); + if (inEp && outEp) { found = { itf: itf.interfaceNumber, alt: alt.alternateSetting, inEp, outEp }; break; } + } + if (found) break; + } + if (!found) throw new LinkError("the device has no vendor interface"); + await d.claimInterface(found.itf); + if (found.alt !== 0) await d.selectAlternateInterface(found.itf, found.alt); + this.iface = found.itf; this.epIn = found.inEp.endpointNumber; this.epOut = found.outEp.endpointNumber; + this.readLoop(); + return this; + } + + async close() { + this.reading = false; + for (const w of this.waiters.values()) { clearTimeout(w.timer); w.reject(new LinkError("disconnected")); } + this.waiters.clear(); + try { if (this.iface !== null) await this.device.releaseInterface(this.iface); } catch (_) { /* gone */ } + try { await this.device.close(); } catch (_) { /* gone */ } + this.iface = null; + } + + async readLoop() { + this.reading = true; + while (this.reading) { + let r; + try { + r = await this.device.transferIn(this.epIn, 16384); + } catch (e) { + if (this.reading) { this.reading = false; this.failAll(e); if (this.onclose) this.onclose(e); } + return; + } + if (r.status === "stall") { try { await this.device.clearHalt("in", this.epIn); } catch (_) {} continue; } + if (!r.data || !r.data.byteLength) continue; + for (const f of this.parser.feed(new Uint8Array(r.data.buffer, r.data.byteOffset, r.data.byteLength))) { + if (!f.isReply) continue; + const w = f.correlation !== null ? this.waiters.get(f.correlation) : null; + if (w && w.module === f.module && (!w.types || w.types.includes(f.type))) { + this.waiters.delete(f.correlation); clearTimeout(w.timer); w.resolve(f); + } + } + } + } + + failAll(e) { + for (const w of this.waiters.values()) { clearTimeout(w.timer); w.reject(new LinkError(String(e.message || e))); } + this.waiters.clear(); + } + + async send(bytes) { + let sent = 0; + while (sent < bytes.length) { + const out = await this.device.transferOut(this.epOut, bytes.subarray(sent)); + if (out.status !== "ok") throw new LinkError("USB write: " + out.status); + if (!out.bytesWritten) throw new LinkError("USB write made no progress"); + sent += out.bytesWritten; + } + } + + /** A request and its reply (matched by module and correlation id). The + * device answers in order, so several can be in flight (see readChunks). */ + request(module, type, payload = new Uint8Array(0), { timeoutMs = 15000, types = null } = {}) { + const corr = this.corr = (this.corr % 0xffff) + 1; + const reply = new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.waiters.delete(corr); + reject(new LinkError(`no reply from module 0x${module.toString(16)} to request 0x${type.toString(16)}`)); + }, timeoutMs); + this.waiters.set(corr, { module, resolve, reject, timer, types }); + }); + const frame = buildFrame(module, type, payload, corr); + const sent = this.sendQueue.then(() => this.send(frame)); + this.sendQueue = sent.catch(() => { + const w = this.waiters.get(corr); + if (w) { clearTimeout(w.timer); this.waiters.delete(corr); } + }); + // (both observed at once: a timeout or a lost link while the frame is + // still queued rejects now, and never as an unhandled rejection) + return Promise.all([sent, reply]).then(([, f]) => f); + } + + /** The dispatcher's module list: {name, firmware, modules: [{id, name, protocol, version, ...}]}. */ + async discover() { + const f = await this.request(MODULE.DISCOVERY, 0x00, undefined, { timeoutMs: 3000 }); + return parseDiscovery(f.payload); + } +} + +export function parseDiscovery(p) { + let i = 0; + const need = (n) => { if (i + n > p.length) throw new Error("truncated discovery reply"); }; + const u8 = () => { need(1); return p[i++]; }; + const u16 = () => { need(2); const v = p[i] | (p[i + 1] << 8); i += 2; return v; }; + const str = () => { const n = u8(); need(n); const s = new TextDecoder().decode(p.subarray(i, i + n)); i += n; return s; }; + const version = u8(); u8(); // version, reserved + const out = { version, name: str(), firmware: str(), modules: [] }; + const n = u8(); + for (let k = 0; k < n; k++) { + const m = { id: u8(), name: str(), app: str(), description: str(), protocol: "", version: 0 }; + if (version >= 2) { m.protocol = str(); m.version = u16(); } + out.modules.push(m); + } + return out; +} + +// ---------------------------------------------------------- emu.control -- +const enc = new TextEncoder(), dec = new TextDecoder(); +const u32le = (v) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, v, true); return b; }; +const u16le = (v) => { const b = new Uint8Array(2); new DataView(b.buffer).setUint16(0, v, true); return b; }; +const cat = (...parts) => { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let o = 0; + for (const p of parts) { out.set(p, o); o += p.length; } + return out; +}; + +export class ControlError extends Error {} + +/** The emulator's control module (0x20) and the espp system service (7). */ +export class Control { + constructor(link) { + this.link = link; + this.ops = Promise.resolve(); // see exclusive() + this.mainOps = Promise.resolve(); // see onMain() + } + + /** Requests that need the device's main loop run one at a time: a screenshot + * holds the game (the main loop) until its last chunk is read, so a save, + * load, quit or launch sent meanwhile would stall the capture. */ + onMain(fn) { + const run = this.mainOps.then(() => fn()); + this.mainOps = run.catch(() => {}); + return run; + } + + // Operations made of several requests that share the device's state (a file + // written in parts, metadata.csv read, changed and written back) run one at + // a time: two at once would interleave their writes or lose an edit. + exclusive(fn) { + const run = this.ops.then(() => fn()); + this.ops = run.catch(() => {}); + return run; + } + + async call(type, payload = new Uint8Array(0), { timeoutMs = 15000, raw = false } = {}) { + if (typeof payload === "string") payload = enc.encode(payload); + const f = await this.link.request(MODULE.CONTROL, type, payload, { timeoutMs }); + if (!f.payload.length) throw new ControlError("empty reply"); + const body = f.payload.subarray(1); + if (f.payload[0] !== 0) { + let msg = dec.decode(body); + try { msg = JSON.parse(msg).error || msg; } catch (_) { /* plain text */ } + throw new ControlError(msg); + } + if (raw) return body; + return body.length ? JSON.parse(dec.decode(body)) : {}; + } + + remote(path) { + // (the device takes any path: keep this page's on the card) + if (path && path.split("/").includes("..")) throw new ControlError(`no '..' in a path: ${path}`); + if (!path || path === "/" || path === ".") return ROOT; + if (path.startsWith(ROOT)) return path; + return ROOT + "/" + path.replace(/^\/+/, ""); + } + + status() { return this.call(T.STATUS); } + + async roms() { + let out = [], offset = 0; + for (;;) { + const r = await this.call(T.LIST_ROMS, String(offset)); + out = out.concat(r.roms); + offset = r.next; + if (offset >= r.total || !r.roms.length) return out; + } + } + + launch(match) { return this.onMain(() => this.call(T.LAUNCH, match, { timeoutMs: 30000 })); } + quit() { return this.onMain(() => this.call(T.QUIT, undefined, { timeoutMs: 30000 })); } + buttons(mask, holdMs = 0) { return this.call(T.BUTTONS, cat(u16le(mask), u16le(holdMs)), { timeoutMs: holdMs + 5000 }); } + save(slot) { return this.onMain(() => this.call(T.SAVE, new Uint8Array([slot]), { timeoutMs: 60000 })); } + load(slot) { return this.onMain(() => this.call(T.LOAD, new Uint8Array([slot]), { timeoutMs: 60000 })); } + usbDrive(host) { return this.onMain(() => this.call(T.USB_DRIVE, new Uint8Array([host ? 1 : 0]), { timeoutMs: 20000 })); } + reloadRoms() { return this.onMain(() => this.call(T.RELOAD_ROMS)); } + enterUpdater() { return this.call(T.ENTER_UPDATER); } + consoleFilter(key) { return this.call(T.CONSOLE_FILTER, key || "all"); } + settings(change) { return this.call(T.SETTINGS, change || ""); } + + /** `size` bytes read in 4000-byte chunks, `depth` requests in flight + * (the device answers in order; a short chunk is an error: the size is known). */ + async readChunks(size, request, progress, depth = 4) { + const out = new Uint8Array(size); + const CH = 4000; + let next = 0, done = 0; + const one = async () => { + while (next < size) { + const off = next, n = Math.min(CH, size - off); + next += n; + const chunk = await request(off, n); + if (chunk.length !== n) throw new ControlError(`short read: ${off + chunk.length} of ${size} B`); + out.set(chunk, off); done += n; + if (progress) progress(done, size); + } + }; + await Promise.all(Array.from({ length: Math.min(depth, Math.ceil(size / CH)) }, one)); + return out; + } + + /** The running game's frame, or the launcher's screen: {width, height, format, source, data}. */ + frame(progress) { return this.onMain(() => this.frameNow(progress)); } + async frameNow(progress) { + const info = await this.call(T.SCREENSHOT, undefined, { timeoutMs: 15000 }); + // (the last chunk read lets the game go on: it must be the last one asked for) + const last = Math.max(0, info.size - 4000 > 0 ? info.size - ((info.size % 4000) || 4000) : 0); + const head = await this.readChunks(last, (off, n) => this.call(T.SCREENSHOT_READ, cat(u32le(off), u16le(n)), { raw: true }), progress); + const tail = await this.call(T.SCREENSHOT_READ, cat(u32le(last), u16le(info.size - last)), { raw: true }); + if (tail.length !== info.size - last) throw new ControlError(`short read at the end of the frame`); + const data = new Uint8Array(info.size); + data.set(head); data.set(tail, last); + if (progress) progress(info.size, info.size); + return { ...info, data }; + } + + // files on the SD card + async ls(path) { + const p = this.remote(path); + let r = await this.call(T.FILE_LIST, p); + let out = r.entries; + while (r.truncated && r.next != null && r.entries.length) { + r = await this.call(T.FILE_LIST, p + "\0" + r.next); + out = out.concat(r.entries); + } + return out; + } + async stat(path) { + try { return await this.call(T.FILE_STAT, this.remote(path)); } catch (e) { + if (String(e.message).includes("does not exist")) return null; + throw e; + } + } + mkdir(path) { return this.call(T.MKDIR, this.remote(path)); } + rm(path) { return this.exclusive(() => this.call(T.FILE_DELETE, this.remote(path), { timeoutMs: 120000 })); } + + // (queued too: a read alongside a write of the same file could see part of it) + readFile(path, progress) { return this.exclusive(() => this.readFileNow(path, progress)); } + async readFileNow(path, progress) { + const p = enc.encode(this.remote(path)); + const st = await this.call(T.FILE_STAT, p); + return this.readChunks(st.size, (off, n) => this.call(T.FILE_READ, cat(u32le(off), u16le(n), p), { raw: true }), progress); + } + + writeFile(path, data, progress) { return this.exclusive(() => this.writeFileNow(path, data, progress)); } + async writeFileNow(path, data, progress) { + const p = enc.encode(this.remote(path)); + // path + data at most 3584 bytes a frame, as emulink: under the 4096-byte + // payload (MAX_PAYLOAD) with room to spare + const chunk = 3584 - p.length; + if (chunk < 256) throw new ControlError("path too long"); + let off = 0; + do { + const part = data.subarray(off, off + chunk); + await this.call(T.FILE_WRITE, cat(u32le(off), u16le(p.length), p, part), { timeoutMs: 30000 }); + off += part.length; + if (progress) progress(off, data.length); + } while (off < data.length); + await this.call(T.FILE_CLOSE); + } + + /** Add (or remove) a metadata.csv line; returns the number of games after the reload. */ + addRom(romPath, name, boxart = "", remove = false) { + return this.exclusive(() => this.addRomNow(romPath, name, boxart, remove)); + } + async addRomNow(romPath, name, boxart, remove) { + const rel = romPath.startsWith(ROOT + "/") ? romPath.slice(ROOT.length + 1) : romPath; + for (const [field, value] of [["ROM path", rel], ["boxart path", boxart], ["name", name]]) { + if (/[\r\n]/.test(value) || (field !== "name" && value.includes(","))) + throw new ControlError(`the ${field} cannot hold ${value.includes(",") ? "a comma" : "a line break"}`); + } + const meta = "metadata.csv"; + // only a missing file starts an empty list: a failed read must not rewrite it + const text = (await this.stat(meta)) ? dec.decode(await this.readFileNow(meta)) : ""; + const lines = text.split(/\r?\n/).filter((l) => l.trim() && l.split(",")[0].trim() !== rel); + if (!remove) lines.push(`${rel}, ${boxart}, ${name}`); + await this.writeFileNow(meta, enc.encode(lines.join("\n") + "\n")); + return (await this.reloadRoms()).total; + } + + // the espp system service + async info() { + const f = await this.link.request(MODULE.SYSTEM, 0x01, undefined, { timeoutMs: 5000, types: [0x81, 0x84] }); + if (f.type !== 0x81) throw new ControlError("GET_INFO failed"); + const p = f.payload, out = {}; + const strs = { 1: "chip", 5: "idf", 6: "project", 7: "firmware", 8: "build_date", 9: "build_time", + 11: "running_partition", 12: "boot_partition" }; + const le = (v) => v.reduceRight((n, b) => n * 256 + b, 0); + for (let i = 0; i + 2 <= p.length;) { + const tag = p[i], n = p[i + 1], v = p.subarray(i + 2, i + 2 + n); + i += 2 + n; + if (strs[tag]) out[strs[tag]] = dec.decode(v); + else if (tag === 2) out.chip_revision = le(v); + else if (tag === 3) out.cores = v[0]; + else if (tag === 10) out.elf_sha256 = [...v].map((b) => b.toString(16).padStart(2, "0")).join(""); + else if (tag === 13) out.ota_state = { 0: "new", 1: "pending verify", 2: "valid", 3: "invalid", 4: "aborted", 0xfe: "undefined", 0xff: "n/a" }[v[0]] ?? v[0]; + else if (tag === 14) out.reset_reason = RESET_REASONS[v[0]] ?? v[0]; + else if (tag === 15) out.uptime_ms = le(v); + else if (tag === 16) out.mac = [...v].map((b) => b.toString(16).padStart(2, "0")).join(":"); + else if (tag >= 17 && tag <= 21) out[{ 17: "flash_size", 18: "psram_size", 19: "cpu_mhz", 20: "free_heap", 21: "min_free_heap" }[tag]] = le(v); + } + return out; + } + + reboot(bootloader = false, delayMs = 250) { + return this.link.request(MODULE.SYSTEM, bootloader ? 0x03 : 0x02, u16le(delayMs), { timeoutMs: 5000, types: [0x83, 0x84] }); + } +} + +export const RESET_REASONS = { + 0: "unknown", 1: "power-on", 2: "external", 3: "software", 4: "panic", 5: "interrupt WDT", 6: "task WDT", + 7: "other WDT", 8: "deep sleep", 9: "brownout", 10: "SDIO", 11: "USB", 12: "JTAG", 13: "eFuse", + 14: "power glitch", 15: "CPU lockup", +}; + +/** RGB565 pixels (rows packed) into an ImageData. */ +export function rgb565ToImageData(data, width, height, bigEndian = false) { + const img = new ImageData(width, height); + const px = img.data; + for (let i = 0, j = 0; i + 1 < data.length && j < px.length; i += 2, j += 4) { + const v = bigEndian ? (data[i] << 8) | data[i + 1] : data[i] | (data[i + 1] << 8); + const r = (v >> 11) & 0x1f, g = (v >> 5) & 0x3f, b = v & 0x1f; + px[j] = (r << 3) | (r >> 2); px[j + 1] = (g << 2) | (g >> 4); px[j + 2] = (b << 3) | (b >> 2); px[j + 3] = 255; + } + return img; +}