diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index c30cfd9..aaa3969 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -1,13 +1,13 @@ 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. +# The Emulator Console (web/, from the emulink submodule): 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/**' + - 'components/emulink' - '.github/workflows/pages.yml' workflow_dispatch: @@ -28,11 +28,13 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} steps: - uses: actions/checkout@v4 + - name: The emulink submodule (only it) + run: git submodule update --init components/emulink - name: Check the scripts parse (as ES modules) - run: for f in web/*.js; do node --input-type=module --check < "$f" || exit 1; done + run: for f in components/emulink/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 + path: components/emulink/web - id: deployment uses: actions/deploy-pages@v4 diff --git a/.gitmodules b/.gitmodules index 27fa31b..fc8b601 100644 --- a/.gitmodules +++ b/.gitmodules @@ -49,3 +49,7 @@ path = components/scummvm/scummvm url = https://github.com/esp-cpp/scummvm.git branch = esp32p4 +[submodule "components/emulink"] + path = components/emulink + url = https://github.com/esp-cpp/emulink.git + branch = main diff --git a/CMakeLists.txt b/CMakeLists.txt index 653aa19..27efb1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -110,12 +110,15 @@ set(GAME_COMPONENTS set( COMPONENTS main esptool_py esp_lcd esp_psram task format display display_drivers monitor timer - ${GAME_COMPONENTS} tab5-emu pool_allocator gui menu rom_info statistics settings devlink + ${GAME_COMPONENTS} tab5-emu pool_allocator gui menu rom_info statistics settings emulink CACHE STRING "List of components to include" FORCE ) +# the USB link (components/emulink) builds against this board +idf_build_set_property(EMULINK_BOARD_COMPONENT tab5-emu) + project(tab5-emu) set(CMAKE_CXX_STANDARD 23) diff --git a/components/devlink/CMakeLists.txt b/components/devlink/CMakeLists.txt deleted file mode 100644 index 387def3..0000000 --- a/components/devlink/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -idf_component_register( - INCLUDE_DIRS "include" - SRC_DIRS "src" - PRIV_REQUIRES esp_system - REQUIRES app_update coredump dispatcher monitor system tab5-emu) -# the two-slot OTA service: off on the Tab5, whose app does not fit twice (an -# update goes through the updater app in ota_1, see updater/) -target_compile_definitions(${COMPONENT_LIB} PUBLIC DEVLINK_HAS_OTA=0) -# keep the last panic's reason across the reset (DevLink::last_panic()) -target_link_options(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=esp_panic_handler" "-Wl,--wrap=panic_abort") diff --git a/components/devlink/idf_component.yml b/components/devlink/idf_component.yml deleted file mode 100644 index 11aa1f5..0000000 --- a/components/devlink/idf_component.yml +++ /dev/null @@ -1,7 +0,0 @@ -## IDF Component Manager Manifest File -dependencies: - idf: '>=6.0' - espp/coredump: '>=1.4.2' - espp/dispatcher: '>=1.4.2' - espp/monitor: '>=1.4.2' - espp/system: '>=1.4.2' diff --git a/components/devlink/include/devlink.hpp b/components/devlink/include/devlink.hpp deleted file mode 100644 index 064542c..0000000 --- a/components/devlink/include/devlink.hpp +++ /dev/null @@ -1,112 +0,0 @@ -#pragma once - -#include -#include - -#include "coredump.hpp" -#include "coredump_service.hpp" -#include "dispatcher_worker.hpp" -#include "monitor_service.hpp" -#include "system_service.hpp" - -#include -#include - -#include "box-emu.hpp" - -/// Check the heap around every flash-touching request (debugging aid). -#ifndef DEVLINK_HEAP_CHECK -#define DEVLINK_HEAP_CHECK 0 -#endif -#if DEVLINK_HAS_OTA -#include "ota.hpp" -#include "ota_service.hpp" -#endif - -/// A module whose requests touch the flash (erase / write / read), run under -/// the launcher's LVGL lock. While the flash is busy the cache is off and only -/// interrupt handlers placed in internal RAM run; the display's SPI "transfer -/// done" interrupt is one and calls into LVGL (flash / PSRAM): a screen update -/// finishing during an OTA erase panics (esp-box-emu). LVGL waits for its -/// transfers before it lets go of the lock, so none is in flight meanwhile. -template class FlashGuarded { -public: - explicit FlashGuarded(Module &module) : module_(module) {} - uint8_t module_id() const { return module_.module_id(); } - espp::DispatcherModuleInfo module_info() const { return module_.module_info(); } - void handle(const espp::stream_frame::Frame &frame) { - std::lock_guard lk(BoxEmu::lvgl_mutex()); -#if DEVLINK_HEAP_CHECK - if (!heap_caps_check_integrity_all(true)) abort_corrupt("before", frame); -#endif - module_.handle(frame); -#if DEVLINK_HEAP_CHECK - if (!heap_caps_check_integrity_all(true)) abort_corrupt("after", frame); -#endif - } - -protected: -#if DEVLINK_HEAP_CHECK - [[noreturn]] static void abort_corrupt(const char *when, const espp::stream_frame::Frame &frame) { - static char msg[80]; - const bool internal_ok = heap_caps_check_integrity(MALLOC_CAP_INTERNAL, false); - const bool psram_ok = heap_caps_check_integrity(MALLOC_CAP_SPIRAM, false); - snprintf(msg, sizeof(msg), "heap corrupt %s request: internal %s, psram %s (frame @%p)", when, - internal_ok ? "ok" : "BAD", psram_ok ? "ok" : "BAD", (const void *)&frame); - esp_system_abort(msg); - } -#endif - Module &module_; -}; - -/// The framed services on the composite USB device's vendor interface, one -/// espp::DispatcherWorker routing them (shared by esp-box-emu and tab5-emu): -/// -/// | module | service | host tool | -/// |--------|-------------------------------------------|--------------------------| -/// | 0 | OTA (DEVLINK_HAS_OTA: a two-slot layout) | espp_ota, emulink ota | -/// | 4 | core dump of the last crash | espp_coredump, emulink | -/// | 7 | system info, reboot, ROM download mode | emulink reboot | -/// | 8 | heap / task monitor | the espp Device Hub | -/// | 0x20 | test control (registered by the app) | emulink | -/// -/// The device answers discovery, so the hosted espp web consoles find them. -class DevLink { -public: - struct Config { - std::string device_name; ///< advertised through discovery - std::string firmware; ///< firmware version, advertised through discovery - }; - - explicit DevLink(const Config &config); - ~DevLink(); - - /// Register an application module (e.g. the test control service). - template void register_module(Module &module) { - worker_->register_module(module); - } - - /// Send one frame to the host (serialized; all or nothing). - static void send(std::span frame); - - /// The running image booted after an update and has not been confirmed - /// yet: confirm it (call once the app is up). No-op otherwise. - static void mark_app_valid(); - - /// After a panic reset: what it was ("reason (detail) at PC on core N"), - /// kept in RTC memory (no core dump needed); "" otherwise. - static std::string last_panic(); - -protected: - std::unique_ptr worker_; - espp::CoreDump core_dump_; - std::unique_ptr core_dump_service_; - std::unique_ptr> core_dump_guarded_; - std::unique_ptr system_service_; - std::unique_ptr monitor_service_; -#if DEVLINK_HAS_OTA - std::unique_ptr ota_; - std::unique_ptr ota_service_; - std::unique_ptr> ota_guarded_; -#endif -}; diff --git a/components/devlink/src/devlink.cpp b/components/devlink/src/devlink.cpp deleted file mode 100644 index 43cdc50..0000000 --- a/components/devlink/src/devlink.cpp +++ /dev/null @@ -1,165 +0,0 @@ -#include "devlink.hpp" - -#include -#include -#include - -#include -#include -#include -#if CONFIG_IDF_TARGET_ARCH_XTENSA -#include -#endif -#include -#include -#include -#include - -#include "box-emu.hpp" - -void DevLink::send(std::span frame) { BoxEmu::get().vendor_write(frame); } - -DevLink::DevLink(const Config &config) { - auto &emu = BoxEmu::get(); - worker_ = std::make_unique(espp::DispatcherWorker::Config{ - .send = &DevLink::send, - .on_overflow = - [this]() { -#if DEVLINK_HAS_OTA - if (ota_service_) ota_service_->on_rx_overflow(); -#endif - }, - // ~3.5 KB used at the high-water mark (file transfers, core dump reads); - // internal RAM, since the core dump service reads the flash - .task_config = {.name = "devlink", .stack_size_bytes = 6144}, - }); - core_dump_service_ = std::make_unique(core_dump_, espp::CoreDumpService::Config{ - .send = &DevLink::send, - }); - system_service_ = std::make_unique(espp::SystemService::Config{ - .send = &DevLink::send, - .on_reboot_request = - [](espp::SystemService::RebootKind kind) { - if (kind == espp::SystemService::RebootKind::Bootloader) { - BoxEmu::get().usb_prepare_for_rom_download(); - } - return true; - }, - }); - monitor_service_ = std::make_unique(espp::MonitorService::Config{ - .send = &DevLink::send, - }); - core_dump_guarded_ = std::make_unique>(*core_dump_service_); - worker_->register_module(*core_dump_guarded_); - worker_->register_module(*system_service_); - worker_->register_module(*monitor_service_); -#if DEVLINK_HAS_OTA - ota_ = std::make_unique(espp::Ota::Config{}); - ota_service_ = std::make_unique(*ota_, espp::OtaService::Config{ - .send = &DevLink::send, - }); - ota_guarded_ = std::make_unique>(*ota_service_); - worker_->register_module(*ota_guarded_); -#endif - worker_->serve_discovery(config.device_name, config.firmware); - emu.set_vendor_rx([this](std::span data) { worker_->push(data); }); -} - -DevLink::~DevLink() { BoxEmu::get().set_vendor_rx(nullptr); } - -void DevLink::mark_app_valid() { - esp_ota_img_states_t state; - const esp_partition_t *running = esp_ota_get_running_partition(); - if (running && esp_ota_get_state_partition(running, &state) == ESP_OK && state == ESP_OTA_IMG_PENDING_VERIFY) { - esp_ota_mark_app_valid_cancel_rollback(); - fmt::print("devlink: the updated firmware is up; marked valid\n"); - } -} - -// The last panic, kept across the reset in RTC memory: a crash in the middle of -// a flash operation (an OTA erase) cannot write its core dump, and the console -// is the USB CDC port, which dies with the chip. The wrappers run in the panic -// path (possibly with the cache off): IRAM, and only plain byte copies. -namespace { -struct LastPanic { - uint32_t magic; - uint32_t addr; - int32_t core; - int32_t exception; - char reason[64]; - char detail[96]; - char task[16]; - uint32_t backtrace[20]; // Xtensa: the abort()'s caller chain -}; -constexpr uint32_t kPanicMagic = 0x50414e43; // "PANC" -RTC_NOINIT_ATTR LastPanic s_last_panic; -DRAM_ATTR volatile bool s_aborting = false; -IRAM_ATTR void copy_str(char *dst, size_t n, const char *src) { - size_t i = 0; - if (src) { - for (; i + 1 < n && src[i]; ++i) dst[i] = src[i]; - } - dst[i] = 0; -} -} // namespace - -extern "C" void __real_esp_panic_handler(panic_info_t *info); -extern "C" IRAM_ATTR void __wrap_esp_panic_handler(panic_info_t *info) { - // an abort() gets here too (panic_abort() traps): keep its message - if (s_aborting) { - __real_esp_panic_handler(info); - return; - } - s_last_panic.magic = kPanicMagic; - s_last_panic.addr = (uint32_t)info->addr; - s_last_panic.core = info->core; - s_last_panic.exception = (int32_t)info->exception; - copy_str(s_last_panic.reason, sizeof(s_last_panic.reason), info->reason); - copy_str(s_last_panic.detail, sizeof(s_last_panic.detail), info->description); - TaskHandle_t t = xTaskGetCurrentTaskHandle(); - copy_str(s_last_panic.task, sizeof(s_last_panic.task), t ? pcTaskGetName(t) : "?"); - std::fill(std::begin(s_last_panic.backtrace), std::end(s_last_panic.backtrace), 0); - __real_esp_panic_handler(info); -} - -extern "C" void __real_panic_abort(const char *details); -IRAM_ATTR void note_task_and_backtrace() { - TaskHandle_t t = xTaskGetCurrentTaskHandle(); - copy_str(s_last_panic.task, sizeof(s_last_panic.task), t ? pcTaskGetName(t) : "?"); - std::fill(std::begin(s_last_panic.backtrace), std::end(s_last_panic.backtrace), 0); -#if CONFIG_IDF_TARGET_ARCH_XTENSA - esp_backtrace_frame_t frame{}; - esp_backtrace_get_start(&frame.pc, &frame.sp, &frame.next_pc); - for (int i = 0; i < 20; ++i) { - s_last_panic.backtrace[i] = esp_cpu_process_stack_pc(frame.pc); - if (!esp_backtrace_get_next_frame(&frame)) break; - } -#endif -} - -extern "C" IRAM_ATTR void __wrap_panic_abort(const char *details) { - s_aborting = true; - note_task_and_backtrace(); - s_last_panic.magic = kPanicMagic; - s_last_panic.addr = 0; - s_last_panic.core = -1; - s_last_panic.exception = -1; - copy_str(s_last_panic.reason, sizeof(s_last_panic.reason), "abort"); - copy_str(s_last_panic.detail, sizeof(s_last_panic.detail), details); - __real_panic_abort(details); -} - -std::string DevLink::last_panic() { - if (esp_reset_reason() != ESP_RST_PANIC || s_last_panic.magic != kPanicMagic) { - return ""; - } - s_last_panic.reason[sizeof(s_last_panic.reason) - 1] = 0; - s_last_panic.detail[sizeof(s_last_panic.detail) - 1] = 0; - s_last_panic.task[sizeof(s_last_panic.task) - 1] = 0; - std::string bt; - for (auto pc : s_last_panic.backtrace) { - if (pc) bt += fmt::format(" {:#010x}", pc); - } - return fmt::format("{} ({}) at {:#010x} on core {} in task '{}'{}{}", s_last_panic.reason, s_last_panic.detail, - s_last_panic.addr, s_last_panic.core, s_last_panic.task, bt.empty() ? "" : "; backtrace", bt); -} diff --git a/components/emulink b/components/emulink new file mode 160000 index 0000000..3433770 --- /dev/null +++ b/components/emulink @@ -0,0 +1 @@ +Subproject commit 3433770dfac07836090b95181b426bcdeb5001b1 diff --git a/main/remote_control.hpp b/main/remote_control.hpp deleted file mode 100644 index 7dc17c8..0000000 --- a/main/remote_control.hpp +++ /dev/null @@ -1,952 +0,0 @@ -#pragma once - -// Test control over the USB link (dispatcher module 0x20, protocol -// "emu.control"): what a test script needs to drive the emulator -- list and -// launch games, quit, hold buttons, save / load states, take screenshots, move -// files to and from the SD card (with the device running), hand the card to -// the PC as a USB drive and reboot into the updater. tools/emulink is the -// host side. -// -// Every request is answered with a reply frame of the same type whose -// payload is one status byte (0 = ok, 1 = error) and then the body: JSON text -// (an error's message as {"error": ...}), or the raw bytes for FILE_READ and -// SCREENSHOT_READ. -// Requests that touch the launcher or the running game are handed to the main -// loop (MainQueue) and answered once it ran them. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "bootloader_common.h" -#include "esp_flash_partitions.h" -#if CONFIG_IDF_TARGET_ESP32S3 -#include "soc/rtc_cntl_reg.h" -#endif - -#include "dispatcher.hpp" -#include "format.hpp" -#include "stream_frame.hpp" - -#include "cart.hpp" -#include "devlink.hpp" -#include "gui.hpp" -#include "settings.hpp" - -/// Work for the main loop (the task that owns the launcher and the running -/// cart), posted from other tasks; run() waits for it to be done. -class MainQueue { -public: - /// Run `fn` on the main loop and wait for it. If the main loop does not - /// get to it within `timeout` it is dropped (never run later) and run() - /// returns false; once started it is always waited for. - bool run(std::function fn, std::chrono::milliseconds timeout) { - auto item = std::make_shared(); - item->fn = std::move(fn); - std::unique_lock lk(mutex_); - queue_.push_back(item); - if (!cv_.wait_for(lk, timeout, [&] { return item->state != Item::QUEUED; })) { - item->state = Item::CANCELLED; - return false; - } - cv_.wait(lk, [&] { return item->state == Item::DONE; }); - return true; - } - /// Run `fn` on the main loop without waiting for it. - void post(std::function fn) { - auto item = std::make_shared(); - item->fn = std::move(fn); - std::lock_guard lk(mutex_); - queue_.push_back(item); - } - /// Called by the main loop: run what was posted. - void poll() { - std::unique_lock lk(mutex_); - while (!queue_.empty()) { - auto item = queue_.front(); - queue_.pop_front(); - if (item->state == Item::CANCELLED) continue; - item->state = Item::RUNNING; - cv_.notify_all(); - lk.unlock(); - item->fn(); - lk.lock(); - item->state = Item::DONE; - cv_.notify_all(); - } - } - -protected: - struct Item { - enum State { QUEUED, RUNNING, DONE, CANCELLED } state{QUEUED}; - std::function fn; - }; - std::mutex mutex_; - std::condition_variable cv_; - std::deque> queue_; -}; - -class RemoteControl { -public: - static constexpr uint8_t kModule = 0x20; - static constexpr const char *kProtocol = "emu.control"; - // 2: in-memory screenshots, 3: console filter, launcher screenshots, 4: settings, boxart / console keys in the list, - // 5: touch - static constexpr uint16_t kProtocolVersion = 5; - /// TOUCH: the fingers byte's flag for coordinates in the game's frame - static constexpr uint8_t kTouchInFrame = 0x80; - - enum class Type : uint8_t { - STATUS = 0x01, ///< () -> {state, rom, platform, console, heap, uptime, ...} - 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) - SAVE = 0x06, ///< (u8 slot) - LOAD = 0x07, ///< (u8 slot) - /// (path: text, optional). With a path: saved there on the card as - /// [u16be w][u16be h][RGB565] -> {path}. Without: -> {width, height, size, - /// format: rgb565le, source: game | launcher}, and the game holds still - /// (its frame buffer with it) while SCREENSHOT_READ reads the pixels, - /// until the last of them is read; with no game running, the launcher's - /// screen is drawn into a copy instead. - SCREENSHOT = 0x08, - USB_DRIVE = 0x09, ///< (u8 1 = the PC gets the SD card, 0 = the device takes it back) - RELOAD_ROMS = 0x0A, ///< () re-read metadata.csv - ENTER_UPDATER = 0x0B, ///< () reboot into the updater app (ota_1) for an update - SCREENSHOT_READ = 0x0C, ///< (u32 offset, u16 length) -> raw bytes of the held SCREENSHOT (short at the end) - /// (console key: text, e.g. "snes"; "all" for every console) -> {filter, - /// 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, - /// (u8 fingers, u16 x, u16 y, u16 hold ms): a finger on the screen at - /// (x, y) in its logical (landscape) pixels, held for hold ms and lifted - /// (the answer comes after), or with hold 0 until the next TOUCH (a drag - /// is a run of those); fingers = 0 lifts it. Like a finger on the touch - /// screen everywhere: the launcher's menus, the touch gamepad, the games. - /// With kTouchInFrame set in fingers, (x, y) are in the screenshot's - /// pixels (the running game's frame) instead. - TOUCH = 0x0F, - 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 - FILE_DELETE = 0x13, ///< (path: text) - MKDIR = 0x14, ///< (path: text) (with parents) - FILE_STAT = 0x15, ///< (path: text) -> {size, dir} - FILE_CLOSE = 0x16, ///< () flush and close the file being written - }; - - /// Where the main loop is, for STATUS. - enum class State { MENU, GAME }; - - RemoteControl(Gui &gui, MainQueue &main_queue) - : gui_(gui) - , main_(main_queue) { - // the launcher's drive switch can hand the card over between two FILE_WRITEs - BoxEmu::get().set_before_sd_handover([this] { close_file(); }); - } - ~RemoteControl() { BoxEmu::get().set_before_sd_handover(nullptr); } - - uint8_t module_id() const { return kModule; } - espp::DispatcherModuleInfo module_info() const { - return {.name = "Emulator control", - .app = "", - .description = "Launch games, input, save states, screenshots, SD card files", - .protocol = kProtocol, - .protocol_version = kProtocolVersion}; - } - - /// The main loop tells us what is running (nullptr: the launcher). - void set_cart(Cart *cart) { - std::lock_guard lk(state_mutex_); - cart_ = cart; - // what the game reads while it runs (see in_use_by_game()) - game_rom_ = cart ? normal_path(cart->rom_info().rom_path) : std::string(); - game_folder_ = cart && cart->uses_rom_folder() - ? normal_path(std::filesystem::path(cart->rom_info().rom_path).parent_path().string()) - : std::string(); - } - - void handle(const espp::stream_frame::Frame &frame) { - if (frame.is_reply() || frame.module != kModule) { - return; - } - std::vector body; - bool ok = true; - const std::string_view text(reinterpret_cast(frame.payload.data()), frame.payload.size()); - // the first error is the one reported - auto fail = [&](std::string_view message) { - if (!ok) return; - ok = false; - const auto j = fmt::format("{{\"error\":{}}}", quote(message)); - body.assign(j.begin(), j.end()); - }; - auto json = [&](const std::string &j) { - if (ok) body.assign(j.begin(), j.end()); - }; - // the main loop does not take work while it waits in the pause menu - auto on_main = [&](std::function fn, std::chrono::milliseconds timeout) { - if (main_.run(std::move(fn), timeout)) return true; - fail("the device is busy (is the pause menu open?)"); - return false; - }; - const auto &p = frame.payload; - // Held for the card's file requests: the card is handed over (by USB_DRIVE - // or the launcher's drive switch) under this lock, so it is not unmounted - // during one, and while the PC has it they are refused. - std::unique_lock card_lock(BoxEmu::lvgl_mutex(), std::defer_lock); - switch (static_cast(frame.type)) { - case Type::FILE_LIST: - case Type::FILE_READ: - case Type::FILE_WRITE: - case Type::FILE_DELETE: - case Type::MKDIR: - case Type::FILE_STAT: - case Type::FILE_CLOSE: - card_lock.lock(); - if (BoxEmu::get().usb_msc_host_has_card()) { - fail("the PC has the SD card (emulink drive off)"); - reply(frame, ok, body); - return; - } - break; - default: - break; - } - switch (static_cast(frame.type)) { - case Type::STATUS: - json(status()); - break; - case Type::LIST_ROMS: { - const auto roms = gui_.rom_infos(); - size_t offset = 0; - if (!text.empty()) offset = std::strtoul(std::string(text).c_str(), nullptr, 10); - std::string j = fmt::format("{{\"total\":{},\"offset\":{},\"roms\":[", roms.size(), offset); - size_t i = offset; - for (; i < roms.size(); i++) { - const auto &r = roms[i]; - 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; - } - j += fmt::format("],\"next\":{}}}", i); - json(j); - break; - } - case Type::LAUNCH: { - if (current_cart()) { - fail("a game is running; QUIT first"); - break; - } - const std::string match(text); - bool found = false, drive = false; - on_main([&] { - // (the PC has the card: the ROM is not there to load) - if ((drive = BoxEmu::get().usb_msc_host_has_card())) return; - found = select(match) && (gui_.ready_to_play(true), true); - }, std::chrono::seconds(2)); - if (drive) fail("the PC has the SD card (emulink drive off)"); - else if (!found) fail(fmt::format("no game matches '{}'", match)); - else json(fmt::format("{{\"rom\":{}}}", quote(gui_.get_selected_rom()->rom_path))); - break; - } - case Type::QUIT: { - bool quit = false; - on_main([&] { - if (auto *cart = current_cart()) { - cart->request_quit(); - quit = true; - } - }, std::chrono::seconds(5)); - if (!quit) fail("no game is running"); - break; - } - case Type::BUTTONS: { - if (p.size() < 4) { - fail("payload: u16 buttons, u16 hold_ms"); - break; - } - const uint16_t buttons = p[0] | (p[1] << 8); - const uint16_t hold_ms = p[2] | (p[3] << 8); - BoxEmu::get().set_remote_buttons(buttons); - if (hold_ms) { - // held for hold_ms, then released (this task answers afterwards) - std::this_thread::sleep_for(std::chrono::milliseconds(hold_ms)); - BoxEmu::get().set_remote_buttons(0); - } - break; - } - case Type::TOUCH: { - if (p.size() < 7) { - fail("payload: u8 fingers, u16 x, u16 y, u16 hold_ms"); - break; - } - uint8_t fingers = p[0]; - int x = p[1] | (p[2] << 8); - int y = p[3] | (p[4] << 8); - const uint16_t hold_ms = p[5] | (p[6] << 8); - if (fingers & kTouchInFrame) { - // (x, y) in the screenshot's pixels: the running game's frame - fingers &= ~kTouchInFrame; - size_t fw = 0, fh = 0; - main_.run([&] { - if (const auto *cart = current_cart()) std::tie(fw, fh) = cart->frame_size(); - }, std::chrono::seconds(2)); - if (fw && fh) std::tie(x, y) = BoxEmu::get().frame_to_screen(x, y, fw, fh); - } - BoxEmu::get().set_remote_touch(fingers, x, y); - if (fingers && hold_ms) { - std::this_thread::sleep_for(std::chrono::milliseconds(hold_ms)); - BoxEmu::get().set_remote_touch(0, x, y); - } - break; - } - case Type::SAVE: - case Type::LOAD: { - if (p.empty()) { - fail("payload: u8 slot"); - break; - } - const int slot = p[0]; - // (the menu wraps an out-of-range slot round to 0) - if (slot > (int)Menu::MAX_SLOT) { - fail(fmt::format("slot {} out of range (0-{})", slot, Menu::MAX_SLOT)); - break; - } - const bool save = static_cast(frame.type) == Type::SAVE; - bool done = false, has_cart = false; - on_main([&] { - if (auto *cart = current_cart()) { - has_cart = true; - done = save ? cart->save_from_host(slot) : cart->load_from_host(slot); - } - }, std::chrono::seconds(30)); - if (!has_cart) fail("no game is running"); - else if (!done) fail(save ? fmt::format("saving to slot {} failed", slot) - : fmt::format("slot {} has no state, or the game could not load it", slot)); - break; - } - case Type::SCREENSHOT: { - std::string path(text); - if (!path.empty()) { - bool done = false, has_cart = false; - // the old way: a file on the card - on_main([&] { - if (auto *cart = current_cart()) { - has_cart = true; - std::error_code ec; - std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); - // (cores on their own tasks keep drawing: hold them, as below) - cart->capture_hold(true); - done = cart->screenshot(path); - cart->capture_hold(false); - } - }, std::chrono::seconds(10)); - if (!has_cart) fail("no game is running"); - else if (!done) fail("screenshot failed"); - else json(fmt::format("{{\"path\":{}}}", quote(path))); - break; - } - // The frame is read where the game drew it (for most cores one of the - // BSP's two frame buffers): the main loop takes the pointer between two - // frames and then holds, so the game draws nothing over it, until the - // last SCREENSHOT_READ (or a pause in the reading) lets it go on. - release_shot(); - size_t width = 0, height = 0; - { - std::unique_lock lk(shot_mutex_); - shot_state_ = ShotState::CAPTURING; - } - main_.post([this] { - std::unique_lock lk(shot_mutex_); - if (shot_state_ != ShotState::CAPTURING) return; // the request gave up - auto *cart = current_cart(); - shot_size_ = 0; - if (cart) { - cart->capture_hold(true); - auto [w, h] = cart->frame_size(); - const auto pixels = cart->frame_pixels(); - // a core may report more lines than its frame buffer holds (the - // box's NES: 240 for a 224-line frame): keep what is there - if (w) h = std::min(h, pixels.size() / (w * 2)); - shot_width_ = w; - shot_height_ = h; - shot_pixels_ = pixels.data(); - shot_size_ = w * h * 2; - } - else { - // no game: the launcher's screen, drawn into a copy - launcher_shot_ = gui_.snapshot(); - shot_width_ = launcher_shot_.width; - shot_height_ = launcher_shot_.height; - shot_pixels_ = launcher_shot_.pixels.data(); - shot_size_ = launcher_shot_.pixels.size(); - } - shot_state_ = shot_size_ ? ShotState::HELD : ShotState::IDLE; - has_shot_cart_ = cart != nullptr; - shot_cv_.notify_all(); - // hold the game while the frame is read - shot_deadline_ = std::chrono::steady_clock::now() + kShotIdle; - while (shot_state_ == ShotState::HELD && std::chrono::steady_clock::now() < shot_deadline_) { - shot_cv_.wait_until(lk, shot_deadline_); - } - shot_state_ = ShotState::IDLE; - shot_pixels_ = nullptr; - launcher_shot_ = {}; - shot_cv_.notify_all(); - lk.unlock(); - if (cart) cart->capture_hold(false); - }); - std::unique_lock lk(shot_mutex_); - if (!shot_cv_.wait_for(lk, std::chrono::seconds(10), [&] { return shot_state_ != ShotState::CAPTURING; })) { - shot_state_ = ShotState::IDLE; // the posted job skips it - fail("the device is busy (is the pause menu open?)"); - break; - } - if (shot_state_ != ShotState::HELD) { - fail(has_shot_cart_ ? "this game has no frame to capture" : "the launcher could not be drawn"); - break; - } - width = shot_width_; - height = shot_height_; - json(fmt::format("{{\"width\":{},\"height\":{},\"size\":{},\"format\":\"{}\",\"source\":\"{}\"}}", width, - height, shot_size_, kFrameFormat, has_shot_cart_ ? "game" : "launcher")); - break; - } - case Type::SCREENSHOT_READ: { - if (p.size() < 6) { - fail("payload: u32 offset, u16 length"); - break; - } - const uint32_t offset = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); - const size_t length = std::min(p[4] | (p[5] << 8), espp::stream_frame::kMaxPayloadSize - 1); - std::lock_guard lk(shot_mutex_); - if (shot_state_ != ShotState::HELD || !shot_pixels_) { - fail("no screenshot is being read (SCREENSHOT first)"); - break; - } - if (offset < shot_size_) { - const size_t n = std::min(length, shot_size_ - offset); - body.assign(shot_pixels_ + offset, shot_pixels_ + offset + n); - } - if (offset + length >= shot_size_) { - shot_state_ = ShotState::RELEASED; // all read: the game goes on - } else { - shot_deadline_ = std::chrono::steady_clock::now() + kShotIdle; - } - shot_cv_.notify_all(); - break; - } - case Type::USB_DRIVE: { - const bool host = !p.empty() && p[0]; - const bool closed = close_file(); - bool done = false; - on_main([&] { - if (current_cart() && host) return; // a running game uses the card - if (host) { - done = BoxEmu::get().initialize_usb_msc(); - } else { - BoxEmu::get().deinitialize_usb_msc(); - done = !BoxEmu::get().usb_msc_host_has_card(); - if (done) gui_.reload_rom_list(); - } - }, std::chrono::seconds(10)); - if (!closed) fail("the file being written could not be closed (card full?)"); - if (!done) fail(host ? "could not hand the SD card over (a game running?)" : "could not take the SD card back"); - break; - } - case Type::RELOAD_ROMS: - close_file(); - on_main([&] { gui_.reload_rom_list(); }, std::chrono::seconds(5)); - json(fmt::format("{{\"total\":{}}}", gui_.rom_infos().size())); - break; - case Type::ENTER_UPDATER: { -#if DEVLINK_HAS_OTA - fail("this device updates in place (the OTA service, module 0)"); - break; -#else - if (!boot_updater_next()) { - fail("no updater app (ota_1), or otadata could not be written"); - break; - } - close_file(); - // answer first, then restart - reply(frame, true, body); - std::this_thread::sleep_for(std::chrono::milliseconds(300)); - esp_restart(); - return; -#endif - } - case Type::CONSOLE_FILTER: { - std::string key(text); - std::transform(key.begin(), key.end(), key.begin(), - [](unsigned char c) { return static_cast(std::tolower(c)); }); - if (key.empty()) { - json(filter_json()); // a query - break; - } - // On the main loop, as LAUNCH: a launch it has taken (ready_to_play, no - // cart yet) reads the selected game next, which a new filter can change. - // The GUI lock keeps a tap on the screen from starting one meanwhile. - bool pending = false, unknown = false, done = false; - if (!on_main([&] { - std::lock_guard lk(BoxEmu::lvgl_mutex()); - if ((pending = gui_.ready_to_play() && !current_cart())) return; - if (key == "all") { - done = gui_.set_console_filter(std::nullopt); - return; - } - const auto present = gui_.consoles(); - const auto it = std::find_if(present.begin(), present.end(), - [&](Console c) { return key == console_info(c).key; }); - unknown = (it == present.end()); - if (unknown) return; - done = gui_.set_console_filter(*it); - }, std::chrono::seconds(2))) { - break; - } - if (pending) fail("a game is starting"); - else if (unknown) fail(fmt::format("no games for console '{}'", key)); - else if (!done) fail("the filter could not be set"); - 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) - std::string_view path = text; - size_t offset = 0; - if (const auto nul = text.find('\0'); nul != std::string_view::npos) { - path = text.substr(0, nul); - offset = std::strtoul(std::string(text.substr(nul + 1)).c_str(), nullptr, 10); - } - std::error_code ec; - std::string j = "{\"entries\":["; - size_t i = 0; - for (const auto &e : std::filesystem::directory_iterator(std::string(path), ec)) { - if (i < offset) { - i++; - continue; - } - std::error_code ec2; - const bool dir = e.is_directory(ec2); - const uintmax_t size = dir ? 0 : e.file_size(ec2); - auto item = fmt::format("{}{{\"name\":{},\"dir\":{},\"size\":{}}}", i > offset ? "," : "", - quote(e.path().filename().string()), dir, size); - if (j.size() + item.size() + 48 > espp::stream_frame::kMaxPayloadSize) { - j += fmt::format("],\"truncated\":true,\"next\":{}}}", i); - json(j); - goto done; - } - j += item; - i++; - } - if (ec) { - fail(fmt::format("{}: {}", path, ec.message())); - break; - } - j += "]}"; - json(j); - done: - break; - } - case Type::FILE_READ: { - if (p.size() < 7) { - fail("payload: u32 offset, u16 length, path"); - break; - } - const uint32_t offset = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); - const size_t length = std::min(p[4] | (p[5] << 8), espp::stream_frame::kMaxPayloadSize - 1); - const std::string path(reinterpret_cast(p.data() + 6), p.size() - 6); - close_file(path); - FILE *f = fopen(path.c_str(), "rb"); - if (!f) { - fail(fmt::format("cannot open {}", path)); - break; - } - if (fseek(f, offset, SEEK_SET) != 0) { - fclose(f); - fail(fmt::format("cannot seek {} to {}", path, offset)); - break; - } - body.resize(length); - body.resize(fread(body.data(), 1, length, f)); - if (ferror(f)) fail(fmt::format("read error in {} at {}", path, offset)); - fclose(f); - break; - } - case Type::FILE_WRITE: { - if (p.size() < 6) { - fail("payload: u32 offset, u16 path_len, path, data"); - break; - } - const uint32_t offset = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); - const size_t path_len = p[4] | (p[5] << 8); - if (p.size() < 6 + path_len) { - fail("path_len past the end"); - break; - } - const std::string path(reinterpret_cast(p.data() + 6), path_len); - const uint8_t *data = p.data() + 6 + path_len; - const size_t n = p.size() - 6 - path_len; - if (in_use_by_game(path)) { - fail(fmt::format("{} is in use by the running game (quit it first)", path)); - break; - } - if (!open_for_write(path, offset)) { - fail(fmt::format("cannot write {} at {}", path, offset)); - break; - } - if (fwrite(data, 1, n, write_file_) != n) { - close_file(); - fail(fmt::format("write to {} failed (card full?)", path)); - break; - } - write_pos_ = offset + n; - break; - } - 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); - struct stat st; - if (stat(path.c_str(), &st) != 0) { - fail(fmt::format("{} does not exist", path)); - } else if (in_use_by_game(path)) { - fail(fmt::format("{} is in use by the running game (quit it first)", path)); - } else if (S_ISDIR(st.st_mode)) { - std::error_code ec; - std::filesystem::remove_all(path, ec); - if (ec) fail(fmt::format("cannot delete {}: {}", path, ec.message())); - } else if (unlink(path.c_str()) != 0) { - fail(fmt::format("cannot delete {}: {}", path, strerror(errno))); - } - break; - } - case Type::MKDIR: { - std::error_code ec; - std::filesystem::create_directories(std::string(text), ec); - if (ec) fail(fmt::format("{}: {}", text, ec.message())); - break; - } - case Type::FILE_STAT: { - struct stat st; - if (stat(std::string(text).c_str(), &st) != 0) { - fail(fmt::format("{} does not exist", text)); - break; - } - json(fmt::format("{{\"size\":{},\"dir\":{}}}", (uintmax_t)st.st_size, S_ISDIR(st.st_mode))); - break; - } - default: - fail(fmt::format("unknown request type {:#x}", frame.type)); - break; - } - if (card_lock.owns_lock()) card_lock.unlock(); - reply(frame, ok, body); - } - -protected: - static std::string quote(std::string_view s) { - std::string out = "\""; - for (char c : s) { - switch (c) { - case '"': out += "\\\""; break; - case '\\': out += "\\\\"; break; - case '\n': out += "\\n"; break; - case '\r': out += "\\r"; break; - case '\t': out += "\\t"; break; - default: - if ((unsigned char)c < 0x20) out += fmt::format("\\u{:04x}", (unsigned char)c); - else out += c; - } - } - return out + "\""; - } - - static void reply(const espp::stream_frame::Frame &request, bool ok, const std::vector &body) { - std::vector payload; - payload.reserve(body.size() + 1); - payload.push_back(ok ? 0 : 1); - payload.insert(payload.end(), body.begin(), body.end()); - const auto frame = espp::stream_frame::build_frame(true, kModule, request.type, payload, request.correlation); - DevLink::send(frame); - } - - Cart *current_cart() { - std::lock_guard lk(state_mutex_); - return cart_; - } - - /// A path as compared for in_use_by_game(): normalized, no trailing '/', - /// lower case (the card is FAT) - static std::string normal_path(const std::string &path) { - std::string s = std::filesystem::path(path).lexically_normal().string(); - while (s.size() > 1 && s.back() == '/') s.pop_back(); - std::transform(s.begin(), s.end(), s.begin(), - [](unsigned char c) { return static_cast(std::tolower(c)); }); - return s; - } - - /// Whether writing / deleting this path would change files the running - /// game reads while it runs: its ROM (which some cores page in as they go), - /// a folder holding it, or the data folder of a PC port (Doom's WADs, Dark - /// Forces' GOBs) - bool in_use_by_game(const std::string &path) { - const auto within = [](const std::string &p, const std::string &dir) { - return p == dir || (p.size() > dir.size() && p.compare(0, dir.size(), dir) == 0 && - (dir == "/" || p[dir.size()] == '/')); - }; - const std::string target = normal_path(path); - std::lock_guard lk(state_mutex_); - if (game_rom_.empty()) return false; - return within(game_rom_, target) || (!game_folder_.empty() && within(target, game_folder_)); - } - - bool select(const std::string &match) { - // an exact path first, then a part of a name / path - const auto roms = gui_.rom_infos(); - const std::string on_card = std::string(BoxEmu::mount_point) + "/" + match; - const auto exact = std::find_if(roms.begin(), roms.end(), [&](const auto &r) { - return r.rom_path == match || r.rom_path == on_card; - }); - return gui_.select_rom_matching(exact != roms.end() ? exact->rom_path : match); - } - - std::string status() { - std::string rom, platform, console; - bool in_game = false; - uint32_t frames = 0; - { - std::lock_guard lk(state_mutex_); - if (cart_) { - in_game = true; - const auto &info = cart_->rom_info(); - rom = info.rom_path; - platform = fmt::format("{}", info.platform); - console = console_info(console_of(info.platform)).name; - frames = cart_->game_frames(); - } - } - const auto *app = esp_app_get_description(); - const auto *running = esp_ota_get_running_partition(); - return fmt::format("{{\"state\":\"{}\",\"rom\":{},\"platform\":\"{}\",\"console\":{},\"game_frames\":{}," - "\"frames_presented\":{},\"frames_dropped\":{},\"usb_drive\":{}," - "\"uptime_ms\":{},\"internal_free\":{},\"internal_largest\":{},\"internal_min_free\":{}," - "\"psram_free\":{},\"psram_largest\":{},\"psram_min_free\":{},\"dma_free\":{}," - "\"dma_largest\":{},\"firmware\":{},\"built\":{}," - "\"partition\":{},\"elf_sha256\":{},\"reset_reason\":{},\"last_panic\":{},\"filter\":{}}}", - in_game ? "game" : "menu", quote(rom), platform, quote(console), frames, - BoxEmu::get().frames_blitted(), BoxEmu::get().frames_dropped(), - BoxEmu::get().usb_msc_host_has_card(), esp_timer_get_time() / 1000, - heap_caps_get_free_size(MALLOC_CAP_INTERNAL), - heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), - heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL), - heap_caps_get_free_size(MALLOC_CAP_SPIRAM), heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM), - heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM), - heap_caps_get_free_size(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL), - heap_caps_get_largest_free_block(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL), quote(app->version), - quote(fmt::format("{} {}", app->date, app->time)), quote(running ? running->label : ""), - quote(elf_sha256()), (int)esp_reset_reason(), quote(DevLink::last_panic()), - quote(filter_key())); - } - - /// The launcher's console filter: its console's key, empty for all. - std::string filter_key() const { - const auto f = gui_.console_filter(); - return f ? console_info(*f).key : ""; - } - - std::string filter_json() const { - std::string consoles; - for (const Console c : gui_.consoles()) { - consoles += fmt::format("{}{}", consoles.empty() ? "" : ",", quote(console_info(c).key)); - } - return fmt::format("{{\"filter\":{},\"consoles\":[{}]}}", quote(filter_key()), consoles); - } - - /// Make the bootloader start the updater (ota_1) next. esp_ota_set_boot_partition() - /// first verifies the image through a flash mapping, which is unreliable in an - /// app that runs its code from PSRAM (esp-box-emu: the mapping can land on the - /// PSRAM heap's addresses), so the otadata entry is written here directly, with - /// plain SPI flash reads / writes: the same entry esp_ota_ops would write - /// (boot slot = (seq - 1) % slots). The updater, which has no PSRAM, verifies - /// and sets the boot partition the usual way. - static bool boot_updater_next() { - const esp_partition_t *updater = - esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, nullptr); - const esp_partition_t *otadata = - esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, nullptr); - if (!updater || !otadata) return false; - const uint32_t slots = esp_ota_get_app_partition_count(); - const uint32_t sector = otadata->erase_size; - esp_ota_select_entry_t e[2]; - for (int i = 0; i < 2; i++) { - if (esp_partition_read(otadata, i * sector, &e[i], sizeof(e[i])) != ESP_OK) return false; - } - const bool v0 = bootloader_common_ota_select_valid(&e[0]), v1 = bootloader_common_ota_select_valid(&e[1]); - const uint32_t seq = std::max(v0 ? e[0].ota_seq : 0, v1 ? e[1].ota_seq : 0); - uint32_t next = seq + 1; - while ((next - 1) % slots != 1) next++; // slot 1: the updater - // overwrite the older (or an invalid) entry, so the current one survives a failure - const int target = !v0 ? 0 : !v1 ? 1 : (e[0].ota_seq <= e[1].ota_seq ? 0 : 1); - esp_ota_select_entry_t entry; - memset(&entry, 0xFF, sizeof(entry)); - entry.ota_seq = next; - entry.ota_state = ESP_OTA_IMG_VALID; - entry.crc = bootloader_common_ota_select_crc(&entry); - esp_ota_select_entry_t check; - if (esp_partition_erase_range(otadata, target * sector, sector) == ESP_OK && - esp_partition_write(otadata, target * sector, &entry, sizeof(entry)) == ESP_OK && - esp_partition_read(otadata, target * sector, &check, sizeof(check)) == ESP_OK && - memcmp(&check, &entry, sizeof(entry)) == 0) { - return true; - } -#if CONFIG_IDF_TARGET_ESP32S3 - // esp-box-emu: with the flash and PSRAM at 120 MHz the app's flash writes - // do not land; the bootloader (bootloader_components/updater_switch) - // writes the entry when it finds this, at the next reset - REG_WRITE(RTC_CNTL_STORE0_REG, 0x55504454u); // "UPDT" - return true; -#else - return false; -#endif - } - - static std::string elf_sha256() { - char sha[17] = {}; - esp_app_get_elf_sha256(sha, sizeof(sha)); - return sha; - } - - // FILE_WRITE keeps the file open between chunks - bool open_for_write(const std::string &path, uint32_t offset) { - if (write_file_ && path == write_path_ && offset == write_pos_) { - return true; - } - 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"); - } else { - write_file_ = fopen(path.c_str(), "r+b"); - if (write_file_ && fseek(write_file_, offset, SEEK_SET) != 0) { - close_file(); - } - } - if (!write_file_) return false; - write_path_ = path; - write_pos_ = offset; - return true; - } - /// false: the file's buffered data could not be written - bool close_file(const std::string &only_if_path = "") { - // (the handover hook calls this from the task that hands the card over) - std::lock_guard lk(BoxEmu::lvgl_mutex()); - if (write_file_ && (only_if_path.empty() || only_if_path == write_path_)) { - 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; - } - - // the pixels' byte order in the cores' frame buffers (both devices) - static constexpr const char *kFrameFormat = "rgb565le"; - // how long the game is held for a screenshot without a SCREENSHOT_READ - static constexpr std::chrono::milliseconds kShotIdle{2000}; - enum class ShotState { IDLE, CAPTURING, HELD, RELEASED }; - - /// Let the game go on if a screenshot is held (a new one replaces it). - void release_shot() { - std::unique_lock lk(shot_mutex_); - if (shot_state_ == ShotState::HELD) shot_state_ = ShotState::RELEASED; - shot_cv_.notify_all(); - shot_cv_.wait_for(lk, std::chrono::seconds(1), [&] { return shot_state_ == ShotState::IDLE; }); - } - - Gui &gui_; - MainQueue &main_; - std::mutex state_mutex_; - Cart *cart_{nullptr}; - std::string game_rom_; ///< the running game's ROM (normal_path()) - std::string game_folder_; ///< the folder it reads as it runs, if any - // the screenshot being read: the held game's frame buffer - std::mutex shot_mutex_; - std::condition_variable shot_cv_; - ShotState shot_state_{ShotState::IDLE}; - std::chrono::steady_clock::time_point shot_deadline_; - const uint8_t *shot_pixels_{nullptr}; - size_t shot_width_{0}, shot_height_{0}, shot_size_{0}; - bool has_shot_cart_{false}; - Gui::Snapshot launcher_shot_; ///< the launcher's screen, while it is read - 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 b/tools/emulink new file mode 120000 index 0000000..ad3e4cc --- /dev/null +++ b/tools/emulink @@ -0,0 +1 @@ +../components/emulink/tools/emulink \ No newline at end of file diff --git a/tools/emulink/emulink/__init__.py b/tools/emulink/emulink/__init__.py deleted file mode 100644 index c12cea3..0000000 --- a/tools/emulink/emulink/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -"""emulink: drive esp-box-emu / tab5-emu over their composite USB device. - -The device's vendor (WebUSB) interface carries espp `stream_frame` frames -routed by module: OTA (0, esp-box-emu), core dump (4), system (7), monitor (8) -and the emulator's test control (0x20). The CDC interface carries the console -and the MSC interface is the SD card (when handed to the PC). -""" - -from .link import Link, LinkError # noqa: F401 -from .control import Control, ControlError, Buttons # noqa: F401 - -__version__ = "0.1.0" diff --git a/tools/emulink/emulink/__main__.py b/tools/emulink/emulink/__main__.py deleted file mode 100644 index dd8a8c9..0000000 --- a/tools/emulink/emulink/__main__.py +++ /dev/null @@ -1,5 +0,0 @@ -import sys - -from .cli import main - -sys.exit(main()) diff --git a/tools/emulink/emulink/cli.py b/tools/emulink/emulink/cli.py deleted file mode 100644 index d05c83e..0000000 --- a/tools/emulink/emulink/cli.py +++ /dev/null @@ -1,605 +0,0 @@ -"""emulink command line: python -m emulink ...""" - -from __future__ import annotations - -import argparse -import json -import os -import struct -import sys -import time -import zlib -from typing import Optional - -from . import espp_tools -from .control import Buttons, Control, ControlError -from .link import Link, LinkError, find_console_port, find_devices - - -def _progress(label: str): - start = time.monotonic() - - def cb(done: int, total: int) -> None: - if not sys.stderr.isatty(): - return - pct = 100 * done // total if total else 100 - rate = done / max(time.monotonic() - start, 1e-3) / 1024 - sys.stderr.write(f"\r{label}: {pct:3d}% {done}/{total} bytes ({rate:.0f} KiB/s)") - if done >= total: - sys.stderr.write("\n") - sys.stderr.flush() - - return cb - - -def _png(width: int, height: int, rgb: bytes) -> bytes: - raw = b"".join(b"\x00" + rgb[y * width * 3:(y + 1) * width * 3] for y in range(height)) - - def chunk(kind: bytes, data: bytes) -> bytes: - return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) - - return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + - chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b"")) - - -def frame_to_png(frame, big_endian: bool) -> bytes: - return _png(frame.width, frame.height, frame.rgb(big_endian)) - - -def _open(args, timeout_s: float = 0.0) -> Link: - return Link(args.serial).open(timeout_s) - - -def cmd_devices(args) -> int: - for d in find_devices(): - print(f"{d['serial']:12s} {d['product']:20s} bus {d['bus']} address {d['address']} " - f"console {find_console_port(d['serial']) or '-'}") - return 0 - - -def cmd_status(args) -> int: - with _open(args) as link: - print(json.dumps(Control(link).status(), indent=2)) - return 0 - - -def cmd_info(args) -> int: - with _open(args) as link: - print(json.dumps(Control(link).info(), indent=2)) - return 0 - - -def cmd_roms(args) -> int: - with _open(args) as link: - roms = Control(link).roms() - if args.json: - print(json.dumps(roms, indent=2)) - return 0 - console = None - for r in roms: - if r["console"] != console: - console = r["console"] - print(f"== {console}") - print(f" {r['name']} ({r['path']})") - return 0 - - -def cmd_launch(args) -> int: - with _open(args) as link: - rom = Control(link).launch(args.match, wait=not args.no_wait, timeout_s=args.timeout) - print(rom) - return 0 - - -def cmd_quit(args) -> int: - with _open(args) as link: - Control(link).quit(wait=not args.no_wait) - return 0 - - -def cmd_press(args) -> int: - with _open(args) as link: - c = Control(link) - for _ in range(args.repeat): - c.press(args.buttons, hold_ms=args.hold, gap_ms=args.gap) - return 0 - - -def cmd_hold(args) -> int: - with _open(args) as link: - Control(link).buttons(Buttons.parse(args.buttons), 0) - return 0 - - -def cmd_tap(args) -> int: - with _open(args) as link: - c = Control(link) - for _ in range(args.repeat): - c.tap(args.x, args.y, fingers=args.fingers, hold_ms=args.hold, frame=args.frame) - if args.gap: - time.sleep(args.gap / 1000) - return 0 - - -def cmd_touch(args) -> int: - with _open(args) as link: - if args.x is None: - Control(link).release() - elif args.y is None: - raise SystemExit("touch: give x and y (or neither, to lift the finger)") - else: - Control(link).touch(args.x, args.y, fingers=args.fingers, frame=args.frame) - return 0 - - -def cmd_drag(args) -> int: - with _open(args) as link: - Control(link).drag(args.x0, args.y0, args.x1, args.y1, duration_ms=args.ms, steps=args.steps, - fingers=args.fingers, release=not args.no_release, frame=args.frame) - return 0 - - -def cmd_save(args) -> int: - with _open(args) as link: - Control(link).save(args.slot) - return 0 - - -def cmd_load(args) -> int: - with _open(args) as link: - Control(link).load(args.slot) - return 0 - - -def cmd_screenshot(args) -> int: - with _open(args) as link: - frame = Control(link).frame(progress=_progress("screenshot")) - if args.byteswap is not None: - big_endian = args.byteswap - else: # every core so far renders little-endian RGB565 - big_endian = frame.format == "rgb565be" - out = args.output or time.strftime("screenshot-%Y%m%d-%H%M%S.png") - with open(out, "wb") as f: - if out.endswith(".png"): - f.write(frame_to_png(frame, big_endian)) - else: # the device's own screenshot file format - f.write(struct.pack(">HH", frame.width, frame.height) + frame.data) - print(out) - return 0 - - -def cmd_filter(args) -> int: - with _open(args) as link: - r = Control(link).console_filter(args.console) - print(f"filter: {r.get('filter') or 'all'} (consoles: {', '.join(r.get('consoles', [])) or 'none'})") - 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): - print(f"{'d' if e['dir'] else '-'} {e['size']:>10} {e['name']}") - return 0 - - -def cmd_push(args) -> int: - with _open(args) as link: - for f in Control(link).push(args.local, args.remote, _progress(os.path.basename(args.local))): - print(f) - return 0 - - -def cmd_pull(args) -> int: - with _open(args) as link: - data = Control(link).read_file(args.remote, _progress(os.path.basename(args.remote))) - out = args.local or os.path.basename(args.remote) - with open(out, "wb") as f: - f.write(data) - print(out) - return 0 - - -def cmd_rm(args) -> int: - with _open(args) as link: - Control(link).rm(args.path) - return 0 - - -def cmd_mkdir(args) -> int: - with _open(args) as link: - Control(link).mkdir(args.path) - return 0 - - -def cmd_add_rom(args) -> int: - """Copy a game (and its boxart) to the card, list it in metadata.csv, reload.""" - with _open(args) as link: - c = Control(link) - rom_remote = f"{args.dir.strip('/')}/{os.path.basename(args.rom)}" - c.push(args.rom, rom_remote, _progress(os.path.basename(args.rom))) - boxart = "" - if args.boxart: - boxart = f"boxart/{os.path.basename(args.boxart)}" - c.push(args.boxart, boxart, _progress(os.path.basename(args.boxart))) - name = args.name or os.path.splitext(os.path.basename(args.rom))[0] - total = c.add_rom(rom_remote, name, boxart) - print(f"{rom_remote}: listed as {name!r} ({total} games)") - return 0 - - -def cmd_remove_rom(args) -> int: - with _open(args) as link: - c = Control(link) - total = c.add_rom(args.rom, "", remove=True) - if args.delete: - c.rm(args.rom) - print(f"{total} games") - return 0 - - -def cmd_reload(args) -> int: - with _open(args) as link: - print(Control(link).reload_roms()) - return 0 - - -def _msc_disk(product: str) -> Optional[str]: - """macOS: the BSD disk (e.g. disk20) of the emulator's SD card drive.""" - import re - import subprocess - - try: - out = subprocess.run(["ioreg", "-p", "IOService", "-l", "-w0", "-r", "-n", product], - capture_output=True, text=True, timeout=10).stdout - except (OSError, subprocess.TimeoutExpired): - return None - m = re.search(r'"BSD Name" = "(disk\d+)"', out) - return m.group(1) if m else None - - -def _msc_mount(product: str) -> Optional[str]: - """macOS: where the emulator's SD card is mounted, once it is.""" - import plistlib - import subprocess - - disk = _msc_disk(product) - if not disk: - return None - try: - out = subprocess.run(["diskutil", "info", "-plist", f"{disk}s1"], capture_output=True, timeout=10).stdout - mount = plistlib.loads(out).get("MountPoint") if out else None - except (OSError, subprocess.TimeoutExpired, plistlib.InvalidFileException): - return None - return mount or None - - -def cmd_drive(args) -> int: - """Hand the SD card to the PC (it mounts it), or take it back: on macOS the - volume is ejected first, which the device needs before it can have it.""" - with _open(args) as link: - serial = link.serial # (check this device again, not the first one found) - c = Control(link) - if args.state == "on": - c.usb_drive(True) - if sys.platform == "darwin": - deadline = time.monotonic() + 60 - mount = None - while time.monotonic() < deadline and not mount: - time.sleep(0.5) - mount = _msc_mount(link.product) - print(f"the PC has the SD card ({mount or 'not mounted yet'})") - return 0 - if sys.platform == "darwin": - disk = _msc_disk(link.product) - if disk: - import subprocess - - # Spotlight (mdsync) indexing a freshly mounted volume refuses - # the unmount for a while: retry - deadline = time.monotonic() + 60 - while True: - r = subprocess.run(["diskutil", "eject", disk], capture_output=True, text=True, timeout=60) - if r.returncode == 0 or time.monotonic() >= deadline: - break - time.sleep(2) - if r.returncode != 0: - print(f"emulink: could not eject {disk}: {r.stderr.strip() or r.stdout.strip()}", - file=sys.stderr) - return 1 - try: - c.usb_drive(False) - except LinkError: - pass # the device may drop off the bus for a moment to take the card back - # (re)connect and check - deadline = time.monotonic() + 20 - while time.monotonic() < deadline: - try: - with Link(serial).open(5) as link: - if not Control(link).status()["usb_drive"]: - print("the device has the SD card again") - return 0 - except (LinkError, ControlError): - pass - time.sleep(0.5) - print("emulink: the device did not take the SD card back", file=sys.stderr) - return 1 - - -def cmd_reboot(args) -> int: - with _open(args) as link: - try: - Control(link).reboot(bootloader=args.bootloader) - except LinkError: - pass # the device may drop off the bus before its reply gets out - if args.bootloader: - # the ROM's download mode shows up as the chip's USB-Serial-JTAG port - from serial.tools import list_ports - - deadline = time.monotonic() + 15 - while time.monotonic() < deadline: - for p in list_ports.comports(): - if p.vid == 0x303A and p.pid == 0x1001: - print(p.device) - return 0 - time.sleep(0.5) - print("emulink: no download-mode port showed up", file=sys.stderr) - return 1 - return 0 - - -def cmd_log(args) -> int: - """Follow the console; across a reboot (the port goes away and comes back) - it reconnects, so a log can span a reset.""" - import serial - - out = open(args.output, "ab") if args.output else None - write = out.write if out else sys.stdout.buffer.write - end = time.monotonic() + args.duration if args.duration else None - until = args.until.encode() if args.until else None - tail = b"" # (the text can straddle two reads) - first_wait = time.monotonic() + args.wait - while end is None or time.monotonic() < end: - port = find_console_port(args.serial) - if not port: - if time.monotonic() > first_wait and out is None and args.duration == 0 and not args.follow: - print("no emulator console port found", file=sys.stderr) - return 1 - time.sleep(0.2) - continue - try: - with serial.Serial(port, 115200, timeout=0.2) as s: - while end is None or time.monotonic() < end: - data = s.read(4096) - if data: - write(data) - (out or sys.stdout.buffer).flush() - if until: - if until in tail + data: - return 0 - tail = (tail + data)[-len(until):] - except (serial.SerialException, OSError): - time.sleep(0.2) # the device went away (reset): wait for it to come back - return 0 - - -def cmd_coredump(args) -> int: - cd = espp_tools.load("espp_coredump", "coredump") - from espp_coredump.client import CoreDumpClient # type: ignore - - with _open(args) as link: - client = CoreDumpClient(link) - size = client.size() - if not size: - print("no core dump on the device") - return 0 - print(client.summary()) - if args.output: - image = client.read_image() - with open(args.output, "wb") as f: - f.write(image) - print(f"{args.output}: {len(image)} bytes (decode: esp-coredump info_corefile -t raw -c {args.output} " - f"build/.elf)") - if args.erase: - client.erase() - print("erased") - return 0 - - -def cmd_ota(args) -> int: - """Flash a new app over USB. On the Tab5 (no second emulator slot) the - emulator reboots into the updater app first, which takes the image.""" - espp_tools.load("espp_ota", "ota") - from espp_ota.client import OtaClient # type: ignore - - image = open(args.binary, "rb").read() - link = _open(args) - serial = link.serial # (the updater and the new firmware are this same device) - try: - if "updater" not in link.product.lower(): - print("rebooting into the updater ...") - Control(link).enter_updater() - link.close() - time.sleep(2) - link = Link(serial) - deadline = time.monotonic() + 30 - while True: - try: - link.open(5) - if "updater" in link.product.lower(): - break - link.close() - except LinkError: - pass - if time.monotonic() > deadline: - raise LinkError("the updater did not show up") - time.sleep(1) - print(f"flashing {args.binary} ({len(image)} bytes) via {link.product} ...") - OtaClient(link, progress=_progress("ota")).flash(image, image_size=len(image)) - print("done: the device restarts into the new firmware") - finally: - link.close() - if args.wait: - link = Link(serial) - last_error = None - deadline = time.monotonic() + args.wait - while time.monotonic() < deadline: - try: - link.open(5) - if "updater" not in link.product.lower(): - st = Control(link).status() - print(f"up: {st['firmware']} ({st['built']}, elf {st.get('elf_sha256', '?')}) on {st['partition']}") - link.close() - return 0 - link.close() - except (LinkError, ControlError) as e: - last_error = e - link.close() - time.sleep(1) - print(f"the new firmware did not come up ({last_error})", file=sys.stderr) - return 1 - return 0 - - -def build_parser() -> argparse.ArgumentParser: - p = argparse.ArgumentParser(prog="emulink", description=__doc__) - p.add_argument("--serial", help="USB serial number (tab5-emu / esp-box-emu); default: the first one found") - sub = p.add_subparsers(dest="cmd", required=True) - - sub.add_parser("devices", help="list the emulators on USB").set_defaults(fn=cmd_devices) - sub.add_parser("status", help="state, running game, memory, firmware").set_defaults(fn=cmd_status) - sub.add_parser("info", help="chip, firmware, partitions, last reset reason (system service)").set_defaults(fn=cmd_info) - s = sub.add_parser("roms", help="the game list") - s.add_argument("--json", action="store_true") - s.set_defaults(fn=cmd_roms) - s = sub.add_parser("launch", help="start a game (rom path, or part of a name / path)") - s.add_argument("match") - s.add_argument("--no-wait", action="store_true") - s.add_argument("--timeout", type=float, default=60) - s.set_defaults(fn=cmd_launch) - s = sub.add_parser("quit", help="quit the running game") - s.add_argument("--no-wait", action="store_true") - s.set_defaults(fn=cmd_quit) - s = sub.add_parser("press", help="press buttons (a b x y select start up down left right l r l2 r2; a+b = together)") - s.add_argument("buttons", nargs="+") - s.add_argument("--hold", type=int, default=100, help="ms each press is held") - s.add_argument("--gap", type=int, default=100, help="ms after each press") - s.add_argument("--repeat", type=int, default=1) - s.set_defaults(fn=cmd_press) - s = sub.add_parser("hold", help="hold buttons until the next press/hold (hold with none releases)") - s.add_argument("buttons", nargs="*") - s.set_defaults(fn=cmd_hold) - # touch: (x, y) in the screen's logical (landscape) pixels, e.g. 1280x720 - # on the Tab5, 320x240 on the ESP32-S3-BOX; with --frame in the - # screenshot's pixels (the running game's frame, e.g. 320x200) - s = sub.add_parser("tap", help="tap the screen at x y (its pixels, landscape)") - s.add_argument("x", type=int) - s.add_argument("y", type=int) - s.add_argument("--hold", type=int, default=100, help="ms the finger stays down") - s.add_argument("--gap", type=int, default=100, help="ms after each tap") - s.add_argument("--repeat", type=int, default=1) - s.add_argument("--fingers", type=int, default=1, help="2 = a two-finger tap (a right click in ScummVM)") - s.add_argument("--frame", action="store_true", help="x, y in the screenshot's pixels (the game's frame)") - s.set_defaults(fn=cmd_tap) - s = sub.add_parser("touch", help="put a finger down at x y until the next touch/tap/drag (touch with none lifts it)") - s.add_argument("x", type=int, nargs="?") - s.add_argument("y", type=int, nargs="?") - s.add_argument("--fingers", type=int, default=1) - s.add_argument("--frame", action="store_true", help="x, y in the screenshot's pixels (the game's frame)") - s.set_defaults(fn=cmd_touch) - s = sub.add_parser("drag", help="slide a finger from x0 y0 to x1 y1") - for a in ("x0", "y0", "x1", "y1"): - s.add_argument(a, type=int) - s.add_argument("--ms", type=int, default=300, help="how long the slide takes") - s.add_argument("--steps", type=int, default=0, help="moves along the way (0: one per ~16 ms)") - s.add_argument("--fingers", type=int, default=1) - s.add_argument("--no-release", action="store_true", help="leave the finger down at the end") - s.add_argument("--frame", action="store_true", help="x, y in the screenshot's pixels (the game's frame)") - s.set_defaults(fn=cmd_drag) - for name, fn in (("save", cmd_save), ("load", cmd_load)): - s = sub.add_parser(name, help=f"{name} a save state") - s.add_argument("slot", type=int) - s.set_defaults(fn=fn) - s = sub.add_parser("screenshot", help="the running game's frame (or the launcher's screen) as a PNG") - s.add_argument("-o", "--output") - s.add_argument("--byteswap", action=argparse.BooleanOptionalAction, default=None, - help="RGB565 big-endian (default: the byte order the device reports)") - s.set_defaults(fn=cmd_screenshot) - s = sub.add_parser("ls", help="list a directory on the SD card") - s.add_argument("path", nargs="?", default="") - s.set_defaults(fn=cmd_ls) - s = sub.add_parser("push", help="copy a file / directory to the SD card (relative paths are from its root)") - s.add_argument("local") - s.add_argument("remote") - s.set_defaults(fn=cmd_push) - s = sub.add_parser("pull", help="copy a file from the SD card") - s.add_argument("remote") - s.add_argument("local", nargs="?") - s.set_defaults(fn=cmd_pull) - s = sub.add_parser("rm", help="delete a file / directory on the SD card") - s.add_argument("path") - s.set_defaults(fn=cmd_rm) - s = sub.add_parser("mkdir") - s.add_argument("path") - s.set_defaults(fn=cmd_mkdir) - s = sub.add_parser("add-rom", help="copy a game to the card and list it in metadata.csv") - s.add_argument("rom") - s.add_argument("--dir", required=True, help="directory on the card, e.g. genesis") - s.add_argument("--name") - s.add_argument("--boxart", help="a JPEG, copied to boxart/") - s.set_defaults(fn=cmd_add_rom) - s = sub.add_parser("remove-rom", help="take a game out of metadata.csv") - s.add_argument("rom", help="its path on the card, as in metadata.csv") - 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) - s = sub.add_parser("drive", help="hand the SD card to the PC as a USB drive (on) or take it back (off)") - s.add_argument("state", choices=("on", "off")) - s.set_defaults(fn=cmd_drive) - s = sub.add_parser("reboot") - s.add_argument("--bootloader", action="store_true", help="into the ROM download mode (for idf.py flash)") - s.set_defaults(fn=cmd_reboot) - s = sub.add_parser("log", help="print (or save) the console") - s.add_argument("-o", "--output") - s.add_argument("--duration", type=float, default=0, help="seconds (0 = until ^C)") - s.add_argument("--until", help="stop once this text is seen") - s.add_argument("--follow", action="store_true", help="keep waiting for the port to (re)appear") - s.add_argument("--wait", type=float, default=10, help="seconds to wait for the port") - s.set_defaults(fn=cmd_log) - s = sub.add_parser("coredump", help="the last crash: summary, image, erase") - s.add_argument("-o", "--output", help="save the raw core dump") - s.add_argument("--erase", action="store_true") - s.set_defaults(fn=cmd_coredump) - s = sub.add_parser("ota", help="flash a new app (build/.bin) over USB") - s.add_argument("binary") - s.add_argument("--wait", type=float, default=90, help="seconds to wait for it to come up (0 = do not)") - s.set_defaults(fn=cmd_ota) - return p - - -def main(argv: Optional[list] = None) -> int: - args = build_parser().parse_args(argv) - try: - return args.fn(args) - except (LinkError, ControlError, ValueError) as e: - print(f"emulink: {e}", file=sys.stderr) - return 1 - except KeyboardInterrupt: - return 130 diff --git a/tools/emulink/emulink/control.py b/tools/emulink/emulink/control.py deleted file mode 100644 index 71ecf2d..0000000 --- a/tools/emulink/emulink/control.py +++ /dev/null @@ -1,395 +0,0 @@ -"""The emulator's test control (dispatcher module 0x20, "emu.control") and the -espp system service (module 7), on top of a Link.""" - -from __future__ import annotations - -import json -import os -import struct -import sys -import time -from typing import Iterable, List, Optional - -from .link import Link, LinkError - -MODULE = 0x20 -SYSTEM_MODULE = 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 -TOUCH = 0x0F -#: TOUCH: the fingers byte's flag for (x, y) in the screenshot's pixels (the game's frame) -TOUCH_IN_FRAME = 0x80 -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 -CHUNK = 3584 - - -class ControlError(RuntimeError): - pass - - -class Frame: - """A game's frame: RGB565 pixels, row by row. ``format`` is "rgb565le" / - "rgb565be" (None: not reported by the device).""" - - def __init__(self, width: int, height: int, format: Optional[str], data: bytes) -> None: - self.width, self.height, self.format, self.data = width, height, format, data - - def rgb(self, big_endian: bool) -> bytes: - """The pixels as 8-bit RGB.""" - from array import array - px = array("H") - px.frombytes(self.data) - if big_endian != (sys.byteorder == "big"): - px.byteswap() - return b"".join(map(_rgb565_table().__getitem__, px)) - - -_RGB565 = None - - -def _rgb565_table(): - global _RGB565 - if _RGB565 is None: - def entry(v): - r, g, b = (v >> 11) & 0x1F, (v >> 5) & 0x3F, v & 0x1F - return bytes(((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2))) - _RGB565 = [entry(v) for v in range(65536)] - return _RGB565 - - -class Buttons: - """GamepadState::buttons bits.""" - - A, B, X, Y, SELECT, START, UP, DOWN, LEFT, RIGHT, L, R, L2, R2 = (1 << i for i in range(14)) - NAMES = {"a": A, "b": B, "x": X, "y": Y, "select": SELECT, "start": START, "up": UP, "down": DOWN, - "left": LEFT, "right": RIGHT, "l": L, "r": R, "l2": L2, "r2": R2} - - @classmethod - def parse(cls, names: Iterable[str]) -> int: - mask = 0 - for n in names: - for part in n.replace("+", ",").split(","): - part = part.strip().lower() - if not part: - continue - if part not in cls.NAMES: - raise ValueError(f"unknown button {part!r} (one of {', '.join(cls.NAMES)})") - mask |= cls.NAMES[part] - return mask - - -class Control: - def __init__(self, link: Link) -> None: - self.link = link - - # -- plumbing -------------------------------------------------------------- - def _call(self, type_: int, payload: bytes = b"", timeout_s: float = 15.0, raw: bool = False): - fr = self.link.request(MODULE, type_, payload, timeout_s=timeout_s) - if not fr.payload: - raise ControlError("empty reply") - status, body = fr.payload[0], fr.payload[1:] - if status != 0: - try: - msg = json.loads(body.decode()).get("error", body.decode()) - except Exception: - msg = body.decode(errors="replace") - raise ControlError(msg) - if raw: - return body - return json.loads(body.decode()) if body else {} - - @property - def root(self) -> str: - return "/sdcard" - - def remote(self, path: str) -> str: - """A path on the SD card: absolute, or relative to the card's root.""" - if path in ("", "/", "."): - return self.root - if path.startswith(self.root): - return path - return f"{self.root}/{path.lstrip('/')}" - - # -- the emulator ---------------------------------------------------------- - def status(self) -> dict: - return self._call(STATUS) - - def roms(self) -> List[dict]: - out: List[dict] = [] - offset = 0 - while True: - r = self._call(LIST_ROMS, str(offset).encode()) - out += r["roms"] - offset = r["next"] - if offset >= r["total"] or not r["roms"]: - return out - - def launch(self, match: str, wait: bool = True, timeout_s: float = 60.0) -> str: - rom = self._call(LAUNCH, match.encode())["rom"] - if wait: - self.wait_state("game", timeout_s) - return rom - - def quit(self, wait: bool = True, timeout_s: float = 30.0) -> None: - self._call(QUIT) - if wait: - self.wait_state("menu", timeout_s) - - def wait_state(self, state: str, timeout_s: float = 60.0) -> dict: - deadline = time.monotonic() + timeout_s - while True: - try: - st = self.status() - if st["state"] == state: - return st - except LinkError: - pass # busy (e.g. a game loading) - if time.monotonic() > deadline: - raise ControlError(f"not in state {state!r} after {timeout_s:.0f} s") - time.sleep(0.25) - - def buttons(self, mask: int, hold_ms: int = 0) -> None: - """Hold `mask` for hold_ms (then release), or until the next call (0).""" - self._call(BUTTONS, struct.pack(" None: - self.buttons(Buttons.parse(names), hold_ms) - if gap_ms: - time.sleep(gap_ms / 1000) - - def touch(self, x: int, y: int, fingers: int = 1, hold_ms: int = 0, frame: bool = False) -> None: - """Put `fingers` on the screen at (x, y), in its logical (landscape) - pixels, or with `frame` in the screenshot's (the running game's - frame): for hold_ms (then lifted), or until the next call (0). - fingers = 0 lifts them (protocol 5).""" - flags = TOUCH_IN_FRAME if frame and fingers else 0 - self._call(TOUCH, struct.pack(" None: - """Lift the finger(s) held by touch() / drag().""" - self.touch(0, 0, fingers=0) - - def tap(self, x: int, y: int, fingers: int = 1, hold_ms: int = 100, frame: bool = False) -> None: - self.touch(x, y, fingers, hold_ms, frame) - - def drag(self, x0: int, y0: int, x1: int, y1: int, duration_ms: int = 300, steps: int = 0, - fingers: int = 1, release: bool = True, frame: bool = False) -> None: - """Slide a finger from (x0, y0) to (x1, y1) over duration_ms, in - `steps` moves (0: one per ~16 ms), then lift it (unless release is False).""" - steps = steps or max(1, duration_ms // 16) - start = time.monotonic() - for i in range(steps + 1): - self.touch(round(x0 + (x1 - x0) * i / steps), round(y0 + (y1 - y0) * i / steps), fingers, frame=frame) - wait = start + duration_ms / 1000 * (i + 1) / (steps + 1) - time.monotonic() - if wait > 0: - time.sleep(wait) - if release: - self.release() - - def save(self, slot: int) -> None: - self._call(SAVE, bytes([slot]), timeout_s=60) - - def load(self, slot: int) -> None: - self._call(LOAD, bytes([slot]), timeout_s=60) - - def screenshot(self, remote_path: str = "screenshots/screenshot.bin") -> str: - """Save the running game's frame on the SD card ([u16be w][u16be h][RGB565]); returns its path.""" - return self._call(SCREENSHOT, self.remote(remote_path).encode())["path"] - - def frame(self, progress=None) -> "Frame": - """The running game's frame, copied straight from its frame buffer, - or with no game running (protocol 3) the launcher's screen (firmware - before protocol 2 saves it on the card and it is read from there).""" - info = self._call(SCREENSHOT, timeout_s=15) - if "path" in info: # older firmware - data = self.read_file(info["path"]) - if len(data) < 4: - raise ControlError(f"the screenshot file {info['path']} is {len(data)} bytes") - w, h = struct.unpack(">HH", data[:4]) - px = data[4:] - if w: - h = min(h, len(px) // (w * 2)) - return Frame(w, h, None, px[:w * h * 2]) - size = info["size"] - out = bytearray() - while len(out) < size: - n = min(4000, size - len(out)) - chunk = self._call(SCREENSHOT_READ, struct.pack(" None: - self._call(USB_DRIVE, bytes([1 if host else 0]), timeout_s=20) - - def console_filter(self, console: str | None = None) -> dict: - """Set the launcher's console filter (a console key such as "snes", or - "all"); with None, only report it (an empty request changes nothing on - the device). -> {filter, consoles}""" - if console is None: - 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"] - - def enter_updater(self) -> None: - self._call(ENTER_UPDATER) - - # -- files on the SD card -------------------------------------------------- - def ls(self, path: str = "") -> List[dict]: - path = self.remote(path).encode() - r = self._call(FILE_LIST, path) - out = r["entries"] - # a full page says where the next starts; older firmware only says "truncated" - while r.get("truncated") and r.get("next") is not None and r["entries"]: - r = self._call(FILE_LIST, path + b"\0" + str(r["next"]).encode()) - out += r["entries"] - return out - - def stat(self, path: str) -> Optional[dict]: - """None if there is no such file; any other failure raises.""" - try: - return self._call(FILE_STAT, self.remote(path).encode()) - except ControlError as e: - if "does not exist" in str(e): - return None - raise - - def mkdir(self, path: str) -> None: - self._call(MKDIR, self.remote(path).encode()) - - def rm(self, path: str) -> None: - self._call(FILE_DELETE, self.remote(path).encode(), timeout_s=60) - - def read_file(self, path: str, progress=None) -> bytes: - path = self.remote(path) - st = self._call(FILE_STAT, path.encode()) - size = st["size"] - out = bytearray() - while len(out) < size: - n = min(4000, size - len(out)) - chunk = self._call(FILE_READ, struct.pack(" None: - path = self.remote(path) - p = path.encode() - chunk = CHUNK - len(p) - if chunk < 256: - raise ControlError("path too long") - off = 0 - while True: - part = data[off: off + chunk] - self._call(FILE_WRITE, struct.pack("= len(data): - break - self._call(FILE_CLOSE) - - def push(self, local: str, remote: str, progress=None) -> List[str]: - """Copy a file or a directory tree to the SD card; returns the remote files.""" - written = [] - if os.path.isdir(local): - for root, _dirs, files in os.walk(local): - for f in files: - src = os.path.join(root, f) - rel = os.path.relpath(src, local) - dst = f"{remote.rstrip('/')}/{rel}" - self.write_file(dst, open(src, "rb").read(), progress) - written.append(self.remote(dst)) - else: - if remote.endswith("/"): - remote += os.path.basename(local) - self.write_file(remote, open(local, "rb").read(), progress) - written.append(self.remote(remote)) - return written - - def add_rom(self, rom_path: str, name: str, boxart: str = "", remove: bool = False) -> int: - """Add (or with remove=True take out) a metadata.csv line; returns the - number of games after reloading the list.""" - rom_rel = rom_path[len(self.root) + 1:] if rom_path.startswith(self.root + "/") else rom_path - # metadata.csv has no quoting: the paths end at a comma (the name, the - # last field, may have them) and a line break starts another game - for field, value in (("ROM path", rom_rel), ("boxart path", boxart), ("name", name)): - if "\n" in value or "\r" in value or (field != "name" and "," in value): - raise ControlError(f"the {field} cannot hold {'a comma' if ',' in value else 'a line break'}: {value!r}") - meta = self.remote("metadata.csv") - # only a missing file starts an empty list: a failed read must not - # rewrite metadata.csv with just this game - text = self.read_file(meta).decode() if self.stat(meta) is not None else "" - lines = [l for l in text.splitlines() if l.strip() and l.split(",")[0].strip() != rom_rel] - if not remove: - lines.append(f"{rom_rel}, {boxart}, {name}") - self.write_file(meta, ("\n".join(lines) + "\n").encode()) - return self.reload_roms() - - # -- the espp system service ------------------------------------------------ - 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"} - - def info(self) -> dict: - """The espp system service's GET_INFO: chip, firmware, partitions, reset reason, uptime...""" - fr = self.link.request(SYSTEM_MODULE, 0x01, b"", timeout_s=5, reply_types=(0x81, 0x84)) - if fr.type != 0x81: - raise ControlError("GET_INFO failed") - p, i, out = fr.payload, 0, {} - strs = {1: "chip", 6: "project", 7: "firmware", 5: "idf", 8: "build_date", 9: "build_time", - 11: "running_partition", 12: "boot_partition"} - while i + 2 <= len(p): - tag, n = p[i], p[i + 1] - v = p[i + 2:i + 2 + n] - i += 2 + n - if tag in strs: - out[strs[tag]] = v.decode(errors="replace") - elif tag == 2: - out["chip_revision"] = int.from_bytes(v, "little") - elif tag == 3: - out["cores"] = v[0] - elif tag == 10: - out["elf_sha256"] = v.hex() - elif tag == 13: - out["ota_state"] = {0: "new", 1: "pending verify", 2: "valid", 3: "invalid", 4: "aborted", - 0xFE: "undefined", 0xFF: "n/a"}.get(v[0], v[0]) - elif tag == 14: - out["reset_reason"] = self.RESET_REASONS.get(v[0], v[0]) - elif tag == 15: - out["uptime_ms"] = int.from_bytes(v, "little") - elif tag == 16: - out["mac"] = ":".join(f"{b:02x}" for b in v) - elif tag in (17, 18, 19, 20, 21): - out[{17: "flash_size", 18: "psram_size", 19: "cpu_mhz", 20: "free_heap", 21: "min_free_heap"}[tag]] = \ - int.from_bytes(v, "little") - return out - - def reboot(self, bootloader: bool = False, delay_ms: int = 250) -> None: - self.link.request(SYSTEM_MODULE, 0x03 if bootloader else 0x02, struct.pack("/python``) or in a project's -``managed_components/espp__/python`` after a build. -""" - -from __future__ import annotations - -import importlib -import os -import sys -from pathlib import Path - -_HERE = Path(__file__).resolve() -_REPO = _HERE.parents[3] # tools/emulink/emulink/espp_tools.py -> the project - - -def _candidates(component: str): - if os.environ.get("ESPP_DIR"): - yield Path(os.environ["ESPP_DIR"]) / "components" / component / "python" - for base in (_REPO, _REPO / "updater"): - yield base / "managed_components" / f"espp__{component}" / "python" - yield Path.home() / "esp-cpp" / "espp" / "components" / component / "python" - - -def load(package: str, component: str): - """Import `package` (e.g. espp_ota) from wherever the espp component is.""" - try: - return importlib.import_module(package) - except ImportError: - pass - for c in _candidates(component): - if (c / package).is_dir(): - sys.path.insert(0, str(c)) - return importlib.import_module(package) - raise ImportError(f"{package} not found: set ESPP_DIR to an espp checkout, or build the project " - f"so managed_components/espp__{component} exists") diff --git a/tools/emulink/emulink/frame.py b/tools/emulink/emulink/frame.py deleted file mode 100644 index 6949550..0000000 --- a/tools/emulink/emulink/frame.py +++ /dev/null @@ -1,86 +0,0 @@ -"""The espp stream_frame v2 codec (see espp/components/stream_frame). - -[magic u16 = 0x4F54]["flags u8"][module u8][type u8]{[correlation u16]}[len u32][payload][crc32 u32] -little-endian; flags bit0 = reply, bit1 = correlation present, bits 4..7 = version (1). -""" - -from __future__ import annotations - -import struct -import zlib -from dataclasses import dataclass -from typing import List, Optional - -MAGIC = 0x4F54 -MAGIC_BYTES = struct.pack(" bool: - return bool(self.flags & FLAG_REPLY) - - -def build(module: int, type_: int, payload: bytes = b"", reply: bool = False, - correlation: Optional[int] = None) -> bytes: - if len(payload) > MAX_PAYLOAD: - raise ValueError(f"payload too large ({len(payload)} > {MAX_PAYLOAD})") - flags = (VERSION << 4) | (FLAG_REPLY if reply else 0) | (FLAG_CORRELATION if correlation is not None else 0) - out = bytearray(MAGIC_BYTES) - out += bytes([flags, module & 0xFF, type_ & 0xFF]) - if correlation is not None: - out += struct.pack(" None: - self._buf = bytearray() - - def feed(self, data: bytes) -> List[Frame]: - self._buf += data - frames: List[Frame] = [] - while True: - i = self._buf.find(MAGIC_BYTES) - if i < 0: - # keep a trailing half magic - del self._buf[:-1] - return frames - if i: - del self._buf[:i] - if len(self._buf) < 5: - return frames - flags = self._buf[2] - hdr = 5 + (2 if flags & FLAG_CORRELATION else 0) + 4 - if len(self._buf) < hdr: - return frames - corr = struct.unpack_from(" MAX_PAYLOAD: - del self._buf[:2] # not a frame: resync past this magic - continue - total = hdr + length + 4 - if len(self._buf) < total: - return frames - crc = struct.unpack_from(" List[dict]: - """The emulators on the bus: [{serial, product, bus, address}].""" - core, util = _usb() - out = [] - for dev in core.find(find_all=True, idVendor=VID, idProduct=PID) or []: - try: - serial = util.get_string(dev, dev.iSerialNumber) - product = util.get_string(dev, dev.iProduct) - except Exception: - continue - if serial in SERIALS: - out.append({"serial": serial, "product": product, "bus": dev.bus, "address": dev.address, "dev": dev}) - return out - - -class Link: - """One open vendor interface. Also a transport for the espp host clients - (``write(bytes, timeout_ms)`` / ``read(max_len, timeout_ms)``).""" - - def __init__(self, serial: Optional[str] = None) -> None: - self.serial = serial or os.environ.get("EMULINK_SERIAL") - self._dev = None - self._itf = None - self._ep_in = None - self._ep_out = None - self._parser = _f.Parser() - self._pending: Deque[_f.Frame] = deque() - self._corr = itertools.count(1) - self.product = "" - - # -- lifecycle ------------------------------------------------------------- - def open(self, timeout_s: float = 0.0) -> "Link": - core, util = _usb() - deadline = time.monotonic() + timeout_s - while True: - devs = [d for d in find_devices() if self.serial in (None, d["serial"])] - if devs: - break - if time.monotonic() >= deadline: - raise LinkError("no emulator found on USB" + (f" with serial {self.serial!r}" if self.serial else "")) - time.sleep(0.5) - d = devs[0] - self._dev, self.serial, self.product = d["dev"], d["serial"], d["product"] - try: - return self._claim(core, util) - except core.USBError as e: - # e.g. still enumerating after a reset: the caller may retry - self._dev = None - raise LinkError(f"cannot open the device's vendor interface: {e}") from e - - def _claim(self, core, util) -> "Link": - cfg = self._dev.get_active_configuration() - for itf in cfg: - if itf.bInterfaceClass != 0xFF: - continue - eps = list(itf) - ep_in = next((e for e in eps if util.endpoint_direction(e.bEndpointAddress) == util.ENDPOINT_IN), None) - ep_out = next((e for e in eps if util.endpoint_direction(e.bEndpointAddress) == util.ENDPOINT_OUT), None) - if ep_in is not None and ep_out is not None: - self._itf, self._ep_in, self._ep_out = itf.bInterfaceNumber, ep_in, ep_out - break - if self._itf is None: - raise LinkError("the device has no vendor interface") - try: - if self._dev.is_kernel_driver_active(self._itf): - self._dev.detach_kernel_driver(self._itf) - except (NotImplementedError, core.USBError): - pass - util.claim_interface(self._dev, self._itf) - return self - - def close(self) -> None: - if self._dev is not None: - _, util = _usb() - try: - util.release_interface(self._dev, self._itf) - util.dispose_resources(self._dev) - except Exception: - pass - self._dev = None - self._itf = None - # (a reply cut off by a reset must not be glued onto the next one) - self._parser = _f.Parser() - self._pending.clear() - - def __enter__(self) -> "Link": - return self.open() if self._dev is None else self - - def __exit__(self, *exc) -> None: - self.close() - - # -- raw transport (espp clients use these) -------------------------------- - def write(self, data: bytes, timeout_ms: int = 5000) -> int: - try: - return self._ep_out.write(data, timeout=timeout_ms) - except Exception as e: - raise LinkError(f"USB write failed: {e}") from e - - def read(self, max_len: int = 16384, timeout_ms: int = 1000) -> bytes: - core, _ = _usb() - try: - return bytes(self._ep_in.read(max(max_len, 64), timeout=timeout_ms)) - except core.USBTimeoutError: - return b"" - except core.USBError as e: - if getattr(e, "errno", None) in (60, 110) or "timed out" in str(e).lower(): - return b"" - raise LinkError(f"USB read failed: {e}") from e - - # -- request / reply ------------------------------------------------------- - def request(self, module: int, type_: int, payload: bytes = b"", timeout_s: float = 10.0, - reply_types: Optional[tuple] = None) -> _f.Frame: - """Send a request and return its reply (matched by module and - correlation id; frames for anything else are dropped).""" - corr = next(self._corr) & 0xFFFF - try: - self.write(_f.build(module, type_, payload, correlation=corr)) - except LinkError: - # the host reset the interface (e.g. macOS after ejecting the - # device's drive): open it again once - self.close() - self.open(timeout_s=10) - self.write(_f.build(module, type_, payload, correlation=corr)) - deadline = time.monotonic() + timeout_s - while time.monotonic() < deadline: - while self._pending: - fr = self._pending.popleft() - if fr.is_reply and fr.module == module and (fr.correlation in (None, corr)) and \ - (reply_types is None or fr.type in reply_types): - return fr - data = self.read(16384, timeout_ms=200) - if data: - self._pending.extend(self._parser.feed(data)) - raise LinkError(f"no reply from module {module:#x} to request {type_:#x} in {timeout_s:.0f} s") - - -def find_console_port(serial: Optional[str] = None) -> Optional[str]: - """The CDC console's serial port (e.g. /dev/cu.usbmodem...) of an emulator.""" - from serial.tools import list_ports - - for p in list_ports.comports(): - if p.vid == VID and p.pid == PID and (p.serial_number in SERIALS) and serial in (None, p.serial_number): - return p.device - return None diff --git a/web b/web new file mode 120000 index 0000000..29b806b --- /dev/null +++ b/web @@ -0,0 +1 @@ +components/emulink/web \ No newline at end of file diff --git a/web/README.md b/web/README.md deleted file mode 100644 index 6faa5c7..0000000 --- a/web/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# 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. The screen is a touch - screen too: click or drag on it to touch the device's screen there. -- **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 deleted file mode 100644 index 822c720..0000000 --- a/web/app.css +++ /dev/null @@ -1,196 +0,0 @@ -: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 { touch-action: none; cursor: crosshair; 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 deleted file mode 100644 index 31c2162..0000000 --- a/web/app.js +++ /dev/null @@ -1,915 +0,0 @@ -// 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; } - -// The screenshot is a touch screen: a press, a drag and a release on it are a -// finger on the device's screen at the same spot (in the frame's pixels; one -// touch request in flight at a time, the latest position wins) -function initScreenTouch() { - const c = $("screen"); - let down = false, sending = false, pending = null; - const send = async (fingers, x, y) => { - pending = [fingers, x, y]; - if (sending) return; - sending = true; - try { - while (pending && state.ctl) { - const [f, px, py] = pending; - pending = null; - await state.ctl.touch(f, px, py, { frame: true }); - } - } catch (e) { - toast("Touch: " + (e.message || e), true); - } finally { - sending = false; - pending = null; - } - }; - const at = (ev) => { - const r = c.getBoundingClientRect(); - return [Math.floor((ev.clientX - r.left) * c.width / r.width), Math.floor((ev.clientY - r.top) * c.height / r.height)]; - }; - c.addEventListener("pointerdown", (ev) => { - if (!state.ctl || !state.lastShot) return; - ev.preventDefault(); - c.setPointerCapture?.(ev.pointerId); - down = true; - send(1, ...at(ev)); - }); - c.addEventListener("pointermove", (ev) => { if (down) send(1, ...at(ev)); }); - const up = () => { - if (!down) return; - down = false; - send(0, 0, 0); - if (!state.live) setTimeout(capture, 300); // what the touch did - }; - c.addEventListener("pointerup", up); - c.addEventListener("pointercancel", up); - c.addEventListener("lostpointercapture", up); -} - -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(); - initScreenTouch(); - $("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 deleted file mode 100644 index ef566a3..0000000 --- a/web/index.html +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - 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 deleted file mode 100644 index 6fb96a0..0000000 --- a/web/link.js +++ /dev/null @@ -1,486 +0,0 @@ -// 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, TOUCH: 0x0f, - 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 || ""); } - /** A finger at (x, y) (fingers 0 lifts it): in the screen's pixels, or with - * `frame` in the screenshot's (the running game's frame); held for holdMs, - * or until the next touch (0). */ - touch(fingers, x, y, { holdMs = 0, frame = false } = {}) { - const f = (fingers & 0x7f) | (frame && fingers ? 0x80 : 0); - return this.call(T.TOUCH, cat(new Uint8Array([f]), u16le(Math.max(0, x)), u16le(Math.max(0, y)), u16le(holdMs)), - { timeoutMs: holdMs + 5000 }); - } - - /** `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; -}