diff --git a/.github/workflows/build_and_publish_docs.yml b/.github/workflows/build_and_publish_docs.yml index 8587edfb88..3739704dd3 100644 --- a/.github/workflows/build_and_publish_docs.yml +++ b/.github/workflows/build_and_publish_docs.yml @@ -39,10 +39,11 @@ jobs: # written next to their pages (components/*/web/*.js), so the apps # copy below publishes them and the pages offer "Connect virtual device" run: | - git submodule update --init components/format/detail/fmt components/serialization/detail/alpaca + git submodule update --init components/format/detail/fmt components/serialization/detail/alpaca components/hid-rp/detail/hid-rp source ~/emsdk/emsdk_env.sh components/canopen/can_bridge_example/virtual/build_wasm.sh components/gamepad_map/virtual/build_wasm.sh + components/hid-rp/inspector/build_wasm.sh - name: Build Documentation (HTML) run: | cd doc diff --git a/.github/workflows/host_tests.yml b/.github/workflows/host_tests.yml index d1cbecf35e..141b51eb09 100644 --- a/.github/workflows/host_tests.yml +++ b/.github/workflows/host_tests.yml @@ -111,10 +111,11 @@ jobs: ~/emsdk/emsdk activate "$EMSDK_VERSION" - name: Build the virtual devices run: | - git submodule update --init components/format/detail/fmt components/serialization/detail/alpaca + git submodule update --init components/format/detail/fmt components/serialization/detail/alpaca components/hid-rp/detail/hid-rp source ~/emsdk/emsdk_env.sh components/canopen/can_bridge_example/virtual/build_wasm.sh components/gamepad_map/virtual/build_wasm.sh + components/hid-rp/inspector/build_wasm.sh - name: The protocol, end to end (the apps' code over the virtual device) env: REQUIRE_VIRTUAL_DEVICES: "1" @@ -131,3 +132,8 @@ jobs: REQUIRE_VIRTUAL_DEVICES: "1" CHROME: google-chrome run: node components/gamepad_map/web/test/virtual_device_ui_test.js + - name: The HID Descriptor Inspector in headless Chrome + env: + REQUIRE_VIRTUAL_DEVICES: "1" + CHROME: google-chrome + run: node components/hid-rp/web/test/hid_inspector_ui_test.js diff --git a/.gitignore b/.gitignore index e2493169df..bb4130632c 100644 --- a/.gitignore +++ b/.gitignore @@ -79,3 +79,4 @@ components/rtps/interop/qemu/images/ # the docs build publishes them, they are never committed components/canopen/web/virtual_can_bridge.js components/gamepad_map/web/virtual_gamepad_map.js +components/hid-rp/web/hid_inspector.js diff --git a/components/dispatcher/web/test/shared_blocks_test.js b/components/dispatcher/web/test/shared_blocks_test.js index 3b85cc9f68..9adbb7d7c0 100644 --- a/components/dispatcher/web/test/shared_blocks_test.js +++ b/components/dispatcher/web/test/shared_blocks_test.js @@ -32,7 +32,7 @@ const expected = { "virtual device": 3, // the CAN bridge console and DS402 panel (virtual CAN bridge), the Gamepad Map console "module discovery": 11, // every dispatcher-module console "connection helpers": 12, // ... and the hub - "app navigation": 19, // every web app + "app navigation": 20, // every web app "app hand-back": 11, // every dispatcher-module console }; for (const block of S.BLOCKS) { diff --git a/components/hid-rp/README.md b/components/hid-rp/README.md index 9622a10a7b..8f1bc7d4ef 100644 --- a/components/hid-rp/README.md +++ b/components/hid-rp/README.md @@ -23,6 +23,28 @@ Pop balance, only known items, a usage page for every short usage) and returns exceptions are enabled; without them (ESP-IDF's default) a truncated or malformed descriptor made it read past the buffer. +## Descriptor inspector + +The [HID Descriptor Inspector](https://esp-cpp.github.io/espp/apps/hid_descriptor_inspector.html) +web app shows a pasted report descriptor the way the firmware reads it: every +item, the fields `ReportMap` maps (bit offsets, usages, logical ranges), the +report sizes, what the decoders take it for (a gamepad and its button layout, a +keyboard, a mouse), and any input report decoded into the `GamepadState` a +remapper sees, typed in or live from a HID device through WebHID (browsers do +not hand a page the raw descriptor, so it is pasted; they also keep keyboards +and mice from WebHID). The parsing is this component's own C++ +(`inspector/hid_inspector.hpp`, host-tested by `test/hid_inspector_host_test.cpp`), +compiled to WebAssembly: + +``` +source /emsdk_env.sh # emsdk install 4.0.10 && emsdk activate 4.0.10 +components/hid-rp/inspector/build_wasm.sh +``` + +That writes `web/hid_inspector.js` (gitignored; the docs build publishes it +with the apps). `web/test/hid_inspector_ui_test.js` runs the page in headless +Chrome; CI builds the module and requires it. + ## Rumble `hid-rp-rumble.hpp` handles rumble in both directions of a controller bridge: diff --git a/components/hid-rp/inspector/build_wasm.sh b/components/hid-rp/inspector/build_wasm.sh new file mode 100755 index 0000000000..b55b82f62a --- /dev/null +++ b/components/hid-rp/inspector/build_wasm.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Build the HID descriptor inspector's C++ side (hid-rp's ReportMap and +# decoders) for the hid_descriptor_inspector web app, with a pinned Emscripten: +# +# source /emsdk_env.sh # emsdk install 4.0.10 && emsdk activate 4.0.10 +# components/hid-rp/inspector/build_wasm.sh [out.js] +# +# Writes components/hid-rp/web/hid_inspector.js by default (gitignored): the +# WebAssembly module inlined (base64) in its loader, so the page works from +# file:// as well as from the published apps (the docs build runs this, then +# copies it beside the page). Without it the page says how to build it. +set -euo pipefail +EMSCRIPTEN_VERSION=4.0.10 +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +components="$(cd "$here/../.." && pwd)" +have="$(emcc --version | head -1 | sed -E 's/.* ([0-9]+\.[0-9]+\.[0-9]+) .*/\1/')" +if [ "$have" != "$EMSCRIPTEN_VERSION" ]; then + echo "need Emscripten $EMSCRIPTEN_VERSION (emsdk install/activate $EMSCRIPTEN_VERSION), have $have" >&2 + exit 1 +fi +out="${1:-$components/hid-rp/web/hid_inspector.js}" +mkdir -p "$(dirname "$out")" +for h in "$components/hid-rp/detail/hid-rp/hid-rp/hid/rdf/parser.hpp" \ + "$components/format/detail/fmt/include/fmt/format.h"; do + [ -f "$h" ] || { echo "missing $h: git submodule update --init components/hid-rp/detail/hid-rp components/format/detail/fmt" >&2; exit 1; } +done +includes=(-I"$here") +for d in "$components"/*/include; do includes+=(-I"$d"); done +includes+=(-isystem "$components/hid-rp/detail/hid-rp/hid-rp" + -isystem "$components/format/detail/fmt/include") +# -fno-exceptions, as the firmware builds hid-rp (ReportMap::parse() checks the +# descriptor first, so its parser's assertions are never needed) +em++ -std=c++23 -Oz -fno-exceptions -flto "${includes[@]}" "$here/hid_inspector_wasm.cpp" \ + -sMODULARIZE -sEXPORT_NAME=HidInspectorModule -sENVIRONMENT=web,node -sSINGLE_FILE=1 \ + -sALLOW_MEMORY_GROWTH -sFILESYSTEM=0 -sASSERTIONS=0 \ + -sEXPORTED_FUNCTIONS=_hri_alloc,_hri_free,_hri_parse,_hri_decode,_hri_presets \ + -sEXPORTED_RUNTIME_METHODS=HEAPU8,UTF8ToString \ + -o "$out" +echo "wrote $out ($(wc -c < "$out" | tr -d ' ') bytes)" diff --git a/components/hid-rp/inspector/hid_inspector.hpp b/components/hid-rp/inspector/hid_inspector.hpp new file mode 100644 index 0000000000..b1d11efb07 --- /dev/null +++ b/components/hid-rp/inspector/hid_inspector.hpp @@ -0,0 +1,492 @@ +#pragma once + +// The HID descriptor inspector's C++ side: what the hid_descriptor_inspector +// web app shows, computed by the same code the firmware runs +// (espp::hid_rp::ReportMap and the gamepad / keyboard / mouse decoders, on +// hid-rp's descriptor parser), as JSON strings the page renders. Built into +// WebAssembly by build_wasm.sh (hid_inspector_wasm.cpp), host-tested by +// test/hid_inspector_host_test.cpp. +// +// parse_json(descriptor) -> the items, the Input / Output fields, the report +// sizes, and what the descriptor looks like (a +// gamepad and its button layout, a keyboard, a mouse) +// decode_json(descriptor, report, vid, pid, combine) +// -> one report decoded as each kind it looks like, and +// the GamepadState a remapper (gamepad_map) sees +// presets() -> descriptors to start from: hid-rp's generated +// ones and a real controller's + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gamepad_state.hpp" +#include "gamepad_state_hid_rp.hpp" +#include "hid-rp-3dconnexion.hpp" +#include "hid-rp-playstation.hpp" +#include "hid-rp-report-map.hpp" +#include "hid-rp-xbox.hpp" + +namespace espp::hid_inspector { + +namespace detail { + +/// A minimal JSON writer (objects, arrays, strings, numbers, booleans). +class Json { +public: + Json &begin_object() { return open('{'); } + Json &end_object() { return close('}'); } + Json &begin_array() { return open('['); } + Json &end_array() { return close(']'); } + Json &key(std::string_view k) { + comma(); + string_literal(k); + out_ += ':'; + after_key_ = true; + return *this; + } + Json &value(std::string_view s) { + comma(); + string_literal(s); + return *this; + } + Json &value(const char *s) { return value(std::string_view(s)); } + Json &value(bool b) { + comma(); + out_ += b ? "true" : "false"; + return *this; + } + template + requires std::is_integral_v Json &value(T n) { + comma(); + out_ += std::to_string(n); + return *this; + } + Json &null() { + comma(); + out_ += "null"; + return *this; + } + template Json &field(std::string_view k, const T &v) { return key(k).value(v); } + const std::string &str() const { return out_; } + +private: + Json &open(char c) { + comma(); + out_ += c; + first_ = true; + return *this; + } + Json &close(char c) { + out_ += c; + first_ = false; + return *this; + } + void comma() { + if (after_key_) { + after_key_ = false; + return; + } + if (!first_ && !out_.empty()) + out_ += ','; + first_ = false; + } + void string_literal(std::string_view s) { + out_ += '"'; + for (char c : s) { + if (c == '"' || c == '\\') { + out_ += '\\'; + out_ += c; + } else if (static_cast(c) < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast(c)); + out_ += buf; + } else { + out_ += c; + } + } + out_ += '"'; + } + std::string out_; + bool first_{true}; + bool after_key_{false}; +}; + +/// The HID short item's name (HID 1.11, 6.2.2.4-6.2.2.8), by type and tag. +inline const char *item_name(unsigned type, unsigned tag) { + static const char *const main_names[16] = { + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + "Input", "Output", "Collection", "Feature", "End Collection", nullptr, nullptr, nullptr}; + static const char *const global_names[16] = {"Usage Page", + "Logical Minimum", + "Logical Maximum", + "Physical Minimum", + "Physical Maximum", + "Unit Exponent", + "Unit", + "Report Size", + "Report ID", + "Report Count", + "Push", + "Pop", + nullptr, + nullptr, + nullptr, + nullptr}; + static const char *const local_names[16] = {"Usage", + "Usage Minimum", + "Usage Maximum", + "Designator Index", + "Designator Minimum", + "Designator Maximum", + nullptr, + "String Index", + "String Minimum", + "String Maximum", + "Delimiter", + nullptr, + nullptr, + nullptr, + nullptr, + nullptr}; + const char *name = nullptr; + if (tag < 16) { + if (type == 0) + name = main_names[tag]; + else if (type == 1) + name = global_names[tag]; + else if (type == 2) + name = local_names[tag]; + } + return name ? name : "(reserved)"; +} + +inline const char *item_type_name(unsigned type) { + switch (type) { + case 0: + return "main"; + case 1: + return "global"; + case 2: + return "local"; + default: + return "reserved"; + } +} + +inline void write_field(Json &j, const hid_rp::ReportField &f) { + j.begin_object() + .field("report_id", f.report_id) + .field("bit_offset", f.bit_offset) + .field("bit_size", f.bit_size) + .field("usage_page", f.usage_page) + .field("usage", f.usage) + .field("usage_max", f.usage_max) + .field("logical_min", f.logical_min) + .field("logical_max", f.logical_max) + .field("array", f.array) + .field("relative", f.relative) + .field("unit", f.unit) + .field("unit_exponent", f.unit_exponent) + .end_object(); +} + +/// The report IDs a descriptor's fields use, in order of first appearance. +inline std::vector report_ids(const std::vector &fields) { + std::vector ids; + for (const auto &f : fields) + if (std::find(ids.begin(), ids.end(), f.report_id) == ids.end()) + ids.push_back(f.report_id); + return ids; +} + +/// Parse with hid-rp's parser, catching what it throws for a malformed descriptor. +inline std::optional parse_map(std::span descriptor) { +#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND) + try { + return hid_rp::ReportMap::parse(descriptor); + } catch (const ::hid::rdf::exception &) { + return std::nullopt; + } +#else + return hid_rp::ReportMap::parse(descriptor); +#endif +} + +} // namespace detail + +/// The descriptor's items, fields, report sizes and classification, as JSON: +/// +/// {"ok": bool, "error": "...", "items": [{"offset","size","type","tag","name", +/// "data": "hex", "value", "signed"}...], "uses_report_ids", "fields": [...], +/// "output_fields": [...], "reports": [{"id", "bytes"}], "output_reports": [...], +/// "kind": {"gamepad", "keyboard", "mouse"}, "gamepad_layout": "..."} +/// +/// The item list is walked byte by byte (an item whose data runs past the end +/// stops it, with an error); "ok" is whether hid-rp's ReportMap accepts the +/// descriptor (it needs at least one Input field). +inline std::string parse_json(std::span descriptor) { + using detail::Json; + Json j; + j.begin_object(); + // the items, by the HID short / long item format (6.2.2.2, 6.2.2.3) + std::string item_error; + j.key("items").begin_array(); + size_t i = 0; + while (i < descriptor.size()) { + const uint8_t prefix = descriptor[i]; + size_t header = 1, data_size = 0; + unsigned type = (prefix >> 2) & 0x3, tag = prefix >> 4; + bool long_item = prefix == 0xFE; + if (long_item) { + if (i + 2 >= descriptor.size()) { + item_error = "a long item at byte " + std::to_string(i) + " is cut off"; + break; + } + data_size = descriptor[i + 1]; + tag = descriptor[i + 2]; + header = 3; + } else { + static constexpr size_t sizes[4] = {0, 1, 2, 4}; + data_size = sizes[prefix & 0x3]; + } + if (i + header + data_size > descriptor.size()) { + item_error = "the item at byte " + std::to_string(i) + " needs " + + std::to_string(header + data_size) + " bytes, " + + std::to_string(descriptor.size() - i) + " are left"; + break; + } + const auto data = descriptor.subspan(i + header, data_size); + uint32_t u = 0; + for (size_t b = 0; b < data.size() && b < 4; b++) + u |= static_cast(data[b]) << (8 * b); + int32_t s = static_cast(u); + if (!long_item && data_size > 0 && data_size < 4) { + const uint32_t sign = 1u << (8 * data_size - 1); + s = static_cast((u ^ sign) - sign); // sign-extend + } + std::string hex; + char buf[3]; + for (uint8_t b : descriptor.subspan(i, header + data_size)) { + std::snprintf(buf, sizeof(buf), "%02x", b); + hex += buf; + } + j.begin_object() + .field("offset", i) + .field("size", header + data_size) + .field("type", long_item ? "long" : detail::item_type_name(type)) + .field("tag", tag) + .field("name", long_item ? "(long item)" : detail::item_name(type, tag)) + .field("bytes", hex) + .field("value", u) + .field("signed", s) + .end_object(); + i += header + data_size; + } + j.end_array(); + const auto map = detail::parse_map(descriptor); + j.field("ok", map.has_value()); + const bool well_formed = hid_rp::ReportMap::well_formed(descriptor); + j.field("well_formed", well_formed); + if (!map) { + std::string why = item_error; + if (why.empty()) + why = well_formed ? "it has no Input field, or a report longer than " + + std::to_string(hid_rp::ReportMap::kMaxReportBytes) + " bytes" + : "it is not well formed (an unbalanced collection or Push / Pop, a data " + "item outside a collection, an unknown or long item, Report ID 0, or a " + "usage with no usage page)"; + j.field("error", "ReportMap::parse() refuses the descriptor: " + why); + } + if (map) { + j.field("uses_report_ids", map->uses_report_ids()); + j.key("fields").begin_array(); + for (const auto &f : map->fields()) + detail::write_field(j, f); + j.end_array(); + j.key("output_fields").begin_array(); + for (const auto &f : map->output_fields()) + detail::write_field(j, f); + j.end_array(); + j.key("reports").begin_array(); + for (uint8_t id : detail::report_ids(map->fields())) + j.begin_object().field("id", id).field("bytes", map->report_bytes(id)).end_object(); + j.end_array(); + j.key("output_reports").begin_array(); + for (uint8_t id : detail::report_ids(map->output_fields())) + j.begin_object().field("id", id).field("bytes", map->output_report_bytes(id)).end_object(); + j.end_array(); + const bool gamepad = hid_rp::GamepadDecoder::looks_like_gamepad(*map); + j.key("kind") + .begin_object() + .field("gamepad", gamepad) + .field("keyboard", hid_rp::KeyboardDecoder::looks_like_keyboard(*map)) + .field("mouse", hid_rp::MouseDecoder::looks_like_mouse(*map)) + .end_object(); + if (gamepad) { + hid_rp::GamepadDecoder decoder(*map); + j.field("gamepad_layout", hid_rp::GamepadDecoder::layout_name(decoder.quirks().layout)); + } + } + j.end_object(); + return j.str(); +} + +/// One input report (with its report ID byte first when the descriptor uses +/// IDs) decoded as each kind the descriptor looks like, as JSON: +/// +/// {"ok", "error", "report_id", "gamepad": {...GamepadReport..., "state": +/// {"buttons": [names pressed], "axes": {name: value}}}, "keyboard": +/// {"usages": [...]}, "mouse": {...}} +/// +/// `vid` / `pid` select the decoder's per-device quirks; `combine` is +/// GamepadDecoder::set_combine_controls() (the emulator-friendly default) - +/// off is what a pass-through such as gamepad_map sees. +inline std::string decode_json(std::span descriptor, std::span report, + uint16_t vid = 0, uint16_t pid = 0, bool combine = true) { + using detail::Json; + Json j; + j.begin_object(); + const auto map = detail::parse_map(descriptor); + if (!map) { + j.field("ok", false).field("error", "the descriptor does not parse").end_object(); + return j.str(); + } + if (report.empty()) { + j.field("ok", false).field("error", "no report bytes").end_object(); + return j.str(); + } + const uint8_t id = map->uses_report_ids() ? report[0] : 0; + const auto payload = map->uses_report_ids() ? report.subspan(1) : report; + const size_t expected = map->report_bytes(id); + bool any = false; + j.field("report_id", id).field("expected_bytes", expected).field("payload_bytes", payload.size()); + if (hid_rp::GamepadDecoder::looks_like_gamepad(*map)) { + hid_rp::GamepadDecoder decoder(*map); + decoder.apply_quirks(vid, pid); + decoder.set_combine_controls(combine); + hid_rp::GamepadReport r; + if (decoder.decode(id, payload, r)) { + any = true; + j.key("gamepad") + .begin_object() + .field("layout", hid_rp::GamepadDecoder::layout_name(decoder.quirks().layout)) + .field("lx", r.lx) + .field("ly", r.ly) + .field("rx", r.rx) + .field("ry", r.ry) + .field("lt", r.lt) + .field("rt", r.rt) + .field("hat", r.hat) + .field("raw_buttons", r.buttons); + const auto s = to_gamepad_state(r); + j.key("state").begin_object().key("buttons").begin_array(); + for (size_t b = 0; b < GamepadState::BUTTON_COUNT; b++) + if (s.pressed(static_cast(b))) + j.value(GamepadState::name(static_cast(b))); + j.end_array().key("axes").begin_object(); + for (size_t a = 0; a < GamepadState::AXIS_COUNT; a++) + j.field(GamepadState::name(static_cast(a)), + s.axis(static_cast(a))); + j.end_object().end_object().end_object(); + } + } + if (hid_rp::KeyboardDecoder::looks_like_keyboard(*map)) { + hid_rp::KeyboardDecoder decoder(*map); + hid_rp::KeyboardReport k; + if (decoder.decode(report, k)) { + any = true; + j.key("keyboard").begin_object().key("usages").begin_array(); + for (unsigned u = 0; u < 256; u++) + if (k.pressed(static_cast(u))) + j.value(u); + j.end_array().end_object(); + } + } + if (hid_rp::MouseDecoder::looks_like_mouse(*map)) { + hid_rp::MouseDecoder decoder(*map); + hid_rp::MouseReport m; + if (decoder.decode(report, m)) { + any = true; + j.key("mouse") + .begin_object() + .field("dx", m.dx) + .field("dy", m.dy) + .field("wheel", m.wheel) + .field("buttons", m.buttons) + .end_object(); + } + } + j.field("ok", any); + if (!any) + j.field("error", payload.size() < expected + ? "the report is shorter than report " + std::to_string(id) + " (" + + std::to_string(expected) + " bytes)" + : "no decoder took the report (not a gamepad, keyboard or mouse, or " + "a report ID the descriptor does not have)"); + j.end_object(); + return j.str(); +} + +/// A descriptor to start from. +struct Preset { + std::string name; + std::vector descriptor; + std::vector sample_report; ///< an input report to decode (empty: none) +}; + +/// hid-rp's generated descriptors and a real controller's, as JSON +/// [{"name", "descriptor": "hex", "report": "hex"}]. +inline std::vector presets() { + auto bytes = [](const auto &d) { return std::vector(d.begin(), d.end()); }; + auto from_hex = [](std::string_view hex) { + std::vector out; + for (size_t i = 0; i + 1 < hex.size(); i += 2) + out.push_back(static_cast(std::stoi(std::string(hex.substr(i, 2)), nullptr, 16))); + return out; + }; + std::vector p; + p.push_back({"Xbox gamepad (hid-rp's xbox_descriptor)", bytes(espp::xbox_descriptor()), {}}); + p.push_back({"DualSense over BLE (hid-rp's playstation_dualsense_ble_descriptor)", + bytes(espp::playstation_dualsense_ble_descriptor()), + {}}); + p.push_back( + {"SpaceMouse (hid-rp's spacemouse_descriptor)", bytes(espp::spacemouse_descriptor()), {}}); + // a real controller, as it reported itself over BLE (gamepad_map's host test): A pressed, + // hat up, right trigger full, left stick full right + p.push_back({"ShanWan BM-769 (BSP-D8), Android mode over BLE", + from_hex("050c0901a1018503751095011501269c0219012a9c028100c005010905a10185040901a1" + "000930093109320935150026ff00750895048102c00939150025073500463b01651475" + "0495018142750495018101050919012910150025017501951081020502150026ff0009" + "c409c5950275088102750895018101c0"), + from_hex("04ff808080000100ff0000")}); + return p; +} + +inline std::string presets_json() { + detail::Json j; + j.begin_array(); + for (const auto &p : presets()) { + std::string d, r; + char buf[3]; + for (uint8_t b : p.descriptor) { + std::snprintf(buf, sizeof(buf), "%02x", b); + d += buf; + } + for (uint8_t b : p.sample_report) { + std::snprintf(buf, sizeof(buf), "%02x", b); + r += buf; + } + j.begin_object().field("name", p.name).field("descriptor", d).field("report", r).end_object(); + } + j.end_array(); + return j.str(); +} + +} // namespace espp::hid_inspector diff --git a/components/hid-rp/inspector/hid_inspector_wasm.cpp b/components/hid-rp/inspector/hid_inspector_wasm.cpp new file mode 100644 index 0000000000..67e064b51d --- /dev/null +++ b/components/hid-rp/inspector/hid_inspector_wasm.cpp @@ -0,0 +1,46 @@ +// WebAssembly entry points of the HID descriptor inspector (hid_inspector.hpp) +// for components/hid-rp/web/hid_descriptor_inspector.html. Built by +// build_wasm.sh. Each function returns a NUL-terminated JSON string that stays +// valid until the next call. + +#include +#include +#include +#include + +#include "hid_inspector.hpp" + +namespace { +std::string result; // what the last call returned +const char *keep(std::string s) { + result = std::move(s); + return result.c_str(); +} +std::span view(const uint8_t *p, int n) { + return p && n > 0 ? std::span(p, static_cast(n)) + : std::span(); +} +} // namespace + +extern "C" { + +uint8_t *hri_alloc(int size) { return static_cast(std::malloc(size > 0 ? size : 1)); } +void hri_free(uint8_t *p) { std::free(p); } + +/// espp::hid_inspector::parse_json() of the descriptor. +const char *hri_parse(const uint8_t *descriptor, int size) { + return keep(espp::hid_inspector::parse_json(view(descriptor, size))); +} + +/// espp::hid_inspector::decode_json() of one report (combine: 0 / 1). +const char *hri_decode(const uint8_t *descriptor, int descriptor_size, const uint8_t *report, + int report_size, int vid, int pid, int combine) { + return keep(espp::hid_inspector::decode_json( + view(descriptor, descriptor_size), view(report, report_size), static_cast(vid), + static_cast(pid), combine != 0)); +} + +/// espp::hid_inspector::presets_json(). +const char *hri_presets() { return keep(espp::hid_inspector::presets_json()); } + +} // extern "C" diff --git a/components/hid-rp/test/CMakeLists.txt b/components/hid-rp/test/CMakeLists.txt index d5905fa3a5..65b260fa65 100644 --- a/components/hid-rp/test/CMakeLists.txt +++ b/components/hid-rp/test/CMakeLists.txt @@ -6,3 +6,8 @@ espp_add_component_test(hid_rp_gamepad_host_test DOCTEST SOURCES hid_rp_gamepad_ espp_add_component_test(hid_rp_report_map_host_test DOCTEST SOURCES hid_rp_report_map_host_test.cpp) espp_add_component_test(hid_rp_reports_host_test DOCTEST SOURCES hid_rp_reports_host_test.cpp) espp_add_component_test(hid_rp_rumble_host_test DOCTEST SOURCES hid_rp_rumble_host_test.cpp) +# The HID descriptor inspector's C++ side (../inspector), which the web app runs in WebAssembly. +espp_add_component_test(hid_inspector_host_test + DOCTEST + SOURCES hid_inspector_host_test.cpp + INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/../inspector) diff --git a/components/hid-rp/test/hid_inspector_host_test.cpp b/components/hid-rp/test/hid_inspector_host_test.cpp new file mode 100644 index 0000000000..a0b6d71017 --- /dev/null +++ b/components/hid-rp/test/hid_inspector_host_test.cpp @@ -0,0 +1,118 @@ +// The HID descriptor inspector's C++ side (inspector/hid_inspector.hpp): the +// item walk, the fields and classification from hid-rp's ReportMap, decoding a +// report into a GamepadState, malformed descriptors, and the presets. (The web +// app's own test, web/test/hid_inspector_ui_test.js, parses every JSON string.) + +#include +#include +#include +#include + +#include + +#include "hid_inspector.hpp" + +using espp::hid_inspector::decode_json; +using espp::hid_inspector::parse_json; +using espp::hid_inspector::presets; +using espp::hid_inspector::presets_json; + +namespace { +bool has(const std::string &s, const std::string &part) { + return s.find(part) != std::string::npos; +} + +const espp::hid_inspector::Preset &preset(const std::string &prefix) { + static const auto all = presets(); + static const espp::hid_inspector::Preset none{}; // returned (empty) when the check fails + const auto it = std::find_if(all.begin(), all.end(), + [&prefix](const auto &p) { return p.name.rfind(prefix, 0) == 0; }); + REQUIRE_MESSAGE(it != all.end(), "no preset " << prefix); + return it != all.end() ? *it : none; +} +} // namespace + +TEST_CASE("every preset parses") { + for (const auto &p : presets()) { + CAPTURE(p.name); + const auto j = parse_json(p.descriptor); + CHECK(has(j, "\"ok\":true")); + CHECK_FALSE(has(j, "\"error\"")); + } +} + +// hid-rp's Xbox descriptor is the Xbox Wireless controller's over BLE, which +// reports its triggers on the Simulation page: the decoder reads it with the +// Android layout, as it does for that controller. +TEST_CASE("the Xbox descriptor: items, fields, a gamepad with the Android layout") { + const auto j = parse_json(preset("Xbox").descriptor); + // the first item: Usage Page (Generic Desktop) + CHECK(has( + j, + R"({"offset":0,"size":2,"type":"global","tag":0,"name":"Usage Page","bytes":"0501","value":1,"signed":1})")); + CHECK(has(j, R"("name":"Collection")")); + CHECK(has(j, R"("name":"End Collection")")); + CHECK(has(j, R"("kind":{"gamepad":true,"keyboard":false,"mouse":false})")); + CHECK(has(j, R"("gamepad_layout":"Android")")); + CHECK(has(j, R"("output_fields":[{)")); // the rumble output report +} + +// What the decoders conclude, not what the device is: the SpaceMouse's axes +// and buttons make it look like a gamepad and a mouse to them. +TEST_CASE("the SpaceMouse, as the decoders classify it") { + const auto j = parse_json(preset("SpaceMouse").descriptor); + CHECK(has(j, "\"ok\":true")); + CHECK(has(j, R"("kind":{"gamepad":true,"keyboard":false,"mouse":true})")); +} + +TEST_CASE("a real controller's report, as a pass-through sees it") { + const auto p = preset("ShanWan"); // a copy: g++ -Wdangling-reference cannot see it is a static + const auto j = decode_json(p.descriptor, p.sample_report, 0, 0, /*combine=*/false); + CHECK(has(j, "\"ok\":true")); + CHECK(has(j, "\"report_id\":4")); + CHECK(has(j, R"("layout":"Android")")); + CHECK(has(j, R"("buttons":["south","up"])")); // A and the hat, nothing combined + CHECK(has(j, R"("left_x":32767)")); + CHECK(has(j, R"("right_trigger":32767)")); + // combined (the emulator default): the full trigger also presses R2 + CHECK(has(decode_json(p.descriptor, p.sample_report, 0, 0, true), R"("r2")")); +} + +TEST_CASE("signed item values are sign-extended") { + // Logical Minimum -127 (0x15 0x81), Logical Maximum 127 + const std::vector d{0x15, 0x81, 0x25, 0x7f}; + const auto j = parse_json(d); + CHECK(has(j, R"("name":"Logical Minimum","bytes":"1581","value":129,"signed":-127)")); + CHECK(has(j, "\"ok\":false")); // no Input field +} + +TEST_CASE("malformed descriptors are reported, not crashed on") { + // an item whose data runs past the end + const std::vector cut{0x05, 0x01, 0x26, 0xff}; + auto j = parse_json(cut); + CHECK(has(j, "\"ok\":false")); + CHECK(has(j, "needs 3 bytes, 2 are left")); + CHECK(has(j, "\"well_formed\":false")); + // an End Collection with no Collection + const std::vector unbalanced{0x05, 0x01, 0x09, 0x05, 0xc0}; + j = parse_json(unbalanced); + CHECK(has(j, "\"ok\":false")); + CHECK(has(j, "\"error\"")); + CHECK(has(parse_json({}), "\"ok\":false")); + // decoding against a descriptor that does not parse, or no report + CHECK(has(decode_json(unbalanced, std::vector{1, 2}), "does not parse")); + CHECK(has(decode_json(preset("Xbox").descriptor, {}), "no report bytes")); +} + +TEST_CASE("strings are escaped in the JSON") { + espp::hid_inspector::detail::Json j; + j.begin_object().field("s", std::string_view("a\"b\\c\n")).end_object(); + CHECK(j.str() == R"({"s":"a\"b\\c\u000a"})"); +} + +TEST_CASE("presets_json lists every preset") { + const auto j = presets_json(); + for (const auto &p : presets()) + CHECK(has(j, "\"name\":\"" + p.name + "\"")); + CHECK(has(j, R"("report":"04ff808080000100ff0000")")); +} diff --git a/components/hid-rp/web/hid_descriptor_inspector.html b/components/hid-rp/web/hid_descriptor_inspector.html new file mode 100644 index 0000000000..979fd30ff2 --- /dev/null +++ b/components/hid-rp/web/hid_descriptor_inspector.html @@ -0,0 +1,474 @@ + + + + + + espp HID Descriptor Inspector + + + + + + + +
+
+

espp HID Descriptor Inspector

+ +
+ + + +
+

Report descriptor

+
+ + + + +
+
+ +
+
+ Paste a descriptor (e.g. from usbhid-dump, Wireshark, or a device's log) or pick an example. +
+
+ +
+
+

Items

+
+ + + +
OffsetBytesItemValue
+
+
+
+

Fields

+

What ReportMap maps: each Input (and Output) field's place in its report, as the firmware reads it.

+
+ + + +
DirIDBitsUsageLogicalKind
+
+
+
+ +
+

Decode a report

+
+ + + + + +
+
+ + + +
+
+
+
+ + + + diff --git a/components/hid-rp/web/test/hid_inspector_ui_test.js b/components/hid-rp/web/test/hid_inspector_ui_test.js new file mode 100644 index 0000000000..129108253c --- /dev/null +++ b/components/hid-rp/web/test/hid_inspector_ui_test.js @@ -0,0 +1,103 @@ +#!/usr/bin/env node +// The HID Descriptor Inspector in headless Chrome, with its WebAssembly module +// (the firmware's hid-rp ReportMap and decoders, components/hid-rp/inspector): +// the presets parse, a real controller's descriptor is classified and its +// report decoded (pass-through and combined), hex with commas / 0x / comments +// is read, a truncated descriptor is refused with where it is cut, and every +// JSON string the module returns parses. +// +// Needs the built module (components/hid-rp/web/hid_inspector.js, from +// components/hid-rp/inspector/build_wasm.sh) and Google Chrome (or $CHROME); +// skipped without either unless REQUIRE_VIRTUAL_DEVICES=1. +"use strict"; +const assert = require("assert"); +const fs = require("fs"); +const path = require("path"); +const { openPage, findChrome } = require("../../../dispatcher/web/test/headless_page.js"); + +const web = path.join(__dirname, ".."); +const missing = [!fs.existsSync(path.join(web, "hid_inspector.js")) && "the inspector module (run components/hid-rp/inspector/build_wasm.sh)", + !findChrome() && "Google Chrome (set CHROME)"].filter(Boolean); +if (missing.length) { + if (process.env.REQUIRE_VIRTUAL_DEVICES === "1") { console.log("FAIL missing " + missing.join(", ")); process.exit(1); } + console.log("skip: missing " + missing.join(", ")); + process.exit(0); +} + +let passed = 0; +async function test(name, fn) { + try { await fn(); passed++; console.log("ok " + name); } + catch (e) { console.log("FAIL " + name + "\n " + (e && e.stack ? e.stack : e)); process.exitCode = 1; } +} +const pick = (page, prefix) => page.eval((p) => { + const sel = document.getElementById("preset"); + const opt = [...sel.options].find((o) => o.textContent.startsWith(p)); + if (!opt) throw new Error("no preset " + p); + sel.value = opt.value; + sel.dispatchEvent(new Event("change")); + return opt.textContent; +}, prefix); +const summary = (page) => page.text("#summary"); + +(async () => { + const page = await openPage("file://" + path.join(web, "hid_descriptor_inspector.html")); + try { + await test("the module loads and lists the presets", async () => { + await page.waitFor(() => document.body.dataset.ready === "hid-inspector", 10000, "the module"); + const n = await page.eval(() => document.getElementById("preset").options.length); + assert.ok(n >= 5, n + " options"); + assert.strictEqual(await page.eval(() => document.getElementById("missing").hidden), true); + }); + await test("every preset parses", async () => { + const names = await page.eval(() => [...document.getElementById("preset").options].slice(1).map((o) => o.textContent)); + for (const name of names) { + await pick(page, name); + assert.match(await summary(page), /^parses/, name); + } + }); + await test("a real controller: classified, its fields mapped, its report decoded", async () => { + await pick(page, "ShanWan"); + const s = await summary(page); + assert.match(s, /gamepad \(Android layout\)/); + assert.match(s, /#4: 10 B/); + assert.strictEqual(Number((await page.text("#itemCount")).replace(/\D/g, "")), 60); + assert.ok(await page.eval(() => document.querySelectorAll("#fields tr").length) >= 24); + // the preset's report: A pressed, hat up, right trigger full, left stick full right (pass-through) + await page.waitFor(() => document.getElementById("decodedButtons"), 3000, "the decoded state"); + assert.strictEqual(await page.text("#decodedButtons"), "southup"); + const axes = await page.eval(() => Object.fromEntries([...document.querySelectorAll("#decodedAxes tr")].map((tr) => [tr.children[0].textContent, Number(tr.children[1].textContent)]))); + assert.strictEqual(axes.left_x, 32767); + assert.strictEqual(axes.right_trigger, 32767); + // combined, the full trigger also presses R2 + await page.set("#combine", true); + await page.waitFor(() => /r2/.test(document.getElementById("decodedButtons").textContent), 3000, "R2 combined"); + await page.set("#combine", false); + }); + await test("the item list names usages and nests collections", async () => { + const rows = await page.eval(() => [...document.querySelectorAll("#items tr")].map((tr) => [...tr.children].map((td) => td.textContent))); + assert.ok(rows.some((r) => r[2] === "Usage" && r[3] === "Gamepad"), "a Usage named Gamepad"); + assert.ok(rows.some((r) => r[2] === "Usage Page" && r[3] === "Button"), "the Button page"); + assert.ok(rows.some((r) => r[2] === "Input" && /Data, Var, Abs/.test(r[3])), "an Input's flags"); + }); + await test("hex with commas, 0x and comments is read", async () => { + await page.set("#descriptor", "0x05, 0x01, // Generic Desktop\n0x09, 0x05, 0xa1, 0x01, # Gamepad\n0x75 0x01 0x95 0x01 0x15 0x00 0x25 0x01 0x05 0x09 0x09 0x01 0x81 0x02 0xc0"); + await page.click("#inspectBtn"); + await page.waitFor(() => /^parses/.test(document.getElementById("summary").textContent), 3000, "parses"); + assert.match(await summary(page), /21 bytes, 11 items/); + }); + await test("a truncated descriptor is refused, saying where", async () => { + await page.set("#descriptor", "05 01 26 ff"); + await page.click("#inspectBtn"); + await page.waitFor(() => /^refused/.test(document.getElementById("summary").textContent), 3000, "refused"); + assert.match(await summary(page), /the item at byte 2 needs 3 bytes, 2 are left/); + assert.strictEqual(await page.eval(() => document.getElementById("decodeBtn").disabled), true); + }); + await test("bad hex is reported, not inspected", async () => { + await page.set("#descriptor", "05 01 zz"); + await page.click("#inspectBtn"); + await page.waitFor(() => /not hex/.test(document.getElementById("summary").textContent), 3000, "the hex error"); + }); + await test("no script errors", async () => assert.deepStrictEqual(page.errors, [])); + } finally { await page.close(); } + console.log(passed + " passed"); +})().catch((e) => { console.log("FAIL " + (e && e.stack ? e.stack : e)); process.exit(1); }); diff --git a/doc/en/web_apps.rst b/doc/en/web_apps.rst index ecf62547b6..cf0b12e413 100644 --- a/doc/en/web_apps.rst +++ b/doc/en/web_apps.rst @@ -69,6 +69,12 @@ device may serve a protocol on any dispatcher module id. multizone ToF sensor's 4x4 or 8x8 zones, with a numeric grid, per-zone details, the motion indicator, every sensor setting and start / stop / initialize controls. +- **HID Descriptor Inspector** (``hid_descriptor_inspector.html``) — paste a + USB / BLE HID report descriptor and see it as the firmware does: every item, + the fields :doc:`hid-rp `'s ``ReportMap`` maps, the report sizes, + what the decoders take it for, and a report (typed in, or live from a device + over WebHID) decoded into a gamepad state. The parsing is espp's C++ compiled + to WebAssembly. - **Gamepad Map Console** (``gamepad_map_console.html``) — edit a device's :doc:`gamepad maps ` (the default map and one profile per controller type: button / axis rules, stick dead zones, presets, bind a