From d2793656584b59cd2c50a5914ad57ffbe48d34e4 Mon Sep 17 00:00:00 2001 From: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:53:17 +0800 Subject: [PATCH 1/4] Add optional tactile input to the OmniGlove plugin Signed-off-by: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> --- docs/source/_data/devices.yaml | 4 +- .../source/device/hand_tracking/omniglove.rst | 7 + docs/source/device/tactile/index.rst | 1 + docs/source/device/tactile/omniglove.rst | 128 ++++++ src/plugins/omniglove/CMakeLists.txt | 5 + src/plugins/omniglove/README.md | 57 +++ src/plugins/omniglove/app/main.cpp | 18 + src/plugins/omniglove/core/CMakeLists.txt | 6 +- .../inc/omniglove_plugin/omniglove_plugin.hpp | 9 + .../omniglove_plugin/omniglove_tactile.hpp | 87 ++++ .../omniglove/core/omniglove_plugin.cpp | 117 ++++- .../omniglove/core/omniglove_tactile.cpp | 381 ++++++++++++++++ src/plugins/omniglove/plugin.yaml | 8 +- .../omniglove/tools/prepare_tactile.py | 230 ++++++++++ tests/cpp/plugins/omniglove/CMakeLists.txt | 2 +- tests/cpp/plugins/omniglove/test_tactile.cpp | 430 ++++++++++++++++++ tests/python/CMakeLists.txt | 4 + tests/python/plugins/omniglove/CMakeLists.txt | 10 + tests/python/plugins/omniglove/conftest.py | 17 + tests/python/plugins/omniglove/pyproject.toml | 13 + tests/python/plugins/omniglove/test_export.py | 149 ++++++ 21 files changed, 1673 insertions(+), 10 deletions(-) create mode 100644 docs/source/device/tactile/omniglove.rst create mode 100644 src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp create mode 100644 src/plugins/omniglove/core/omniglove_tactile.cpp create mode 100644 src/plugins/omniglove/tools/prepare_tactile.py create mode 100644 tests/cpp/plugins/omniglove/test_tactile.cpp create mode 100644 tests/python/plugins/omniglove/CMakeLists.txt create mode 100644 tests/python/plugins/omniglove/conftest.py create mode 100644 tests/python/plugins/omniglove/pyproject.toml create mode 100644 tests/python/plugins/omniglove/test_export.py diff --git a/docs/source/_data/devices.yaml b/docs/source/_data/devices.yaml index 3b0f9d2ab1..82c75e98f9 100644 --- a/docs/source/_data/devices.yaml +++ b/docs/source/_data/devices.yaml @@ -279,7 +279,7 @@ devices: name: AGILINK OmniGlove url: https://www.agilink-ai.com/omni-gloveuzj.html group: peripheral - modes: High-fidelity finger tracking + modes: High-fidelity finger tracking, optional tactile input since: main company: name: AGILINK @@ -289,6 +289,8 @@ devices: setup: - label: AGILINK Omniglove docs url: https://www.agilink-ai.com/omni-glovernr/25.html + - label: OmniGlove tactile docs + doc: /device/tactile/omniglove - label: AGILINK Omniglove Plugin url: https://github.com/NVIDIA/IsaacCapture/tree/main/src/plugins/omniglove requirements: diff --git a/docs/source/device/hand_tracking/omniglove.rst b/docs/source/device/hand_tracking/omniglove.rst index 54e14cbd1b..9c9951a42c 100644 --- a/docs/source/device/hand_tracking/omniglove.rst +++ b/docs/source/device/hand_tracking/omniglove.rst @@ -159,6 +159,13 @@ incompatible SDK sample contracts stop the plugin with an error. Follow :doc:`/conformance/setup`, :doc:`/conformance/hand` and :doc:`/conformance/submit` for recording, review and submission. +Tactile input +------------- + +The same plugin can optionally publish scalar tactile forces and per-device +layout metadata. See :doc:`/device/tactile/omniglove` for configuration, +calibration requirements and the standard ``TactileTracker`` interface. + Troubleshooting --------------- diff --git a/docs/source/device/tactile/index.rst b/docs/source/device/tactile/index.rst index dfb386122a..a9ec0056e0 100644 --- a/docs/source/device/tactile/index.rst +++ b/docs/source/device/tactile/index.rst @@ -230,3 +230,4 @@ automatically publish the common force-and-layout contract described above. :titlesonly: oglo + omniglove diff --git a/docs/source/device/tactile/omniglove.rst b/docs/source/device/tactile/omniglove.rst new file mode 100644 index 0000000000..5eb52e6b51 --- /dev/null +++ b/docs/source/device/tactile/omniglove.rst @@ -0,0 +1,128 @@ +.. SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +.. SPDX-License-Identifier: Apache-2.0 + +AgiLink OmniGlove tactile input +=============================== + +OmniGlove provides scalar contact values from 746 taxels on each USB glove. +The :doc:`hand-tracking plugin ` can publish +these as standard tactile forces alongside its existing OpenXR hands, using +the same SDK session and device association. Tactile output is opt-in. + +Requirements and installation +----------------------------- + +Use the Linux OmniGlove SDK release and host USB rules described in the +hand-tracking guide. Build with ``BUILD_PLUGIN_OMNIGLOVE=ON``; CMake uses +the same pinned SDK release as the hand plugin. +The SDK release must provide POSE_DATA tactile regions, stream timestamps, +device tokens and the BONE read API; header/runtime ABI must agree. The +plugin and its layout exporter install under ``install/plugins/omniglove``. +Python export additionally requires Isaac Capture and NumPy. + +Live publication requires a compatible OpenXR runtime/headset and the original +plugin's optical or calibrated controller wrist setup. Offline layout export, +config validation and recording replay need no runtime. + +Prepare a device layout +----------------------- + +Prepare these inputs separately for each glove after calibrating it: + +- **Layout JSON.** Obtain the hand-specific tactile geometry and calibration + assets for your glove model from AgiLink, or use your own measured layout. + The SDK's `tactile layout tables`_ give the channel order for each hand. + Use that order in the external version-1 JSON, with 746 taxel bind poses, + 21 ordered OpenXR joint IDs and segment bind poses, ``joint_corrections``, + and four linear blend skinning indices and weights per taxel. Use the + OpenXR wrist frame. The fixture in + :code-file:`tests/python/plugins/omniglove/test_export.py` shows the JSON + fields and array shapes. Use real geometry and binding data for live operation. +- **Device identity and BONE.** Discover the calibrated glove using the + `SDK C API`_. Pass its complete ``omniglove_device_opaque_token()`` value + to ``--device-token``. Use ``omniglove_device_bone_read()`` on the same + device and save the complete 547-byte BONE v4 payload to a binary file. + Use your calibration revision as ``--calibration-id``. +- **Force scale.** Confirm the force per count for the current glove and SDK + with the device supplier or by applying a known reference force. If one + count represents one gram-force, use ``0.00980665`` N/LSB. + +.. _tactile layout tables: https://github.com/AgibotTech/agilink_omniglove_sdk/blob/a2f899cd45c51ae01c9bbca9b893e4afba41c0d7/docs/en/TACTILE_LAYOUT_V1.md +.. _SDK C API: https://github.com/AgibotTech/agilink_omniglove_sdk/blob/a2f899cd45c51ae01c9bbca9b893e4afba41c0d7/docs/en/PUBLIC_C_API.md + +.. code-block:: bash + + python src/plugins/omniglove/tools/prepare_tactile.py /path/to/layout.json \ + --output /path/to/left-config \ + --device-token 'EXACT_SDK_DISCOVERY_TOKEN' --calibration-id 'my-revision' \ + --newtons-per-lsb 0.00980665 --bone-file /path/to/raw-bone-v4.bin \ + --geometry-verified --axes-verified + +The exporter rebases the segment axes onto this HandTracker's conversion +without changing taxel poses. +WRIST bind must be identity; segment indices address the ordered joint list. +The exporter writes ``joint_convention: omniglove-openxr-v2``, including the +handed thumb roll in PR #1445. Configurations exported with the earlier v1 +convention must be regenerated from the original external layout. + +Verification flags are operator assertions. Preliminary estimated layouts +require ``--allow-estimated-layout``. Without a matching complete raw BONE v4 +snapshot, ``--allow-unverified-calibration`` must be explicit. With a snapshot, +startup and connection-generation changes compare its bytes against the +device. This checks bone geometry, not force calibration or the full IK/sensor +calibration. Stop and re-export after changing calibration. + +Run and consume +--------------- + +After starting the runtime and configuring the wrist source: + +.. code-block:: bash + + ./install/plugins/omniglove/omniglove_plugin \ + --check-tactile-left=/path/to/left-config/config.json + export OMNIGLOVE_TACTILE_LEFT_CONFIG=/path/to/left-config/config.json + ./install/plugins/omniglove/omniglove_plugin + +Set ``OMNIGLOVE_TACTILE_RIGHT_CONFIG`` for an independently prepared right glove. +The offline check validates files/schema; live startup checks device identity. +An unconfigured side publishes no tactile collection. + +``TactileTracker("/glove/omniglove_left")`` and +``TactileTracker("/glove/omniglove_right")`` read the respective ``tactile`` +tensors. Companion collections append ``/metadata`` and publish the standard +``metadata`` tensor. Forces have shape ``(746, 3)`` in N; by default +``Fz = -raw * newtons_per_lsb``, with unmeasured shear components set to zero. +Both hands use the same calibrated local sign convention. + +The existing tactile printer records through the official consumer and MCAP +writer, and replays without a runtime: + +.. code-block:: bash + + python -m isaaccapture_examples.tactile.printer \ + --collection-id /glove/omniglove_left --duration 30 --output /path/to/take.mcap + python -m isaaccapture_examples.tactile.printer --replay /path/to/take.mcap + +Timing and troubleshooting +-------------------------- + +Metadata is published before forces, periodically during streaming, and again +on recovery. Invalid or 200 ms stale samples withdraw the collections. The +producer rejects old/future samples and logs malformed frames, queue drops +and sequence gaps. Recovery rechecks identity and any BONE snapshot before +publication. Consumers must be tested for correct invalidation and rediscovery +with the target runtime. + +The common timestamp comes from SDK monotonic sample time. A valid SDK UTC +clock is preserved in raw nanoseconds; otherwise raw time falls back to common +time. These are not claims of physical multi-stream synchronization. BONE +verification runs on a separate worker from the hand update loop but may delay tactile recovery. + +A hand/config mismatch, wrong device token, invalid metadata, missing explicit +scale or changed BONE payload fails startup/publication. Rebuild the local +config from the correct device rather than relabeling its hand or token. +Estimated force axes and nominal geometry remain experimental. Verify taxel +order, geometry, outward normals and tangents on the current glove. Use a +known reference load to assess force accuracy. See +:code-file:`src/plugins/omniglove/README.md` for plugin configuration. diff --git a/src/plugins/omniglove/CMakeLists.txt b/src/plugins/omniglove/CMakeLists.txt index 90d154f334..006d195aa2 100644 --- a/src/plugins/omniglove/CMakeLists.txt +++ b/src/plugins/omniglove/CMakeLists.txt @@ -40,3 +40,8 @@ install(PROGRAMS install_udev_rules.sh DESTINATION plugins/omniglove COMPONENT omniglove ) + +install(FILES tools/prepare_tactile.py + DESTINATION plugins/omniglove/tools + COMPONENT omniglove +) diff --git a/src/plugins/omniglove/README.md b/src/plugins/omniglove/README.md index b23b26a674..37bcffe614 100644 --- a/src/plugins/omniglove/README.md +++ b/src/plugins/omniglove/README.md @@ -10,3 +10,60 @@ Isaac Capture. Installation, wrist calibration, running, licensing and troubleshooting: [AgiLink OmniGlove documentation](https://nvidia.github.io/IsaacCapture/main/device/hand_tracking/omniglove.html). + + +## Optional tactile input + +The plugin also publishes standard `TactileDataArray` forces and +`TactileMetadata` layouts for 746 taxels per configured hand. It copies the +SDK's POSE_DATA tactile regions using the same session as POST_DATA hand +tracking. Tactile processing and BONE checks run on a separate worker so USB +control waits do not stall hand updates. Errors propagate to the main loop. + +Prepare the SDK's personal hand calibration separately, then export an external +version-1 layout (ordered 21 joints, segment/taxel bind poses, joint corrections +and LBS weights) with `tools/prepare_tactile.py`. Vendor assets and personal +calibration files are not bundled. Use the factory-calibrated force values; +this plugin does not write calibration or firmware. + +```bash +python src/plugins/omniglove/tools/prepare_tactile.py /path/to/layout.json \ + --output /path/to/right-config \ + --device-token 'EXACT_SDK_DISCOVERY_TOKEN' --calibration-id 'my-revision' \ + --newtons-per-lsb 0.00980665 --bone-file /path/to/raw-bone-v4.bin \ + --allow-estimated-layout +./install/plugins/omniglove/omniglove_plugin \ + --check-tactile-right=/path/to/right-config/config.json +export OMNIGLOVE_TACTILE_RIGHT_CONFIG=/path/to/right-config/config.json +./install/plugins/omniglove/omniglove_plugin +``` + +The example scale is valid when one SDK count is confirmed to be one gram-force. +The default local force is `(0, 0, -raw * newtons_per_lsb)` N; shear is unmeasured. +Use `--geometry-verified --axes-verified` for a measured layout instead of the +estimated-layout flag. Without a complete raw BONE snapshot, explicit +`--allow-unverified-calibration` is required. BONE comparison checks bone +configuration, not all personal calibration parameters or factory force accuracy. +Re-export after calibration changes. + +The exporter requires Isaac Capture's Python schema and NumPy. It writes the +`omniglove-openxr-v2` joint convention, including PR #1445's thumb roll; old v1 +configurations must be regenerated. Export never overwrites an output directory. +The offline check above needs no USB device or OpenXR runtime. At live startup, +the plugin verifies hand, opaque device token and any BONE snapshot, repeating +identity/BONE checks on connection-generation changes. + +Set `OMNIGLOVE_TACTILE_LEFT_CONFIG` independently for the left glove. Unset +variables disable tactile input. Read `/glove/omniglove_right` or +`/glove/omniglove_left` with `TactileTracker`; the companion `/metadata` +collection carries the `metadata` tensor. Metadata precedes forces and refreshes +periodically. Invalid or 200 ms stale samples withdraw both collections; a valid +recovery recreates them. The device monitor includes configured tactile paths. + +Live use retains the hand plugin's runtime/headset and wrist-source requirements. +The SDK common timestamp is monotonic; a valid device UTC timestamp is preserved +as raw nanoseconds. Queue drops and source sequence gaps are logged. Runtime +consumer rediscovery after collection withdrawal must be qualified separately. +The hand CTS evidence does not qualify tactile measurements. + +Full usage: [OmniGlove tactile documentation](https://nvidia.github.io/IsaacCapture/main/device/tactile/omniglove.html). diff --git a/src/plugins/omniglove/app/main.cpp b/src/plugins/omniglove/app/main.cpp index f6ff0e25f4..b55ce161fa 100644 --- a/src/plugins/omniglove/app/main.cpp +++ b/src/plugins/omniglove/app/main.cpp @@ -42,6 +42,24 @@ try } } + bool checked = false; + for (int index = 1; index < argc; ++index) + { + const std::string argument = argv[index]; + for (bool is_left : { true, false }) + { + const std::string prefix = is_left ? "--check-tactile-left=" : "--check-tactile-right="; + if (argument.rfind(prefix, 0) == 0) + { + plugins::omniglove::TactileConfig::load(argument.substr(prefix.size()), is_left); + checked = true; + } + } + } + if (checked) + { + return 0; + } std::signal(SIGINT, signal_handler); std::signal(SIGTERM, signal_handler); diff --git a/src/plugins/omniglove/core/CMakeLists.txt b/src/plugins/omniglove/core/CMakeLists.txt index b9bef1b202..416ad04b77 100644 --- a/src/plugins/omniglove/core/CMakeLists.txt +++ b/src/plugins/omniglove/core/CMakeLists.txt @@ -4,6 +4,8 @@ add_library(omniglove_plugin_core STATIC omniglove_hand_conversion.cpp omniglove_plugin.cpp + omniglove_tactile.cpp + inc/omniglove_plugin/omniglove_tactile.hpp inc/omniglove_plugin/omniglove_hand_conversion.hpp inc/omniglove_plugin/omniglove_plugin.hpp ) @@ -15,8 +17,10 @@ target_include_directories(omniglove_plugin_core target_link_libraries(omniglove_plugin_core PRIVATE - OmnigloveSDK::api + yaml-cpp::yaml-cpp PUBLIC + OmnigloveSDK::api + pusherio::pusherio Teleop::plugin_utils deviceio::deviceio_session deviceio::deviceio_trackers diff --git a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp index a50c0f9cff..120a4c872d 100644 --- a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp +++ b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp @@ -4,6 +4,7 @@ #pragma once #include "omniglove_hand_conversion.hpp" +#include "omniglove_tactile.hpp" #include #include @@ -22,6 +23,7 @@ #include #include #include +#include struct omniglove_session; struct omniglove_stream_sample; @@ -64,11 +66,15 @@ class OmniglovePlugin { OmniglovePlugin* plugin; bool is_left; + TactileSource* tactile = nullptr; }; struct HandState { std::optional stream; + StreamContext tactile_context{}; + omniglove_device_t* device = nullptr; + std::unique_ptr tactile; std::unique_ptr injector; int64_t last_pushed_ns = 0; core::PluginDeviceState state = core::PluginDeviceState_DISCONNECTED; @@ -84,6 +90,7 @@ class OmniglovePlugin static void stream_callback(const omniglove_stream_sample* sample, void* user_data) noexcept; void start_device_streams(); + void pump_tactile(std::stop_token stop); void on_sample(const omniglove_stream_sample& sample, bool is_left); void pump_hand(HandState& hand, bool is_left, const CallbackState& input); @@ -102,6 +109,8 @@ class OmniglovePlugin std::exception_ptr m_callback_error; // Destroy the SDK first: its callbacks borrow the contexts, frames and mutex above. SdkSession m_sdk_session; + // Join the tactile worker before destroying the SDK and its borrowed devices. + std::jthread m_tactile_worker; }; } // namespace plugins::omniglove diff --git a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp new file mode 100644 index 0000000000..866202c762 --- /dev/null +++ b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace plugins::omniglove +{ + +inline constexpr size_t kTaxelCount = 746; + +struct TactileFrame +{ + std::array taxels{}; + int64_t sample_ns = 0; + int64_t raw_ns = 0; + uint64_t generation = 0; + uint64_t sequence = 0; + uint64_t source_gaps = 0; +}; + +// Copies borrowed region buffers in SDK wire order; never retain SDK pointers. +bool copy_tactile_sample(const omniglove_stream_sample_t& sample, bool is_left, TactileFrame& frame); +std::vector encode_tactile_forces(const TactileFrame& frame, float newtons_per_lsb, int normal_sign); +void validate_tactile_metadata(const std::vector& bytes); + +struct TactileConfig +{ + std::string device_token; + std::string calibration_id; + std::vector metadata; + std::vector bone; + float newtons_per_lsb = 0.0F; + int normal_sign = -1; + + static TactileConfig load(const std::string& path, bool is_left); +}; + +class TactileSource +{ +public: + TactileSource(TactileConfig config, bool is_left, const std::string& collection_id); + void check_device(omniglove_device_t* device) const; + void on_sample(const omniglove_stream_sample_t& sample); + void pump(const core::OpenXRSessionHandles& handles, omniglove_device_t* device, int64_t now_ns); + void stop(); + bool active() const noexcept + { + return m_active.load(std::memory_order_acquire); + } + +private: + static constexpr size_t kCapacity = 64; + std::atomic m_active{ false }; + TactileConfig m_config; + bool m_is_left; + std::string m_collection_id; + std::mutex m_mutex; + std::array m_frames{}; + size_t m_head = 0; + size_t m_size = 0; + bool m_invalidated = false; + uint64_t m_dropped = 0; + uint64_t m_invalid = 0; + uint64_t m_reported_invalid = 0; + uint64_t m_reported_dropped = 0; + uint64_t m_generation = 0; + uint64_t m_last_sequence = 0; + int64_t m_last_sample_ns = 0; + int64_t m_last_metadata_ns = 0; + bool m_have_generation = false; + std::unique_ptr m_data_pusher; + std::unique_ptr m_metadata_pusher; +}; + +} // namespace plugins::omniglove diff --git a/src/plugins/omniglove/core/omniglove_plugin.cpp b/src/plugins/omniglove/core/omniglove_plugin.cpp index 1807559f81..dfd1ece2db 100644 --- a/src/plugins/omniglove/core/omniglove_plugin.cpp +++ b/src/plugins/omniglove/core/omniglove_plugin.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -88,6 +89,15 @@ OmniglovePlugin::OmniglovePlugin(const std::string& plugin_root_id) wrist_config.right_aim_to_wrist = plugin_utils::pose_from_env("OMNIGLOVE_AIM_TO_WRIST_RIGHT"); } m_logger->info("wrist source {}", plugin_utils::to_string(wrist_config.mode)); + for (bool is_left : { true, false }) + { + const char* path = std::getenv(is_left ? "OMNIGLOVE_TACTILE_LEFT_CONFIG" : "OMNIGLOVE_TACTILE_RIGHT_CONFIG"); + if (path != nullptr && *path != '\0') + { + hand_state(is_left).tactile = std::make_unique( + TactileConfig::load(path, is_left), is_left, std::string("/glove/omniglove_") + hand_name(is_left)); + } + } m_sdk_session = create_sdk_session(m_logger); const auto wrist_requirements = plugin_utils::WristPoseSource::collect_requirements(wrist_config.mode); @@ -97,6 +107,15 @@ OmniglovePlugin::OmniglovePlugin(const std::string& plugin_root_id) const auto status_extensions = plugin_utils::PluginDeviceStatusPublisher::get_required_extensions(); extensions.insert(extensions.end(), status_extensions.begin(), status_extensions.end()); + const bool have_tactile = + std::any_of(m_hands.begin(), m_hands.end(), [](const auto& hand) { return hand.tactile != nullptr; }); + if (have_tactile) + { + const auto tactile_extensions = core::SchemaPusher::get_required_extensions(); + extensions.insert(extensions.end(), tactile_extensions.begin(), tactile_extensions.end()); + } + std::sort(extensions.begin(), extensions.end()); + extensions.erase(std::unique(extensions.begin(), extensions.end()), extensions.end()); m_session = std::make_unique("Omniglove", extensions); const auto handles = m_session->get_handles(); m_deviceio_session = core::DeviceIOSession::run(wrist_requirements.trackers, handles); @@ -109,9 +128,21 @@ OmniglovePlugin::OmniglovePlugin(const std::string& plugin_root_id) m_logger->info( "initialized with {} glove stream(s)", std::count_if(m_hands.begin(), m_hands.end(), [](const auto& hand) { return hand.stream.has_value(); })); + if (have_tactile) + { + m_tactile_worker = std::jthread([this](std::stop_token stop) { pump_tactile(stop); }); + } } -OmniglovePlugin::~OmniglovePlugin() = default; +OmniglovePlugin::~OmniglovePlugin() +{ + if (m_tactile_worker.joinable()) + { + m_tactile_worker.request_stop(); + m_tactile_worker.join(); + } + m_sdk_session.reset(); +} void OmniglovePlugin::start_device_streams() { @@ -140,6 +171,7 @@ void OmniglovePlugin::start_device_streams() // Own the callback context before starting the stream, including failure cleanup. hand_state.stream.emplace(StreamContext{ this, is_left }); + hand_state.device = device; omniglove_stream_config_t config{}; config.struct_size = sizeof(config); @@ -164,9 +196,29 @@ void OmniglovePlugin::start_device_streams() throw std::runtime_error(std::string("could not start ") + hand_name(is_left) + " POST_DATA stream: " + std::to_string(static_cast(start_error))); } + if (hand_state.tactile) + { + hand_state.tactile->check_device(device); + hand_state.tactile_context = { this, is_left, hand_state.tactile.get() }; + config.kind = OMNIGLOVE_STREAM_POSE_DATA; + config.pose_components = OMNIGLOVE_POSE_COMPONENT_TACTILE; + config.callback_user_data = &hand_state.tactile_context; + if (omniglove_device_stream_configure(device, &config) != OMNIGLOVE_STREAM_ERROR_NONE || + omniglove_device_stream_start(device, config.kind) != OMNIGLOVE_STREAM_ERROR_NONE) + { + throw std::runtime_error(std::string("could not start ") + hand_name(is_left) + " tactile stream"); + } + } m_logger->info("started {} glove at {} Hz", hand_name(is_left), omniglove_device_nominal_source_rate_hz(device)); } + for (const auto& hand : m_hands) + { + if (hand.tactile && !hand.stream) + { + throw std::runtime_error("configured tactile glove was not discovered"); + } + } if (std::none_of(m_hands.begin(), m_hands.end(), [](const auto& hand) { return hand.stream.has_value(); })) { throw std::runtime_error("no left or right Omniglove POST_DATA stream could be started"); @@ -175,14 +227,21 @@ void OmniglovePlugin::start_device_streams() void OmniglovePlugin::stream_callback(const omniglove_stream_sample_t* sample, void* user_data) noexcept { - if (sample == nullptr) + if (sample == nullptr || user_data == nullptr) { return; } auto* context = static_cast(user_data); try { - context->plugin->on_sample(*sample, context->is_left); + if (context->tactile) + { + context->tactile->on_sample(*sample); + } + else + { + context->plugin->on_sample(*sample, context->is_left); + } } catch (...) { @@ -301,6 +360,40 @@ void OmniglovePlugin::pump_hand(HandState& hand, bool is_left, const CallbackSta hand.reason = core::PluginDeviceReason_NONE; } +void OmniglovePlugin::pump_tactile(std::stop_token stop) +{ + // BONE reads can wait on USB; hand updates must keep running during recovery. + try + { + while (!stop.stop_requested()) + { + for (auto& hand : m_hands) + { + if (hand.tactile) + { + hand.tactile->pump(m_session->get_handles(), hand.device, core::os_monotonic_now_ns()); + } + } + std::this_thread::sleep_for(kSourceInterval); + } + } + catch (...) + { + std::lock_guard lock(m_frame_mutex); + if (!m_callback_error) + { + m_callback_error = std::current_exception(); + } + } + for (auto& hand : m_hands) + { + if (hand.tactile) + { + hand.tactile->stop(); + } + } +} + void OmniglovePlugin::update() { std::array inputs; @@ -321,9 +414,21 @@ void OmniglovePlugin::update() } const auto& left = hand_state(true); const auto& right = hand_state(false); - m_status_publisher->publish_if_changed( - { { "/hand/left", left.state, left.reason, {} }, { "/hand/right", right.state, right.reason, {} } }, - core::os_monotonic_now_ns()); + std::vector entries = { { "/hand/left", left.state, left.reason, {} }, + { "/hand/right", right.state, right.reason, {} } }; + for (bool is_left : { true, false }) + { + const auto& hand = hand_state(is_left); + if (hand.tactile) + { + const bool active = hand.tactile->active(); + entries.push_back({ std::string("/glove/omniglove_") + hand_name(is_left), + active ? core::PluginDeviceState_CONNECTED : core::PluginDeviceState_DEGRADED, + active ? core::PluginDeviceReason_NONE : core::PluginDeviceReason_NO_CURRENT_DATA, + {} }); + } + } + m_status_publisher->publish_if_changed(entries, core::os_monotonic_now_ns()); } } // namespace plugins::omniglove diff --git a/src/plugins/omniglove/core/omniglove_tactile.cpp b/src/plugins/omniglove/core/omniglove_tactile.cpp new file mode 100644 index 0000000000..0e1c612514 --- /dev/null +++ b/src/plugins/omniglove/core/omniglove_tactile.cpp @@ -0,0 +1,381 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/omniglove_plugin/omniglove_tactile.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace plugins::omniglove +{ +namespace +{ +constexpr int64_t kStaleNs = 200'000'000; +constexpr int64_t kMetadataPeriodNs = 1'000'000'000; + +std::vector read_bytes(const std::filesystem::path& path, size_t max_size) +{ + std::ifstream input(path, std::ios::binary | std::ios::ate); + if (!input || input.tellg() <= 0 || input.tellg() > static_cast(max_size)) + { + throw std::runtime_error("invalid or oversized tactile input: " + path.string()); + } + std::vector bytes(static_cast(input.tellg())); + input.seekg(0); + if (!input.read(reinterpret_cast(bytes.data()), static_cast(bytes.size()))) + { + throw std::runtime_error("cannot read tactile input: " + path.string()); + } + return bytes; +} + +void validate_scale(float scale, int sign) +{ + if (!std::isfinite(scale) || scale <= 0.0F || scale > std::numeric_limits::max() / 255.0F || + (sign != -1 && sign != 1)) + { + throw std::runtime_error("tactile scale must be finite and positive; normal_sign must be -1 or 1"); + } +} +} // namespace + +bool copy_tactile_sample(const omniglove_stream_sample_t& sample, bool is_left, TactileFrame& frame) +{ + if (sample.struct_size < sizeof(sample) || sample.kind != OMNIGLOVE_STREAM_POSE_DATA || + sample.hand != (is_left ? OMNIGLOVE_HAND_LEFT : OMNIGLOVE_HAND_RIGHT) || + sample.layout_version != OMNIGLOVE_STREAM_LAYOUT_VERSION || sample.sample_monotonic_ns == 0 || + sample.sample_monotonic_ns > static_cast(std::numeric_limits::max())) + { + return false; + } + const auto* pose = sample.data.posedata; + if (pose == nullptr || !pose->mapped || !(pose->components & OMNIGLOVE_POSE_COMPONENT_TACTILE)) + { + return false; + } + const auto& t = pose->tactile; + if (!t.mapped || t.count != kTaxelCount || t.thumb.middle.count || t.thumb.root.count || t.index.middle.count || + t.middle.middle.count || t.ring.middle.count || t.pinky.pad.count) + { + return false; + } + const std::array regions = { &t.thumb.tip, &t.thumb.pad, &t.index.tip, &t.index.pad, &t.index.root, + &t.middle.tip, &t.middle.pad, &t.middle.root, &t.ring.tip, &t.ring.pad, + &t.ring.root, &t.pinky.tip, &t.pinky.middle, &t.pinky.root, &t.palm_surface }; + constexpr std::array counts = { 38, 28, 38, 28, 28, 37, 28, 28, 37, 28, 28, 39, 28, 25, 308 }; + size_t offset = 0; + TactileFrame copy; + for (size_t i = 0; i < regions.size(); ++i) + { + if (regions[i]->count != counts[i] || regions[i]->data == nullptr) + { + return false; + } + std::copy_n(regions[i]->data, counts[i], copy.taxels.begin() + static_cast(offset)); + offset += counts[i]; + } + copy.sample_ns = static_cast(sample.sample_monotonic_ns); + copy.raw_ns = copy.sample_ns; + if (sample.flags & OMNIGLOVE_STREAM_SAMPLE_DEVICE_TIME_VALID) + { + constexpr auto limit = static_cast(std::numeric_limits::max()); + if (sample.device_time_us >= 1000 || sample.device_time_ms > (limit - 999'000) / 1'000'000) + { + return false; + } + copy.raw_ns = static_cast(sample.device_time_ms * 1'000'000 + sample.device_time_us * 1000ULL); + } + copy.generation = sample.connection_generation; + copy.sequence = sample.source_sequence; + copy.source_gaps = sample.gap_count; + frame = copy; + return true; +} + +std::vector encode_tactile_forces(const TactileFrame& frame, float newtons_per_lsb, int normal_sign) +{ + validate_scale(newtons_per_lsb, normal_sign); + std::vector forces; + forces.reserve(kTaxelCount); + for (auto raw : frame.taxels) + { + forces.emplace_back(0.0F, 0.0F, static_cast(raw) * newtons_per_lsb * static_cast(normal_sign)); + } + flatbuffers::FlatBufferBuilder builder; + const auto data = core::CreateTactileDataArrayDirect(builder, &forces); + builder.Finish(data); + return { builder.GetBufferPointer(), builder.GetBufferPointer() + builder.GetSize() }; +} + +void validate_tactile_metadata(const std::vector& bytes) +{ + if (bytes.empty() || bytes.size() > core::TRACKER_METADATA_MAX_SIZE) + { + throw std::runtime_error("invalid tactile metadata size"); + } + flatbuffers::Verifier verifier(bytes.data(), bytes.size()); + if (!core::VerifyTactileMetadataBuffer(verifier)) + { + throw std::runtime_error("invalid TactileMetadata FlatBuffer"); + } + const auto* metadata = core::GetTactileMetadata(bytes.data()); + core::verify_tactile_metadata(*metadata); + const auto* lbs = metadata->geometry_mapping_as_LBS(); + const auto* joints = metadata->segment_source_as_HandSkeletonRef()->joint_ids(); + constexpr std::array required = { core::HandJoint_WRIST, + core::HandJoint_THUMB_METACARPAL, + core::HandJoint_THUMB_PROXIMAL, + core::HandJoint_THUMB_DISTAL, + core::HandJoint_THUMB_TIP, + core::HandJoint_INDEX_PROXIMAL, + core::HandJoint_INDEX_INTERMEDIATE, + core::HandJoint_INDEX_DISTAL, + core::HandJoint_INDEX_TIP, + core::HandJoint_MIDDLE_PROXIMAL, + core::HandJoint_MIDDLE_INTERMEDIATE, + core::HandJoint_MIDDLE_DISTAL, + core::HandJoint_MIDDLE_TIP, + core::HandJoint_RING_PROXIMAL, + core::HandJoint_RING_INTERMEDIATE, + core::HandJoint_RING_DISTAL, + core::HandJoint_RING_TIP, + core::HandJoint_LITTLE_PROXIMAL, + core::HandJoint_LITTLE_INTERMEDIATE, + core::HandJoint_LITTLE_DISTAL, + core::HandJoint_LITTLE_TIP }; + if (lbs->taxel_bind_poses()->size() != kTaxelCount || joints->size() != required.size() || + !std::equal(required.begin(), required.end(), joints->begin())) + { + throw std::runtime_error("tactile layout must have 746 taxels and the ordered 21 OmniGlove joints"); + } + const auto* wrist = lbs->segment_bind_poses()->Get(0); + const auto& p = wrist->position(); + const auto& q = wrist->orientation(); + if (std::abs(p.x()) > 1e-6F || std::abs(p.y()) > 1e-6F || std::abs(p.z()) > 1e-6F || std::abs(q.x()) > 1e-6F || + std::abs(q.y()) > 1e-6F || std::abs(q.z()) > 1e-6F || std::abs(std::abs(q.w()) - 1.0F) > 1e-6F) + { + throw std::runtime_error("tactile WRIST bind pose must be identity"); + } +} + +TactileConfig TactileConfig::load(const std::string& path, bool is_left) +{ + const auto doc = YAML::LoadFile(path); + if (doc["version"].as() != 1 || doc["hand"].as() != (is_left ? "left" : "right") || + doc["joint_convention"].as() != "omniglove-openxr-v2") + { + throw std::runtime_error("unsupported tactile config version, hand or joint convention"); + } + TactileConfig result; + result.device_token = doc["device_token"].as(); + result.calibration_id = doc["calibration_id"].as(); + result.newtons_per_lsb = doc["newtons_per_lsb"].as(); + result.normal_sign = doc["normal_sign"].as(); + validate_scale(result.newtons_per_lsb, result.normal_sign); + if (result.device_token.empty() || result.calibration_id.empty()) + { + throw std::runtime_error("tactile device_token and calibration_id are required"); + } + const auto base = std::filesystem::path(path).parent_path(); + result.metadata = read_bytes(base / doc["metadata_file"].as(), core::TRACKER_METADATA_MAX_SIZE); + validate_tactile_metadata(result.metadata); + if (doc["bone_file"]) + { + result.bone = read_bytes(base / doc["bone_file"].as(), OMNIGLOVE_BONE_MAX_SIZE); + if (result.bone.size() != OMNIGLOVE_BONE_MAX_SIZE) + { + throw std::runtime_error("tactile bone_file must contain the complete raw BONE v4 payload"); + } + } + else if (!doc["allow_unverified_calibration"].as(false)) + { + throw std::runtime_error("tactile bone_file required unless allow_unverified_calibration is explicit"); + } + if ((!doc["geometry_verified"].as() || !doc["axes_verified"].as()) && + !doc["allow_estimated_layout"].as(false)) + { + throw std::runtime_error("estimated tactile layout requires allow_estimated_layout"); + } + return result; +} + +TactileSource::TactileSource(TactileConfig config, bool is_left, const std::string& collection_id) + : m_config(std::move(config)), m_is_left(is_left), m_collection_id(collection_id) +{ +} + +void TactileSource::check_device(omniglove_device_t* device) const +{ + const size_t size = omniglove_device_opaque_token(device, nullptr, 0); + if (size < 2 || size > 4096 || + omniglove_device_hand(device) != (m_is_left ? OMNIGLOVE_HAND_LEFT : OMNIGLOVE_HAND_RIGHT)) + { + throw std::runtime_error("tactile device identity unavailable or hand mismatch"); + } + std::vector token(size, '\0'); + if (omniglove_device_opaque_token(device, token.data(), size) != size || + std::string(token.data(), size - 1) != m_config.device_token) + { + throw std::runtime_error("tactile layout belongs to a different device"); + } + if (!m_config.bone.empty()) + { + std::array bone{}; + size_t length = 0; + omniglove_control_result_t result{}; + result.struct_size = sizeof(result); + const auto status = omniglove_device_bone_read(device, bone.data(), bone.size(), &length, 2000, &result); + if (status != OMNIGLOVE_CONTROL_COMPLETE || result.return_code || result.device_error_code || + length != m_config.bone.size() || !std::equal(bone.begin(), bone.end(), m_config.bone.begin())) + { + throw std::runtime_error("tactile BONE snapshot differs or could not be read; rebuild the layout"); + } + } +} + +void TactileSource::on_sample(const omniglove_stream_sample_t& sample) +{ + TactileFrame frame; + const bool valid = copy_tactile_sample(sample, m_is_left, frame); + std::lock_guard lock(m_mutex); + if (!valid) + { + ++m_invalid; + m_size = 0; + m_invalidated = true; + return; + } + if (m_size == kCapacity) + { + ++m_dropped; + return; + } + m_frames[(m_head + m_size) % kCapacity] = frame; + ++m_size; +} + +void TactileSource::stop() +{ + m_active.store(false, std::memory_order_release); + m_data_pusher.reset(); + m_metadata_pusher.reset(); + m_last_metadata_ns = 0; +} + +void TactileSource::pump(const core::OpenXRSessionHandles& handles, omniglove_device_t* device, int64_t now_ns) +{ + auto logger = isaaccapture::Logger::get("isaaccapture.plugins.omniglove.TactileSource"); + std::array frames; + size_t count; + bool invalidated; + uint64_t dropped; + uint64_t invalid; + { + std::lock_guard lock(m_mutex); + count = m_size; + invalidated = m_invalidated; + dropped = m_dropped; + invalid = m_invalid; + m_invalidated = false; + for (size_t i = 0; i < count; ++i) + { + frames[i] = m_frames[(m_head + i) % kCapacity]; + } + m_head = (m_head + count) % kCapacity; + m_size = 0; + } + if (invalid != m_reported_invalid) + { + logger->warn("{} rejected {} invalid tactile samples", m_collection_id, invalid - m_reported_invalid); + m_reported_invalid = invalid; + } + if (dropped != m_reported_dropped) + { + logger->warn("{} tactile queue dropped {} samples", m_collection_id, dropped - m_reported_dropped); + m_reported_dropped = dropped; + } + if (invalidated || (m_last_sample_ns && now_ns - m_last_sample_ns >= kStaleNs)) + { + if (m_data_pusher) + { + logger->info("{} inactive: tactile frame stale or invalid", m_collection_id); + } + stop(); + } + for (size_t i = 0; i < count; ++i) + { + const auto& frame = frames[i]; + if (frame.sample_ns > now_ns || now_ns - frame.sample_ns >= kStaleNs) + { + continue; + } + const bool new_generation = !m_have_generation || frame.generation != m_generation; + if (m_have_generation && frame.generation < m_generation) + { + continue; + } + if (new_generation) + { + stop(); + check_device(device); + now_ns = core::os_monotonic_now_ns(); + m_last_sample_ns = 0; + m_generation = frame.generation; + m_have_generation = true; + m_last_sequence = 0; + } + if (frame.sample_ns > now_ns || now_ns - frame.sample_ns >= kStaleNs || + (m_last_sample_ns && (frame.sample_ns <= m_last_sample_ns || frame.sequence <= m_last_sequence))) + { + continue; + } + if (!m_data_pusher) + { + m_metadata_pusher = std::make_unique( + handles, + core::SchemaPusherConfig{ .collection_id = core::tracker_metadata_collection_id(m_collection_id), + .max_flatbuffer_size = m_config.metadata.size(), + .tensor_identifier = std::string(core::TRACKER_METADATA_TENSOR_IDENTIFIER), + .localized_name = "OmniGlove tactile layout" }); + m_data_pusher = std::make_unique( + handles, core::SchemaPusherConfig{ .collection_id = m_collection_id, + .max_flatbuffer_size = 16384, + .tensor_identifier = "tactile", + .localized_name = "OmniGlove tactile forces" }); + logger->info( + "{} active: generation {}, calibration {}", m_collection_id, m_generation, m_config.calibration_id); + } + if (!m_last_metadata_ns || now_ns - m_last_metadata_ns >= kMetadataPeriodNs) + { + m_metadata_pusher->push_buffer(m_config.metadata.data(), m_config.metadata.size(), now_ns, now_ns); + m_last_metadata_ns = now_ns; + } + if (frame.source_gaps || (m_last_sample_ns && frame.sequence - m_last_sequence > 1)) + { + logger->warn("{} discontinuity: generation {}, sequence {}, SDK gaps {}", m_collection_id, frame.generation, + frame.sequence, frame.source_gaps); + } + const auto bytes = encode_tactile_forces(frame, m_config.newtons_per_lsb, m_config.normal_sign); + m_data_pusher->push_buffer(bytes.data(), bytes.size(), frame.sample_ns, frame.raw_ns); + m_last_sample_ns = frame.sample_ns; + m_last_sequence = frame.sequence; + m_active.store(true, std::memory_order_release); + } +} + +} // namespace plugins::omniglove diff --git a/src/plugins/omniglove/plugin.yaml b/src/plugins/omniglove/plugin.yaml index 7b0cc581e5..083d1a67e0 100644 --- a/src/plugins/omniglove/plugin.yaml +++ b/src/plugins/omniglove/plugin.yaml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 name: omniglove_plugin -description: "AgiLink OmniGlove hand tracking" +description: "AgiLink OmniGlove hand tracking and optional tactile input" command: "./omniglove_plugin" version: "1.0.0" devices: @@ -12,3 +12,9 @@ devices: - path: "/hand/right" type: "hand_tracker" description: "Right OmniGlove" + - path: "/glove/omniglove_left" + type: "tactile" + description: "Left OmniGlove tactile array (requires configuration)" + - path: "/glove/omniglove_right" + type: "tactile" + description: "Right OmniGlove tactile array (requires configuration)" diff --git a/src/plugins/omniglove/tools/prepare_tactile.py b/src/plugins/omniglove/tools/prepare_tactile.py new file mode 100644 index 0000000000..730db19c48 --- /dev/null +++ b/src/plugins/omniglove/tools/prepare_tactile.py @@ -0,0 +1,230 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Export an external OmniGlove layout for this plugin's OpenXR joint axes.""" + +import argparse +import json +from pathlib import Path + +import numpy as np +from isaaccapture.schema import ( + TRACKER_METADATA_MAX_SIZE, + HandJoint, + HandSkeletonRef, + LBS, + TactileMetadata, +) + +JOINT_IDS = [1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 14, 15, 17, 18, 19, 20, 22, 23, 24, 25] + + +def matrix(q: np.ndarray) -> np.ndarray: + if q.shape != (4,) or not np.isfinite(q).all() or abs(np.linalg.norm(q) - 1) > 1e-5: + raise ValueError("Expected unit XYZW quaternion") + x, y, z, w = q / np.linalg.norm(q) + return np.array( + [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + ) + + +def quaternion(r: np.ndarray) -> np.ndarray: + if ( + r.shape != (3, 3) + or not np.isfinite(r).all() + or not np.allclose(r.T @ r, np.eye(3), atol=1e-6) + or not np.isclose(np.linalg.det(r), 1) + ): + raise ValueError("Expected a proper rotation") + k = ( + np.array( + [ + [ + r[0, 0] - r[1, 1] - r[2, 2], + r[0, 1] + r[1, 0], + r[0, 2] + r[2, 0], + r[2, 1] - r[1, 2], + ], + [ + r[0, 1] + r[1, 0], + r[1, 1] - r[0, 0] - r[2, 2], + r[1, 2] + r[2, 1], + r[0, 2] - r[2, 0], + ], + [ + r[0, 2] + r[2, 0], + r[1, 2] + r[2, 1], + r[2, 2] - r[0, 0] - r[1, 1], + r[1, 0] - r[0, 1], + ], + [r[2, 1] - r[1, 2], r[0, 2] - r[2, 0], r[1, 0] - r[0, 1], np.trace(r)], + ] + ) + / 3 + ) + q = np.linalg.eigh(k)[1][:, -1] + return q if q[3] >= 0 else -q + + +def convert_layout(layout: dict) -> TactileMetadata: + """Keep taxel poses fixed; change segment axes to match convert_post_data().""" + if ( + layout.get("version") != 1 + or layout.get("hand") not in ("left", "right") + or layout.get("root_frame") != "OpenXR wrist" + or layout.get("joint_ids") != JOINT_IDS + ): + raise ValueError("Unsupported external layout") + segments = np.array(layout["segment_bind_poses"], dtype=float) + taxels = np.asarray(layout["taxel_bind_poses"], dtype=float) + corrections = np.asarray(layout["joint_corrections"], dtype=float) + indices = np.asarray(layout["indices"], dtype=float) + weights = np.asarray(layout["weights"], dtype=float) + if ( + segments.shape != (21, 7) + or taxels.shape != (746, 7) + or corrections.shape != (21, 3, 3) + or indices.shape != (746, 4) + or weights.shape != (746, 4) + ): + raise ValueError("Invalid layout dimensions") + for values in (segments, taxels, corrections, indices, weights): + if not np.isfinite(values).all(): + raise ValueError("Layout contains non-finite values") + if ( + (indices < 0).any() + or (indices >= 21).any() + or not np.equal(indices, np.floor(indices)).all() + or (weights < 0).any() + or not np.allclose(weights.sum(axis=1), 1, atol=1e-5, rtol=0) + ): + raise ValueError("Invalid LBS indices or weights") + root = np.eye(3) if layout["hand"] == "left" else np.diag([-1.0, -1.0, 1.0]) + for i, (pose, correction) in enumerate(zip(segments, corrections, strict=True)): + quaternion(correction) + # Match the HandTracker basis, finger half-turn and handed thumb roll. + flip = np.eye(3) if i == 0 else np.diag([-1.0, 1.0, -1.0]) + roll = np.eye(3) + if 1 <= i <= 4: + angle = -np.pi / 2 if layout["hand"] == "left" else np.pi / 2 + roll = np.array( + [ + [np.cos(angle), -np.sin(angle), 0], + [np.sin(angle), np.cos(angle), 0], + [0, 0, 1], + ] + ) + pose[3:] = quaternion(matrix(pose[3:]) @ correction.T @ root.T @ flip @ roll) + for pose in taxels: + matrix(pose[3:]) + if not np.allclose(segments[0, :3], 0, atol=1e-6) or not np.allclose( + matrix(segments[0, 3:]), np.eye(3), atol=1e-6 + ): + raise ValueError("WRIST bind must be identity") + metadata = TactileMetadata( + LBS( + segments.astype(np.float32), + taxels.astype(np.float32), + indices.astype(np.uint32), + weights.astype(np.float32), + ), + HandSkeletonRef([HandJoint(j) for j in JOINT_IDS]), + ) + if len(metadata.to_bytes()) > TRACKER_METADATA_MAX_SIZE: + raise ValueError("Metadata exceeds runtime capacity") + return metadata + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "layout", + type=Path, + help="External version-1 layout JSON; vendor assets are not bundled", + ) + parser.add_argument( + "--output", type=Path, required=True, help="New local configuration directory" + ) + parser.add_argument("--device-token", required=True) + parser.add_argument( + "--calibration-id", required=True, help="Operator's calibration revision label" + ) + parser.add_argument( + "--newtons-per-lsb", + type=float, + required=True, + help="Explicit physical scale; no implicit g/gf assumption", + ) + parser.add_argument("--normal-sign", type=int, choices=(-1, 1), default=-1) + parser.add_argument( + "--bone-file", + type=Path, + help="Matching complete raw SDK BONE v4 snapshot (547 bytes)", + ) + parser.add_argument( + "--geometry-verified", + action="store_true", + help="Operator confirms geometry against the current glove", + ) + parser.add_argument( + "--axes-verified", + action="store_true", + help="Operator confirms outward normals and tangents", + ) + parser.add_argument("--allow-estimated-layout", action="store_true") + parser.add_argument("--allow-unverified-calibration", action="store_true") + args = parser.parse_args() + if ( + not args.device_token + or not args.calibration_id + or not np.isfinite(args.newtons_per_lsb) + or args.newtons_per_lsb <= 0 + or args.newtons_per_lsb > np.finfo(np.float32).max / 255 + ): + parser.error( + "nonempty identity/calibration and finite positive float32 force scale required" + ) + if ( + not (args.geometry_verified and args.axes_verified) + and not args.allow_estimated_layout + ): + parser.error("unverified geometry/axes requires --allow-estimated-layout") + if args.bone_file is None and not args.allow_unverified_calibration: + parser.error("--bone-file or explicit --allow-unverified-calibration required") + bone = None if args.bone_file is None else args.bone_file.read_bytes() + if bone is not None and len(bone) != 547: + parser.error( + "--bone-file must contain the complete 547-byte raw BONE v4 payload" + ) + layout = json.loads(args.layout.read_text()) + metadata = convert_layout(layout).to_bytes() + config = { + "version": 1, + "hand": layout["hand"], + "joint_convention": "omniglove-openxr-v2", + "device_token": args.device_token, + "calibration_id": args.calibration_id, + "metadata_file": "metadata.bin", + "newtons_per_lsb": args.newtons_per_lsb, + "normal_sign": args.normal_sign, + "geometry_verified": args.geometry_verified, + "axes_verified": args.axes_verified, + "allow_estimated_layout": args.allow_estimated_layout, + "allow_unverified_calibration": args.allow_unverified_calibration, + } + if bone is not None: + config["bone_file"] = "bone.bin" + args.output.mkdir(parents=True, exist_ok=False) + (args.output / "metadata.bin").write_bytes(metadata) + if bone is not None: + (args.output / "bone.bin").write_bytes(bone) + (args.output / "config.json").write_text(json.dumps(config, indent=2) + "\n") + print(args.output / "config.json") + + +if __name__ == "__main__": + main() diff --git a/tests/cpp/plugins/omniglove/CMakeLists.txt b/tests/cpp/plugins/omniglove/CMakeLists.txt index f9fbf6a12e..744fb8eed0 100644 --- a/tests/cpp/plugins/omniglove/CMakeLists.txt +++ b/tests/cpp/plugins/omniglove/CMakeLists.txt @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. # SPDX-License-Identifier: Apache-2.0 -add_executable(omniglove_plugin_tests test_hand_conversion.cpp) +add_executable(omniglove_plugin_tests test_hand_conversion.cpp test_tactile.cpp) target_link_libraries(omniglove_plugin_tests PRIVATE Catch2::Catch2WithMain isaac::omniglove_plugin OmnigloveSDK::api ) diff --git a/tests/cpp/plugins/omniglove/test_tactile.cpp b/tests/cpp/plugins/omniglove/test_tactile.cpp new file mode 100644 index 0000000000..179479f827 --- /dev/null +++ b/tests/cpp/plugins/omniglove/test_tactile.cpp @@ -0,0 +1,430 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace plugins::omniglove; + +namespace +{ +struct Sample +{ + std::array raw{}; + omniglove_pose_data_t pose{}; + omniglove_stream_sample_t sample{}; + Sample(bool left = true) + { + pose.mapped = 1; + pose.components = OMNIGLOVE_POSE_COMPONENT_TACTILE; + auto& t = pose.tactile; + t.mapped = 1; + t.count = kTaxelCount; + const std::array regions = { &t.thumb.tip, &t.thumb.pad, &t.index.tip, &t.index.pad, &t.index.root, + &t.middle.tip, &t.middle.pad, &t.middle.root, &t.ring.tip, &t.ring.pad, + &t.ring.root, &t.pinky.tip, &t.pinky.middle, &t.pinky.root, &t.palm_surface }; + constexpr std::array counts = { 38, 28, 38, 28, 28, 37, 28, 28, 37, 28, 28, 39, 28, 25, 308 }; + size_t offset = 0; + for (size_t i = 0; i < regions.size(); ++i) + { + regions[i]->count = counts[i]; + regions[i]->data = raw.data() + offset; + offset += counts[i]; + } + for (size_t i = 0; i < raw.size(); ++i) + raw[i] = static_cast(i % 256); + sample.struct_size = sizeof(sample); + sample.kind = OMNIGLOVE_STREAM_POSE_DATA; + sample.hand = left ? OMNIGLOVE_HAND_LEFT : OMNIGLOVE_HAND_RIGHT; + sample.layout_version = OMNIGLOVE_STREAM_LAYOUT_VERSION; + sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns() - 1'000'000); + sample.source_sequence = 1; + sample.connection_generation = 1; + sample.data.posedata = &pose; + } +}; + +std::vector layout(bool bad_wrist = false) +{ + core::HandSkeletonRefT hand; + for (int id : { 1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 14, 15, 17, 18, 19, 20, 22, 23, 24, 25 }) + hand.joint_ids.push_back(static_cast(id)); + core::LBST lbs; + const core::Pose identity(core::Point(0, 0, 0), core::Quaternion(0, 0, 0, 1)); + lbs.segment_bind_poses.assign(21, identity); + if (bad_wrist) + lbs.segment_bind_poses[0] = core::Pose(core::Point(1, 0, 0), core::Quaternion(0, 0, 0, 1)); + lbs.taxel_bind_poses.assign(kTaxelCount, identity); + const std::array indices = { 0, 0, 0, 0 }; + const std::array weights = { 1, 0, 0, 0 }; + for (size_t i = 0; i < kTaxelCount; ++i) + { + lbs.taxel_segment_indices.emplace_back(flatbuffers::span(indices.data(), 4)); + lbs.taxel_segment_weights.emplace_back(flatbuffers::span(weights.data(), 4)); + } + core::TactileMetadataT metadata; + metadata.geometry_mapping.Set(std::move(lbs)); + metadata.segment_source.Set(std::move(hand)); + flatbuffers::FlatBufferBuilder builder; + builder.Finish(core::TactileMetadata::Pack(builder, &metadata)); + return { builder.GetBufferPointer(), builder.GetBufferPointer() + builder.GetSize() }; +} + +TactileConfig config() +{ + TactileConfig result; + result.device_token = "test-token"; + result.calibration_id = "test-calibration"; + result.metadata = layout(); + result.newtons_per_lsb = 0.01F; + return result; +} + +struct Push +{ + std::string collection; + std::vector bytes; + int64_t time; + uint64_t raw; +}; +std::map collections; +std::vector pushed; +uintptr_t next_handle = 10; +std::string device_token = "test-token"; +bool bone_matches = true; +size_t bone_reads = 0; + +XrResult XRAPI_PTR create_collection(XrSession, + const XrPushTensorCollectionCreateInfoNV* info, + XrPushTensorCollectionCreateResultNV*, + XrPushTensorCollectionNV* output) +{ + *output = reinterpret_cast(++next_handle); + collections[*output] = info->data.identifier; + return XR_SUCCESS; +} +XrResult XRAPI_PTR push(XrPushTensorCollectionNV handle, const XrPushTensorCollectionDataNV* data) +{ + const auto* bytes = static_cast(data->buffer); + pushed.push_back( + { collections.at(handle), { bytes, bytes + data->bufferSize }, data->timestamp, data->rawDeviceTimestamp }); + return XR_SUCCESS; +} +XrResult XRAPI_PTR destroy_collection(XrPushTensorCollectionNV handle) +{ + collections.erase(handle); + return XR_SUCCESS; +} +XrResult XRAPI_PTR to_time(XrInstance, const timespec* ts, XrTime* time) +{ + *time = ts->tv_sec * 1'000'000'000LL + ts->tv_nsec; + return XR_SUCCESS; +} +XrResult XRAPI_PTR from_time(XrInstance, XrTime time, timespec* ts) +{ + ts->tv_sec = time / 1'000'000'000; + ts->tv_nsec = time % 1'000'000'000; + return XR_SUCCESS; +} +XrResult XRAPI_PTR get_proc(XrInstance, const char* name, PFN_xrVoidFunction* out) +{ + const std::map funcs = { + { "xrCreatePushTensorCollectionNV", reinterpret_cast(create_collection) }, + { "xrPushTensorCollectionDataNV", reinterpret_cast(push) }, + { "xrDestroyPushTensorCollectionNV", reinterpret_cast(destroy_collection) }, + { "xrConvertTimespecTimeToTimeKHR", reinterpret_cast(to_time) }, + { "xrConvertTimeToTimespecTimeKHR", reinterpret_cast(from_time) } + }; + const auto it = funcs.find(name); + if (it == funcs.end()) + return XR_ERROR_FUNCTION_UNSUPPORTED; + *out = it->second; + return XR_SUCCESS; +} +core::OpenXRSessionHandles handles() +{ + core::OpenXRSessionHandles result{}; + result.instance = reinterpret_cast(1); + result.session = reinterpret_cast(2); + result.xrGetInstanceProcAddr = get_proc; + return result; +} +omniglove_device_t* device() +{ + return reinterpret_cast(1); +} +} // namespace + +// Executable-local SDK doubles: no USB access in these contract tests. +extern "C" size_t OMNIGLOVE_CALL omniglove_device_opaque_token(const omniglove_device_t*, char* out, size_t size) +{ + if (out && size) + { + std::strncpy(out, device_token.c_str(), size); + out[size - 1] = '\0'; + } + return device_token.size() + 1; +} +extern "C" omniglove_hand_t OMNIGLOVE_CALL omniglove_device_hand(const omniglove_device_t*) +{ + return OMNIGLOVE_HAND_LEFT; +} +extern "C" omniglove_control_status_t OMNIGLOVE_CALL omniglove_device_bone_read( + omniglove_device_t*, uint8_t* out, size_t, size_t* size, uint32_t, omniglove_control_result_t*) +{ + ++bone_reads; + std::fill_n(out, OMNIGLOVE_BONE_MAX_SIZE, bone_matches ? 7 : 8); + *size = OMNIGLOVE_BONE_MAX_SIZE; + return OMNIGLOVE_CONTROL_COMPLETE; +} + +TEST_CASE("746 borrowed taxels preserve order and both hand signs", "[unit][omniglove]") +{ + for (bool left : { true, false }) + { + Sample s(left); + TactileFrame frame; + REQUIRE(copy_tactile_sample(s.sample, left, frame)); + CHECK(frame.taxels == s.raw); + s.raw.fill(0); + CHECK(frame.taxels[255] == 255); + const auto bytes = encode_tactile_forces(frame, 0.01F, -1); + flatbuffers::Verifier verifier(bytes.data(), bytes.size()); + REQUIRE(verifier.VerifyBuffer(nullptr)); + const auto* data = flatbuffers::GetRoot(bytes.data()); + REQUIRE(data->taxel_forces()->size() == 746); + CHECK(data->taxel_forces()->Get(255)->x() == 0); + CHECK(data->taxel_forces()->Get(255)->y() == 0); + CHECK(data->taxel_forces()->Get(255)->z() == -2.55F); + } +} +TEST_CASE("malformed tactile samples and invalid clocks are rejected", "[unit][omniglove]") +{ + Sample s; + TactileFrame frame; + SECTION("wrong union member") + { + s.sample.kind = OMNIGLOVE_STREAM_POST_DATA; + s.sample.data.postdata = reinterpret_cast(1); + } + SECTION("null payload") + { + s.sample.data.posedata = nullptr; + } + SECTION("hand") + { + s.sample.hand = OMNIGLOVE_HAND_RIGHT; + } + SECTION("truncated header") + { + s.sample.struct_size = 0; + } + SECTION("layout") + { + s.sample.layout_version = 4; + } + SECTION("missing component") + { + s.pose.components = 0; + } + SECTION("wrong region") + { + s.pose.tactile.pinky.middle.count = 0; + } + SECTION("null region") + { + s.pose.tactile.palm_surface.data = nullptr; + } + SECTION("unexpected region") + { + s.pose.tactile.pinky.pad.count = 28; + } + SECTION("unmapped") + { + s.pose.tactile.mapped = 0; + } + SECTION("zero clock") + { + s.sample.sample_monotonic_ns = 0; + } + SECTION("raw overflow") + { + s.sample.flags = OMNIGLOVE_STREAM_SAMPLE_DEVICE_TIME_VALID; + s.sample.device_time_ms = UINT64_MAX; + } + SECTION("raw remainder") + { + s.sample.flags = OMNIGLOVE_STREAM_SAMPLE_DEVICE_TIME_VALID; + s.sample.device_time_us = 1000; + } + CHECK_FALSE(copy_tactile_sample(s.sample, true, frame)); + CHECK_THROWS(encode_tactile_forces(frame, 0, -1)); + CHECK_THROWS(encode_tactile_forces(frame, std::numeric_limits::infinity(), -1)); + CHECK_THROWS(encode_tactile_forces(frame, 1, 0)); +} +TEST_CASE("metadata checks wire validity, exact joints and WRIST root", "[unit][omniglove]") +{ + CHECK_NOTHROW(validate_tactile_metadata(layout())); + CHECK_THROWS(validate_tactile_metadata(layout(true))); + CHECK_THROWS(validate_tactile_metadata({ 1, 2, 3 })); +} +TEST_CASE("publisher announces metadata, retains SDK times and expires on silence", "[unit][omniglove]") +{ + pushed.clear(); + collections.clear(); + device_token = "test-token"; + TactileSource source(config(), true, "/test/left"); + Sample s; + s.sample.flags = OMNIGLOVE_STREAM_SAMPLE_DEVICE_TIME_VALID; + s.sample.device_time_ms = 1'700'000'000'000; + s.sample.device_time_us = 123; + source.on_sample(s.sample); + source.pump(handles(), device(), core::os_monotonic_now_ns()); + REQUIRE(source.active()); + REQUIRE(pushed.size() == 2); + CHECK(pushed[0].collection == "/test/left/metadata"); + CHECK(pushed[1].time == static_cast(s.sample.sample_monotonic_ns)); + CHECK(pushed[1].raw == 1'700'000'000'000'123'000ULL); + source.on_sample(s.sample); + source.pump(handles(), device(), core::os_monotonic_now_ns()); + CHECK(pushed.size() == 2); + source.pump(handles(), device(), static_cast(s.sample.sample_monotonic_ns) + 200'000'000); + CHECK(collections.empty()); + CHECK_FALSE(source.active()); + ++s.sample.source_sequence; + s.sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + source.on_sample(s.sample); + source.pump(handles(), device(), core::os_monotonic_now_ns()); + REQUIRE(pushed.size() == 4); + CHECK(pushed[2].collection == "/test/left/metadata"); +} +TEST_CASE("invalid samples withdraw collections and reconnect checks BONE", "[unit][omniglove]") +{ + pushed.clear(); + collections.clear(); + device_token = "test-token"; + bone_matches = true; + bone_reads = 0; + auto cfg = config(); + cfg.bone.assign(OMNIGLOVE_BONE_MAX_SIZE, 7); + TactileSource source(std::move(cfg), true, "/test/left"); + Sample s; + source.on_sample(s.sample); + source.pump(handles(), device(), core::os_monotonic_now_ns()); + REQUIRE(source.active()); + REQUIRE(pushed.size() == 2); + CHECK(bone_reads == 1); + s.pose.mapped = 0; + source.on_sample(s.sample); + source.pump(handles(), device(), core::os_monotonic_now_ns()); + CHECK(collections.empty()); + CHECK_FALSE(source.active()); + s.pose.mapped = 1; + ++s.sample.connection_generation; + s.sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + bone_matches = false; + source.on_sample(s.sample); + CHECK_THROWS(source.pump(handles(), device(), core::os_monotonic_now_ns())); + CHECK(bone_reads == 2); + CHECK(pushed.size() == 2); + device_token = "other-device"; + CHECK_THROWS(source.check_device(device())); + device_token = "test-token"; +} +TEST_CASE("bounded queues, future frames, metadata refresh and dual collection isolation", "[unit][omniglove]") +{ + pushed.clear(); + collections.clear(); + device_token = "test-token"; + TactileSource first(config(), true, "/test/left"); + Sample s; + for (uint64_t i = 0; i < 70; ++i) + { + s.sample.source_sequence = i + 1; + ++s.sample.sample_monotonic_ns; + first.on_sample(s.sample); + } + first.pump(handles(), device(), core::os_monotonic_now_ns()); + REQUIRE(pushed.size() == 65); + const auto now = core::os_monotonic_now_ns(); + s.sample.source_sequence = 100; + s.sample.sample_monotonic_ns = static_cast(now + 1'000'000'000); + first.on_sample(s.sample); + first.pump(handles(), device(), now); + CHECK(pushed.size() == 65); + // Refresh metadata without withdrawing either collection during steady input. + for (uint64_t i = 1; i <= 12; ++i) + { + s.sample.source_sequence = 100 + i; + s.sample.sample_monotonic_ns = static_cast(now) + i * 100'000'000; + first.on_sample(s.sample); + first.pump(handles(), device(), static_cast(s.sample.sample_monotonic_ns)); + } + REQUIRE(pushed.size() == 78); + CHECK(std::count_if(pushed.begin(), pushed.end(), + [](const Push& entry) { return entry.collection == "/test/left/metadata"; }) == 2); + TactileSource second(config(), true, "/test/other"); + s.sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + second.on_sample(s.sample); + second.pump(handles(), device(), core::os_monotonic_now_ns()); + REQUIRE(collections.size() == 4); + first.stop(); + REQUIRE(collections.size() == 2); + for (const auto& entry : collections) + CHECK(entry.second.starts_with("/test/other")); +} + +TEST_CASE("config rejects wrong hands, missing calibration policy and invalid metadata", "[unit][omniglove]") +{ + const auto directory = + std::filesystem::temp_directory_path() / ("omniglove-config-" + std::to_string(core::os_monotonic_now_ns())); + std::filesystem::create_directory(directory); + struct Cleanup + { + std::filesystem::path path; + ~Cleanup() + { + std::filesystem::remove_all(path); + } + } cleanup{ directory }; + const auto bytes = layout(); + std::ofstream binary(directory / "metadata.bin", std::ios::binary); + binary.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + binary.close(); + const auto path = directory / "config.yaml"; + const std::string base = + "version: 1\nhand: left\njoint_convention: omniglove-openxr-v2\n" + "device_token: test-token\ncalibration_id: test-revision\nmetadata_file: metadata.bin\n" + "newtons_per_lsb: 0.01\nnormal_sign: -1\ngeometry_verified: false\naxes_verified: false\n"; + const auto write = [&](const std::string& suffix) { std::ofstream(path) << base << suffix; }; + write(""); + CHECK_THROWS(TactileConfig::load(path.string(), true)); + write("allow_unverified_calibration: true\n"); + CHECK_THROWS(TactileConfig::load(path.string(), true)); + write("allow_unverified_calibration: true\nallow_estimated_layout: true\n"); + CHECK_NOTHROW(TactileConfig::load(path.string(), true)); + CHECK_THROWS(TactileConfig::load(path.string(), false)); + std::string old_config = base; + old_config.replace(old_config.find("omniglove-openxr-v2"), 19, "omniglove-openxr-v1"); + std::ofstream(path) << old_config << "allow_unverified_calibration: true\nallow_estimated_layout: true\n"; + CHECK_THROWS(TactileConfig::load(path.string(), true)); + write("allow_unverified_calibration: true\nallow_estimated_layout: true\nbone_file: missing.bin\n"); + CHECK_THROWS(TactileConfig::load(path.string(), true)); + std::ofstream(directory / "metadata.bin", std::ios::binary | std::ios::trunc) << "bad"; + write("allow_unverified_calibration: true\nallow_estimated_layout: true\n"); + CHECK_THROWS(TactileConfig::load(path.string(), true)); +} diff --git a/tests/python/CMakeLists.txt b/tests/python/CMakeLists.txt index f2609a4e58..2ff4cfd653 100644 --- a/tests/python/CMakeLists.txt +++ b/tests/python/CMakeLists.txt @@ -33,3 +33,7 @@ endif() if(BUILD_EXAMPLES AND BUILD_PYTHON_BINDINGS) add_subdirectory(examples/teleop_keyboard) endif() + +if(BUILD_PLUGIN_OMNIGLOVE AND BUILD_PYTHON_BINDINGS) + add_subdirectory(plugins/omniglove) +endif() diff --git a/tests/python/plugins/omniglove/CMakeLists.txt b/tests/python/plugins/omniglove/CMakeLists.txt new file mode 100644 index 0000000000..d728478b5a --- /dev/null +++ b/tests/python/plugins/omniglove/CMakeLists.txt @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +add_test(NAME omniglove_tactile_layout_export + COMMAND uv run --python ${ISAAC_TELEOP_PYTHON_VERSION} --extra dev pytest -v --tb=short test_export.py + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" +) +set_tests_properties(omniglove_tactile_layout_export PROPERTIES + ENVIRONMENT "PYTHONPATH=${CMAKE_BINARY_DIR}/python_package/$" +) diff --git a/tests/python/plugins/omniglove/conftest.py b/tests/python/plugins/omniglove/conftest.py new file mode 100644 index 0000000000..c1df9955dc --- /dev/null +++ b/tests/python/plugins/omniglove/conftest.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +import importlib.util + +import pytest + +from repo_paths import repo_root + + +@pytest.fixture +def exporter(): + path = repo_root() / "src/plugins/omniglove/tools/prepare_tactile.py" + spec = importlib.util.spec_from_file_location("prepare_tactile", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module diff --git a/tests/python/plugins/omniglove/pyproject.toml b/tests/python/plugins/omniglove/pyproject.toml new file mode 100644 index 0000000000..d1e14023ea --- /dev/null +++ b/tests/python/plugins/omniglove/pyproject.toml @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +[project] +name = "omniglove-tactile-layout-tests" +version = "0.0.0" +requires-python = ">=3.11,<3.14" + +[project.optional-dependencies] +dev = ["pytest", "numpy"] + +[tool.pytest.ini_options] +pythonpath = [".", "../.."] diff --git a/tests/python/plugins/omniglove/test_export.py b/tests/python/plugins/omniglove/test_export.py new file mode 100644 index 0000000000..ca83304df3 --- /dev/null +++ b/tests/python/plugins/omniglove/test_export.py @@ -0,0 +1,149 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Agibot Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +import copy +import json +import subprocess +import sys + +import numpy as np +import pytest + + +def synthetic_layout(hand): + # Wrist is identity; fingers have a 90-degree legacy local correction. + c = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + root = np.eye(3) if hand == "left" else np.diag([-1.0, -1.0, 1.0]) + corrections = np.repeat(c[None], 21, axis=0) + corrections[0] = root.T + segments = np.tile([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], (21, 1)) + # q(root * c) is +90 degrees for left and -90 degrees for right. + segments[1:, 5] = (1 if hand == "left" else -1) * np.sqrt(0.5) + segments[1:, 6] = np.sqrt(0.5) + taxels = np.tile([0.01, 0.02, 0.03, 0.0, 0.0, 0.0, 1.0], (746, 1)) + return { + "version": 1, + "hand": hand, + "root_frame": "OpenXR wrist", + "joint_ids": [ + 1, + 2, + 3, + 4, + 5, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 17, + 18, + 19, + 20, + 22, + 23, + 24, + 25, + ], + "segment_bind_poses": segments.tolist(), + "taxel_bind_poses": taxels.tolist(), + "joint_corrections": corrections.tolist(), + "indices": np.zeros((746, 4), dtype=int).tolist(), + "weights": np.tile([1.0, 0.0, 0.0, 0.0], (746, 1)).tolist(), + } + + +@pytest.mark.parametrize("hand", ["left", "right"]) +def test_segment_axes_match_handtracker_and_preserve_taxels(exporter, hand): + layout = synthetic_layout(hand) + original = copy.deepcopy(layout) + metadata = exporter.convert_layout(layout) + poses = np.asarray(metadata.geometry_mapping.segment_bind_poses) + assert np.allclose(poses[0], [0, 0, 0, 0, 0, 0, 1]) + assert np.allclose(np.abs(poses[5:, 4]), 1) + assert np.allclose(poses[5:, [3, 5, 6]], 0) + # At neutral bind, the corrected thumb +X is handed +/-Y; +Z stays proximal. + for pose in poses[1:5]: + axes = exporter.matrix(pose[3:]) + assert np.allclose(axes[:, 0], [0, -1 if hand == "left" else 1, 0], atol=1e-6) + assert np.allclose(axes[:, 2], [0, 0, -1], atol=1e-6) + assert np.allclose( + metadata.geometry_mapping.taxel_bind_poses, layout["taxel_bind_poses"] + ) + assert layout == original + + +@pytest.mark.parametrize("field", ["weights", "indices", "segment_bind_poses", "hand"]) +def test_bad_layout_rejected(exporter, field): + layout = synthetic_layout("left") + if field == "hand": + layout[field] = "unknown" + elif field == "weights": + layout[field][0] = [0, 0, 0, 0] + elif field == "indices": + layout[field][0][3] = 21 + else: + layout[field][0][0] = 0.1 + with pytest.raises(ValueError): + exporter.convert_layout(layout) + + +def test_export_requires_explicit_units_and_estimate_acceptance(exporter, tmp_path): + layout = tmp_path / "layout.json" + layout.write_text(json.dumps(synthetic_layout("right"))) + output = tmp_path / "config" + command = [ + sys.executable, + exporter.__file__, + str(layout), + "--output", + str(output), + "--device-token", + "test-token", + "--calibration-id", + "synthetic", + ] + assert subprocess.run(command, capture_output=True, check=False).returncode != 0 + command += ["--newtons-per-lsb", "0.00980665"] + assert subprocess.run(command, capture_output=True, check=False).returncode != 0 + command += ["--allow-estimated-layout", "--allow-unverified-calibration"] + subprocess.run(command, check=True, capture_output=True) + config = json.loads((output / "config.json").read_text()) + assert config["hand"] == "right" + assert config["joint_convention"] == "omniglove-openxr-v2" + assert config["newtons_per_lsb"] == 0.00980665 + assert config["allow_unverified_calibration"] + assert (output / config["metadata_file"]).read_bytes() == exporter.convert_layout( + synthetic_layout("right") + ).to_bytes() + assert subprocess.run(command, capture_output=True, check=False).returncode != 0 + + +@pytest.mark.parametrize("hand", ["left", "right"]) +@pytest.mark.parametrize("bend", [0.3, 1.1]) +def test_thumb_skinning_preserves_contact_position_and_normal(exporter, hand, bend): + layout = synthetic_layout(hand) + neutral = exporter.convert_layout(layout).geometry_mapping + root = np.eye(3) if hand == "left" else np.diag([-1.0, -1.0, 1.0]) + # SDK thumb flexes around local Y; the contact frame follows that flexion. + flex = np.array( + [[np.cos(bend), 0, np.sin(bend)], [0, 1, 0], [-np.sin(bend), 0, np.cos(bend)]] + ) + for i in range(1, 5): + correction = np.asarray(layout["joint_corrections"][i]) + layout["segment_bind_poses"][i][3:] = exporter.quaternion( + root @ flex @ correction + ).tolist() + bent = exporter.convert_layout(layout).geometry_mapping + for i in range(1, 5): + bind = exporter.matrix(np.asarray(neutral.segment_bind_poses[i])[3:]) + current = exporter.matrix(np.asarray(bent.segment_bind_poses[i])[3:]) + skinning = current @ bind.T + expected = root @ flex @ root.T + assert np.allclose( + skinning @ [0.01, 0.02, 0.03], expected @ [0.01, 0.02, 0.03], atol=1e-6 + ) + assert np.allclose(skinning @ [0, 0, 1], expected @ [0, 0, 1], atol=1e-6) From b54199773f29900898a9d25c1626faa9504b3488 Mon Sep 17 00:00:00 2001 From: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:55:16 +0800 Subject: [PATCH 2/4] Handle transient OmniGlove BONE reads during recovery Keep a tactile source inactive until the device snapshot can be read and verified. Reject force scales that round to zero in the plugin. Signed-off-by: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> --- docs/source/device/tactile/omniglove.rst | 5 +- src/plugins/omniglove/README.md | 3 +- .../omniglove_plugin/omniglove_tactile.hpp | 5 +- .../omniglove/core/omniglove_plugin.cpp | 3 +- .../omniglove/core/omniglove_tactile.cpp | 34 +++++++++-- .../omniglove/tools/prepare_tactile.py | 3 +- tests/cpp/plugins/omniglove/test_tactile.cpp | 59 +++++++++++++++++++ tests/python/plugins/omniglove/test_export.py | 14 ++++- 8 files changed, 112 insertions(+), 14 deletions(-) diff --git a/docs/source/device/tactile/omniglove.rst b/docs/source/device/tactile/omniglove.rst index 5eb52e6b51..c661341581 100644 --- a/docs/source/device/tactile/omniglove.rst +++ b/docs/source/device/tactile/omniglove.rst @@ -111,8 +111,9 @@ Metadata is published before forces, periodically during streaming, and again on recovery. Invalid or 200 ms stale samples withdraw the collections. The producer rejects old/future samples and logs malformed frames, queue drops and sequence gaps. Recovery rechecks identity and any BONE snapshot before -publication. Consumers must be tested for correct invalidation and rediscovery -with the target runtime. +publication. If the BONE read fails, the affected tactile collection stays +inactive while the plugin retries. Consumers must be tested for correct +invalidation and rediscovery with the target runtime. The common timestamp comes from SDK monotonic sample time. A valid SDK UTC clock is preserved in raw nanoseconds; otherwise raw time falls back to common diff --git a/src/plugins/omniglove/README.md b/src/plugins/omniglove/README.md index 37bcffe614..3636621d03 100644 --- a/src/plugins/omniglove/README.md +++ b/src/plugins/omniglove/README.md @@ -18,7 +18,8 @@ The plugin also publishes standard `TactileDataArray` forces and `TactileMetadata` layouts for 746 taxels per configured hand. It copies the SDK's POSE_DATA tactile regions using the same session as POST_DATA hand tracking. Tactile processing and BONE checks run on a separate worker so USB -control waits do not stall hand updates. Errors propagate to the main loop. +control waits do not stall hand updates. Failed BONE reads are retried with +the affected tactile source inactive. Prepare the SDK's personal hand calibration separately, then export an external version-1 layout (ordered 21 joints, segment/taxel bind poses, joint corrections diff --git a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp index 866202c762..db5d517fab 100644 --- a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp +++ b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp @@ -51,7 +51,8 @@ class TactileSource { public: TactileSource(TactileConfig config, bool is_left, const std::string& collection_id); - void check_device(omniglove_device_t* device) const; + // Returns false if the BONE read needs a retry. Confirmed mismatches throw. + bool check_device(omniglove_device_t* device) const; void on_sample(const omniglove_stream_sample_t& sample); void pump(const core::OpenXRSessionHandles& handles, omniglove_device_t* device, int64_t now_ns); void stop(); @@ -79,7 +80,9 @@ class TactileSource uint64_t m_last_sequence = 0; int64_t m_last_sample_ns = 0; int64_t m_last_metadata_ns = 0; + int64_t m_next_device_check_ns = 0; bool m_have_generation = false; + bool m_device_verified = false; std::unique_ptr m_data_pusher; std::unique_ptr m_metadata_pusher; }; diff --git a/src/plugins/omniglove/core/omniglove_plugin.cpp b/src/plugins/omniglove/core/omniglove_plugin.cpp index dfd1ece2db..30b86022be 100644 --- a/src/plugins/omniglove/core/omniglove_plugin.cpp +++ b/src/plugins/omniglove/core/omniglove_plugin.cpp @@ -198,7 +198,8 @@ void OmniglovePlugin::start_device_streams() } if (hand_state.tactile) { - hand_state.tactile->check_device(device); + // The worker retries a failed BONE read before publishing the first sample. + (void)hand_state.tactile->check_device(device); hand_state.tactile_context = { this, is_left, hand_state.tactile.get() }; config.kind = OMNIGLOVE_STREAM_POSE_DATA; config.pose_components = OMNIGLOVE_POSE_COMPONENT_TACTILE; diff --git a/src/plugins/omniglove/core/omniglove_tactile.cpp b/src/plugins/omniglove/core/omniglove_tactile.cpp index 0e1c612514..0c7e11dbfe 100644 --- a/src/plugins/omniglove/core/omniglove_tactile.cpp +++ b/src/plugins/omniglove/core/omniglove_tactile.cpp @@ -27,6 +27,7 @@ namespace { constexpr int64_t kStaleNs = 200'000'000; constexpr int64_t kMetadataPeriodNs = 1'000'000'000; +constexpr int64_t kDeviceCheckRetryNs = 1'000'000'000; std::vector read_bytes(const std::filesystem::path& path, size_t max_size) { @@ -219,7 +220,7 @@ TactileSource::TactileSource(TactileConfig config, bool is_left, const std::stri { } -void TactileSource::check_device(omniglove_device_t* device) const +bool TactileSource::check_device(omniglove_device_t* device) const { const size_t size = omniglove_device_opaque_token(device, nullptr, 0); if (size < 2 || size > 4096 || @@ -240,12 +241,19 @@ void TactileSource::check_device(omniglove_device_t* device) const omniglove_control_result_t result{}; result.struct_size = sizeof(result); const auto status = omniglove_device_bone_read(device, bone.data(), bone.size(), &length, 2000, &result); - if (status != OMNIGLOVE_CONTROL_COMPLETE || result.return_code || result.device_error_code || - length != m_config.bone.size() || !std::equal(bone.begin(), bone.end(), m_config.bone.begin())) + if (status != OMNIGLOVE_CONTROL_COMPLETE || result.return_code || result.device_error_code) { - throw std::runtime_error("tactile BONE snapshot differs or could not be read; rebuild the layout"); + isaaccapture::Logger::get("isaaccapture.plugins.omniglove.TactileSource") + ->warn("{} BONE read failed (status {}, return code {}, device error {}); will retry", m_collection_id, + static_cast(status), result.return_code, result.device_error_code); + return false; + } + if (length != m_config.bone.size() || !std::equal(bone.begin(), bone.end(), m_config.bone.begin())) + { + throw std::runtime_error("tactile BONE snapshot differs; rebuild the layout"); } } + return true; } void TactileSource::on_sample(const omniglove_stream_sample_t& sample) @@ -332,12 +340,26 @@ void TactileSource::pump(const core::OpenXRSessionHandles& handles, omniglove_de if (new_generation) { stop(); - check_device(device); - now_ns = core::os_monotonic_now_ns(); m_last_sample_ns = 0; m_generation = frame.generation; m_have_generation = true; m_last_sequence = 0; + m_device_verified = false; + m_next_device_check_ns = 0; + } + if (!m_device_verified) + { + if (now_ns < m_next_device_check_ns) + { + continue; + } + m_device_verified = check_device(device); + now_ns = core::os_monotonic_now_ns(); + if (!m_device_verified) + { + m_next_device_check_ns = now_ns + kDeviceCheckRetryNs; + continue; + } } if (frame.sample_ns > now_ns || now_ns - frame.sample_ns >= kStaleNs || (m_last_sample_ns && (frame.sample_ns <= m_last_sample_ns || frame.sequence <= m_last_sequence))) diff --git a/src/plugins/omniglove/tools/prepare_tactile.py b/src/plugins/omniglove/tools/prepare_tactile.py index 730db19c48..406a530429 100644 --- a/src/plugins/omniglove/tools/prepare_tactile.py +++ b/src/plugins/omniglove/tools/prepare_tactile.py @@ -183,7 +183,8 @@ def main() -> None: or not args.calibration_id or not np.isfinite(args.newtons_per_lsb) or args.newtons_per_lsb <= 0 - or args.newtons_per_lsb > np.finfo(np.float32).max / 255 + or args.newtons_per_lsb > float(np.finfo(np.float32).max) / 255 + or np.float32(args.newtons_per_lsb) == 0 ): parser.error( "nonempty identity/calibration and finite positive float32 force scale required" diff --git a/tests/cpp/plugins/omniglove/test_tactile.cpp b/tests/cpp/plugins/omniglove/test_tactile.cpp index 179479f827..19b22d87f1 100644 --- a/tests/cpp/plugins/omniglove/test_tactile.cpp +++ b/tests/cpp/plugins/omniglove/test_tactile.cpp @@ -10,12 +10,14 @@ #include #include +#include #include #include #include #include #include #include +#include #include using namespace plugins::omniglove; @@ -107,6 +109,7 @@ uintptr_t next_handle = 10; std::string device_token = "test-token"; bool bone_matches = true; size_t bone_reads = 0; +size_t bone_timeouts = 0; XrResult XRAPI_PTR create_collection(XrSession, const XrPushTensorCollectionCreateInfoNV* info, @@ -187,6 +190,11 @@ extern "C" omniglove_control_status_t OMNIGLOVE_CALL omniglove_device_bone_read( omniglove_device_t*, uint8_t* out, size_t, size_t* size, uint32_t, omniglove_control_result_t*) { ++bone_reads; + if (bone_timeouts > 0) + { + --bone_timeouts; + return OMNIGLOVE_CONTROL_TIMEOUT; + } std::fill_n(out, OMNIGLOVE_BONE_MAX_SIZE, bone_matches ? 7 : 8); *size = OMNIGLOVE_BONE_MAX_SIZE; return OMNIGLOVE_CONTROL_COMPLETE; @@ -345,6 +353,57 @@ TEST_CASE("invalid samples withdraw collections and reconnect checks BONE", "[un CHECK_THROWS(source.check_device(device())); device_token = "test-token"; } +TEST_CASE("a BONE read timeout withholds only the reconnecting tactile source", "[unit][omniglove]") +{ + pushed.clear(); + collections.clear(); + device_token = "test-token"; + bone_matches = true; + bone_reads = 0; + bone_timeouts = 0; + auto cfg = config(); + cfg.bone.assign(OMNIGLOVE_BONE_MAX_SIZE, 7); + TactileSource reconnecting(std::move(cfg), true, "/test/reconnecting"); + TactileSource unaffected(config(), true, "/test/unaffected"); + Sample input; + auto& sample = input.sample; + reconnecting.on_sample(sample); + reconnecting.pump(handles(), device(), core::os_monotonic_now_ns()); + REQUIRE(reconnecting.active()); + REQUIRE(bone_reads == 1); + + ++sample.connection_generation; + sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + bone_timeouts = 1; + reconnecting.on_sample(sample); + reconnecting.pump(handles(), device(), core::os_monotonic_now_ns()); + CHECK_FALSE(reconnecting.active()); + CHECK(collections.empty()); + CHECK(pushed.size() == 2); + + ++sample.source_sequence; + sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + reconnecting.on_sample(sample); + reconnecting.pump(handles(), device(), core::os_monotonic_now_ns()); + CHECK(bone_reads == 2); + unaffected.on_sample(sample); + unaffected.pump(handles(), device(), core::os_monotonic_now_ns()); + REQUIRE(unaffected.active()); + + std::this_thread::sleep_for(std::chrono::seconds(1)); + ++sample.source_sequence; + sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + unaffected.on_sample(sample); + unaffected.pump(handles(), device(), core::os_monotonic_now_ns()); + reconnecting.on_sample(sample); + reconnecting.pump(handles(), device(), core::os_monotonic_now_ns()); + CHECK(bone_reads == 3); + CHECK(reconnecting.active()); + CHECK(unaffected.active()); + REQUIRE(pushed.size() >= 2); + CHECK(pushed[pushed.size() - 2].collection == "/test/reconnecting/metadata"); + CHECK(pushed.back().collection == "/test/reconnecting"); +} TEST_CASE("bounded queues, future frames, metadata refresh and dual collection isolation", "[unit][omniglove]") { pushed.clear(); diff --git a/tests/python/plugins/omniglove/test_export.py b/tests/python/plugins/omniglove/test_export.py index ca83304df3..bcc34d0032 100644 --- a/tests/python/plugins/omniglove/test_export.py +++ b/tests/python/plugins/omniglove/test_export.py @@ -107,9 +107,19 @@ def test_export_requires_explicit_units_and_estimate_acceptance(exporter, tmp_pa "synthetic", ] assert subprocess.run(command, capture_output=True, check=False).returncode != 0 - command += ["--newtons-per-lsb", "0.00980665"] - assert subprocess.run(command, capture_output=True, check=False).returncode != 0 + scale = ["--newtons-per-lsb", "0.00980665"] + assert ( + subprocess.run(command + scale, capture_output=True, check=False).returncode + != 0 + ) command += ["--allow-estimated-layout", "--allow-unverified-calibration"] + underflow = subprocess.run( + command + ["--newtons-per-lsb", "1e-100"], capture_output=True, check=False + ) + assert underflow.returncode != 0 + assert b"finite positive float32 force scale required" in underflow.stderr + assert not output.exists() + command += scale subprocess.run(command, check=True, capture_output=True) config = json.loads((output / "config.json").read_text()) assert config["hand"] == "right" From e282400f213a1b3643e2dedd57089bbdcbfdc9c8 Mon Sep 17 00:00:00 2001 From: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:15:12 +0800 Subject: [PATCH 3/4] Isolate OmniGlove tactile recovery per hand Give each configured glove its own tactile worker so a blocking BONE read does not delay the other publisher. Join the workers before destroying the SDK session and cover an overlapping read and publication in the regression suite. Signed-off-by: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> --- docs/source/device/tactile/omniglove.rst | 5 +- src/plugins/omniglove/README.md | 7 +- .../inc/omniglove_plugin/omniglove_plugin.hpp | 6 +- .../omniglove_plugin/omniglove_tactile.hpp | 6 + .../omniglove/core/omniglove_plugin.cpp | 45 ++++---- .../omniglove/core/omniglove_tactile.cpp | 13 +++ tests/cpp/plugins/omniglove/test_tactile.cpp | 106 +++++++++++++++++- 7 files changed, 150 insertions(+), 38 deletions(-) diff --git a/docs/source/device/tactile/omniglove.rst b/docs/source/device/tactile/omniglove.rst index c661341581..b644aa585d 100644 --- a/docs/source/device/tactile/omniglove.rst +++ b/docs/source/device/tactile/omniglove.rst @@ -117,8 +117,9 @@ invalidation and rediscovery with the target runtime. The common timestamp comes from SDK monotonic sample time. A valid SDK UTC clock is preserved in raw nanoseconds; otherwise raw time falls back to common -time. These are not claims of physical multi-stream synchronization. BONE -verification runs on a separate worker from the hand update loop but may delay tactile recovery. +time. These are not claims of physical multi-stream synchronization. Each +glove's tactile worker runs its own BONE read, which can delay recovery for +that glove. A hand/config mismatch, wrong device token, invalid metadata, missing explicit scale or changed BONE payload fails startup/publication. Rebuild the local diff --git a/src/plugins/omniglove/README.md b/src/plugins/omniglove/README.md index 3636621d03..151952528b 100644 --- a/src/plugins/omniglove/README.md +++ b/src/plugins/omniglove/README.md @@ -17,9 +17,10 @@ Installation, wrist calibration, running, licensing and troubleshooting: The plugin also publishes standard `TactileDataArray` forces and `TactileMetadata` layouts for 746 taxels per configured hand. It copies the SDK's POSE_DATA tactile regions using the same session as POST_DATA hand -tracking. Tactile processing and BONE checks run on a separate worker so USB -control waits do not stall hand updates. Failed BONE reads are retried with -the affected tactile source inactive. +tracking. Each configured glove has its own tactile worker, so a BONE read +can delay that glove's tactile recovery while hand tracking and the other +glove's tactile publication continue. Failed BONE reads are retried while +the affected tactile source is inactive. Prepare the SDK's personal hand calibration separately, then export an external version-1 layout (ordered 21 joints, segment/taxel bind poses, joint corrections diff --git a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp index 120a4c872d..bdc7bef7e5 100644 --- a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp +++ b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp @@ -90,7 +90,7 @@ class OmniglovePlugin static void stream_callback(const omniglove_stream_sample* sample, void* user_data) noexcept; void start_device_streams(); - void pump_tactile(std::stop_token stop); + void run_tactile(HandState& hand, const core::OpenXRSessionHandles& handles, std::stop_token stop); void on_sample(const omniglove_stream_sample& sample, bool is_left); void pump_hand(HandState& hand, bool is_left, const CallbackState& input); @@ -109,8 +109,8 @@ class OmniglovePlugin std::exception_ptr m_callback_error; // Destroy the SDK first: its callbacks borrow the contexts, frames and mutex above. SdkSession m_sdk_session; - // Join the tactile worker before destroying the SDK and its borrowed devices. - std::jthread m_tactile_worker; + // Join both tactile workers before destroying the SDK and its borrowed devices. + std::array m_tactile_workers; }; } // namespace plugins::omniglove diff --git a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp index db5d517fab..6f4a67a80b 100644 --- a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp +++ b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp @@ -9,9 +9,11 @@ #include #include +#include #include #include #include +#include #include #include @@ -54,6 +56,10 @@ class TactileSource // Returns false if the BONE read needs a retry. Confirmed mismatches throw. bool check_device(omniglove_device_t* device) const; void on_sample(const omniglove_stream_sample_t& sample); + void run(std::stop_token stop, + const core::OpenXRSessionHandles& handles, + omniglove_device_t* device, + std::chrono::milliseconds interval); void pump(const core::OpenXRSessionHandles& handles, omniglove_device_t* device, int64_t now_ns); void stop(); bool active() const noexcept diff --git a/src/plugins/omniglove/core/omniglove_plugin.cpp b/src/plugins/omniglove/core/omniglove_plugin.cpp index 30b86022be..8689269502 100644 --- a/src/plugins/omniglove/core/omniglove_plugin.cpp +++ b/src/plugins/omniglove/core/omniglove_plugin.cpp @@ -128,18 +128,30 @@ OmniglovePlugin::OmniglovePlugin(const std::string& plugin_root_id) m_logger->info( "initialized with {} glove stream(s)", std::count_if(m_hands.begin(), m_hands.end(), [](const auto& hand) { return hand.stream.has_value(); })); - if (have_tactile) + // A synchronous BONE read on one device must not stall the other publisher. + for (size_t i = 0; i < m_hands.size(); ++i) { - m_tactile_worker = std::jthread([this](std::stop_token stop) { pump_tactile(stop); }); + auto& hand = m_hands[i]; + if (hand.tactile) + { + m_tactile_workers[i] = + std::jthread([this, &hand, handles](std::stop_token stop) { run_tactile(hand, handles, stop); }); + } } } OmniglovePlugin::~OmniglovePlugin() { - if (m_tactile_worker.joinable()) + for (auto& worker : m_tactile_workers) { - m_tactile_worker.request_stop(); - m_tactile_worker.join(); + worker.request_stop(); + } + for (auto& worker : m_tactile_workers) + { + if (worker.joinable()) + { + worker.join(); + } } m_sdk_session.reset(); } @@ -361,22 +373,11 @@ void OmniglovePlugin::pump_hand(HandState& hand, bool is_left, const CallbackSta hand.reason = core::PluginDeviceReason_NONE; } -void OmniglovePlugin::pump_tactile(std::stop_token stop) +void OmniglovePlugin::run_tactile(HandState& hand, const core::OpenXRSessionHandles& handles, std::stop_token stop) { - // BONE reads can wait on USB; hand updates must keep running during recovery. try { - while (!stop.stop_requested()) - { - for (auto& hand : m_hands) - { - if (hand.tactile) - { - hand.tactile->pump(m_session->get_handles(), hand.device, core::os_monotonic_now_ns()); - } - } - std::this_thread::sleep_for(kSourceInterval); - } + hand.tactile->run(stop, handles, hand.device, kSourceInterval); } catch (...) { @@ -386,13 +387,7 @@ void OmniglovePlugin::pump_tactile(std::stop_token stop) m_callback_error = std::current_exception(); } } - for (auto& hand : m_hands) - { - if (hand.tactile) - { - hand.tactile->stop(); - } - } + hand.tactile->stop(); } void OmniglovePlugin::update() diff --git a/src/plugins/omniglove/core/omniglove_tactile.cpp b/src/plugins/omniglove/core/omniglove_tactile.cpp index 0c7e11dbfe..5997432e6c 100644 --- a/src/plugins/omniglove/core/omniglove_tactile.cpp +++ b/src/plugins/omniglove/core/omniglove_tactile.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -277,6 +278,18 @@ void TactileSource::on_sample(const omniglove_stream_sample_t& sample) ++m_size; } +void TactileSource::run(std::stop_token stop, + const core::OpenXRSessionHandles& handles, + omniglove_device_t* device, + std::chrono::milliseconds interval) +{ + while (!stop.stop_requested()) + { + pump(handles, device, core::os_monotonic_now_ns()); + std::this_thread::sleep_for(interval); + } +} + void TactileSource::stop() { m_active.store(false, std::memory_order_release); diff --git a/tests/cpp/plugins/omniglove/test_tactile.cpp b/tests/cpp/plugins/omniglove/test_tactile.cpp index 19b22d87f1..c9fceeab37 100644 --- a/tests/cpp/plugins/omniglove/test_tactile.cpp +++ b/tests/cpp/plugins/omniglove/test_tactile.cpp @@ -10,12 +10,15 @@ #include #include +#include #include #include #include #include #include #include +#include +#include #include #include #include @@ -105,23 +108,34 @@ struct Push }; std::map collections; std::vector pushed; +std::mutex publication_mutex; uintptr_t next_handle = 10; std::string device_token = "test-token"; bool bone_matches = true; size_t bone_reads = 0; size_t bone_timeouts = 0; +struct BlockedBoneRead +{ + std::binary_semaphore entered{ 0 }; + std::binary_semaphore release{ 0 }; + std::atomic finished{ false }; +}; +BlockedBoneRead* blocked_bone_read = nullptr; + XrResult XRAPI_PTR create_collection(XrSession, const XrPushTensorCollectionCreateInfoNV* info, XrPushTensorCollectionCreateResultNV*, XrPushTensorCollectionNV* output) { + const std::lock_guard lock(publication_mutex); *output = reinterpret_cast(++next_handle); collections[*output] = info->data.identifier; return XR_SUCCESS; } XrResult XRAPI_PTR push(XrPushTensorCollectionNV handle, const XrPushTensorCollectionDataNV* data) { + const std::lock_guard lock(publication_mutex); const auto* bytes = static_cast(data->buffer); pushed.push_back( { collections.at(handle), { bytes, bytes + data->bufferSize }, data->timestamp, data->rawDeviceTimestamp }); @@ -129,6 +143,7 @@ XrResult XRAPI_PTR push(XrPushTensorCollectionNV handle, const XrPushTensorColle } XrResult XRAPI_PTR destroy_collection(XrPushTensorCollectionNV handle) { + const std::lock_guard lock(publication_mutex); collections.erase(handle); return XR_SUCCESS; } @@ -166,9 +181,9 @@ core::OpenXRSessionHandles handles() result.xrGetInstanceProcAddr = get_proc; return result; } -omniglove_device_t* device() +omniglove_device_t* device(bool left = true) { - return reinterpret_cast(1); + return reinterpret_cast(left ? 1 : 2); } } // namespace @@ -182,14 +197,21 @@ extern "C" size_t OMNIGLOVE_CALL omniglove_device_opaque_token(const omniglove_d } return device_token.size() + 1; } -extern "C" omniglove_hand_t OMNIGLOVE_CALL omniglove_device_hand(const omniglove_device_t*) +extern "C" omniglove_hand_t OMNIGLOVE_CALL omniglove_device_hand(const omniglove_device_t* glove) { - return OMNIGLOVE_HAND_LEFT; + return glove == device() ? OMNIGLOVE_HAND_LEFT : OMNIGLOVE_HAND_RIGHT; } extern "C" omniglove_control_status_t OMNIGLOVE_CALL omniglove_device_bone_read( - omniglove_device_t*, uint8_t* out, size_t, size_t* size, uint32_t, omniglove_control_result_t*) + omniglove_device_t*, uint8_t* out, size_t, size_t* size, uint32_t timeout_ms, omniglove_control_result_t*) { ++bone_reads; + if (blocked_bone_read) + { + blocked_bone_read->entered.release(); + blocked_bone_read->release.try_acquire_for(std::chrono::milliseconds(timeout_ms)); + blocked_bone_read->finished.store(true); + return OMNIGLOVE_CONTROL_TIMEOUT; + } if (bone_timeouts > 0) { --bone_timeouts; @@ -404,6 +426,80 @@ TEST_CASE("a BONE read timeout withholds only the reconnecting tactile source", CHECK(pushed[pushed.size() - 2].collection == "/test/reconnecting/metadata"); CHECK(pushed.back().collection == "/test/reconnecting"); } +TEST_CASE("a blocked BONE read leaves the other tactile worker publishing", "[unit][omniglove]") +{ + using namespace std::chrono_literals; + pushed.clear(); + collections.clear(); + device_token = "test-token"; + bone_matches = true; + auto cfg = config(); + cfg.bone.assign(OMNIGLOVE_BONE_MAX_SIZE, 7); + TactileSource reconnecting(std::move(cfg), true, "/test/reconnecting"); + TactileSource healthy(config(), false, "/test/healthy"); + const auto xr_handles = handles(); + Sample reconnect_sample; + reconnecting.on_sample(reconnect_sample.sample); + reconnecting.pump(xr_handles, device(), core::os_monotonic_now_ns()); + REQUIRE(reconnecting.active()); + Sample healthy_sample(false); + healthy.on_sample(healthy_sample.sample); + healthy.pump(xr_handles, device(false), core::os_monotonic_now_ns()); + REQUIRE(healthy.active()); + + BlockedBoneRead read; + std::jthread reconnect_worker; + // Restore the test double after joining, including when a check fails. + struct ResetRead + { + BlockedBoneRead& read; + std::jthread& worker; + ~ResetRead() + { + if (worker.joinable()) + { + worker.request_stop(); + read.release.release(); + worker.join(); + } + blocked_bone_read = nullptr; + } + }; + const ResetRead reset_read{ read, reconnect_worker }; + blocked_bone_read = &read; + // Queue the reconnect frame before the worker snapshots the monotonic clock. + ++reconnect_sample.sample.connection_generation; + reconnect_sample.sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + reconnecting.on_sample(reconnect_sample.sample); + reconnect_worker = std::jthread([&](std::stop_token stop) { reconnecting.run(stop, xr_handles, device(), 8ms); }); + std::jthread healthy_worker([&](std::stop_token stop) { healthy.run(stop, xr_handles, device(false), 8ms); }); + REQUIRE(read.entered.try_acquire_for(1s)); + + const auto block_start = core::os_monotonic_now_ns(); + for (int i = 0; i < 30; ++i) + { + ++healthy_sample.sample.source_sequence; + healthy_sample.sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + healthy.on_sample(healthy_sample.sample); + std::this_thread::sleep_for(10ms); + } + + CHECK_FALSE(reconnecting.active()); + CHECK(healthy.active()); + { + const std::lock_guard lock(publication_mutex); + REQUIRE_FALSE(read.finished.load()); + const auto is_healthy_force = [block_start](const Push& entry) + { return entry.collection == "/test/healthy" && entry.time >= block_start; }; + const auto first = std::find_if(pushed.begin(), pushed.end(), is_healthy_force); + const auto last = std::find_if(pushed.rbegin(), pushed.rend(), is_healthy_force); + REQUIRE(first != pushed.end()); + REQUIRE(last != pushed.rend()); + CHECK(last->time - first->time > 200'000'000); + CHECK(std::count_if(pushed.begin(), pushed.end(), + [](const Push& entry) { return entry.collection == "/test/healthy/metadata"; }) == 1); + } +} TEST_CASE("bounded queues, future frames, metadata refresh and dual collection isolation", "[unit][omniglove]") { pushed.clear(); From 6010aa1629901e6e380381c28a15ca86939dbd1a Mon Sep 17 00:00:00 2001 From: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:48:46 +0800 Subject: [PATCH 4/4] Serialize OmniGlove tactile collection creation Share a session-scoped lock between the tactile sources when creating their OpenXR collections. Keep BONE reads outside the lock and test simultaneous collection creation at startup and after reconnect. Signed-off-by: zhouyingchun517609 <41613127+zhouyingchun517609@users.noreply.github.com> --- .../inc/omniglove_plugin/omniglove_plugin.hpp | 1 + .../omniglove_plugin/omniglove_tactile.hpp | 6 +- .../omniglove/core/omniglove_plugin.cpp | 3 +- .../omniglove/core/omniglove_tactile.cpp | 37 +++++---- tests/cpp/plugins/omniglove/test_tactile.cpp | 75 +++++++++++++++++-- 5 files changed, 99 insertions(+), 23 deletions(-) diff --git a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp index bdc7bef7e5..98c82a9543 100644 --- a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp +++ b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_plugin.hpp @@ -104,6 +104,7 @@ class OmniglovePlugin std::optional m_status_publisher; std::mutex m_frame_mutex; + std::mutex m_collection_creation_mutex; std::array m_hands; std::array m_inputs; std::exception_ptr m_callback_error; diff --git a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp index 6f4a67a80b..0f69dd1752 100644 --- a/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp +++ b/src/plugins/omniglove/core/inc/omniglove_plugin/omniglove_tactile.hpp @@ -52,7 +52,10 @@ struct TactileConfig class TactileSource { public: - TactileSource(TactileConfig config, bool is_left, const std::string& collection_id); + TactileSource(TactileConfig config, + bool is_left, + const std::string& collection_id, + std::mutex& collection_creation_mutex); // Returns false if the BONE read needs a retry. Confirmed mismatches throw. bool check_device(omniglove_device_t* device) const; void on_sample(const omniglove_stream_sample_t& sample); @@ -73,6 +76,7 @@ class TactileSource TactileConfig m_config; bool m_is_left; std::string m_collection_id; + std::mutex& m_collection_creation_mutex; std::mutex m_mutex; std::array m_frames{}; size_t m_head = 0; diff --git a/src/plugins/omniglove/core/omniglove_plugin.cpp b/src/plugins/omniglove/core/omniglove_plugin.cpp index 8689269502..6eb18b150c 100644 --- a/src/plugins/omniglove/core/omniglove_plugin.cpp +++ b/src/plugins/omniglove/core/omniglove_plugin.cpp @@ -95,7 +95,8 @@ OmniglovePlugin::OmniglovePlugin(const std::string& plugin_root_id) if (path != nullptr && *path != '\0') { hand_state(is_left).tactile = std::make_unique( - TactileConfig::load(path, is_left), is_left, std::string("/glove/omniglove_") + hand_name(is_left)); + TactileConfig::load(path, is_left), is_left, std::string("/glove/omniglove_") + hand_name(is_left), + m_collection_creation_mutex); } } m_sdk_session = create_sdk_session(m_logger); diff --git a/src/plugins/omniglove/core/omniglove_tactile.cpp b/src/plugins/omniglove/core/omniglove_tactile.cpp index 5997432e6c..9034e79ee8 100644 --- a/src/plugins/omniglove/core/omniglove_tactile.cpp +++ b/src/plugins/omniglove/core/omniglove_tactile.cpp @@ -216,8 +216,14 @@ TactileConfig TactileConfig::load(const std::string& path, bool is_left) return result; } -TactileSource::TactileSource(TactileConfig config, bool is_left, const std::string& collection_id) - : m_config(std::move(config)), m_is_left(is_left), m_collection_id(collection_id) +TactileSource::TactileSource(TactileConfig config, + bool is_left, + const std::string& collection_id, + std::mutex& collection_creation_mutex) + : m_config(std::move(config)), + m_is_left(is_left), + m_collection_id(collection_id), + m_collection_creation_mutex(collection_creation_mutex) { } @@ -381,17 +387,22 @@ void TactileSource::pump(const core::OpenXRSessionHandles& handles, omniglove_de } if (!m_data_pusher) { - m_metadata_pusher = std::make_unique( - handles, - core::SchemaPusherConfig{ .collection_id = core::tracker_metadata_collection_id(m_collection_id), - .max_flatbuffer_size = m_config.metadata.size(), - .tensor_identifier = std::string(core::TRACKER_METADATA_TENSOR_IDENTIFIER), - .localized_name = "OmniGlove tactile layout" }); - m_data_pusher = std::make_unique( - handles, core::SchemaPusherConfig{ .collection_id = m_collection_id, - .max_flatbuffer_size = 16384, - .tensor_identifier = "tactile", - .localized_name = "OmniGlove tactile forces" }); + { + // Both workers create collections on the same XrSession. Keep USB reads + // and writes to individual collection handles outside the session lock. + const std::lock_guard lock(m_collection_creation_mutex); + m_metadata_pusher = std::make_unique( + handles, + core::SchemaPusherConfig{ .collection_id = core::tracker_metadata_collection_id(m_collection_id), + .max_flatbuffer_size = m_config.metadata.size(), + .tensor_identifier = std::string(core::TRACKER_METADATA_TENSOR_IDENTIFIER), + .localized_name = "OmniGlove tactile layout" }); + m_data_pusher = std::make_unique( + handles, core::SchemaPusherConfig{ .collection_id = m_collection_id, + .max_flatbuffer_size = 16384, + .tensor_identifier = "tactile", + .localized_name = "OmniGlove tactile forces" }); + } logger->info( "{} active: generation {}, calibration {}", m_collection_id, m_generation, m_config.calibration_id); } diff --git a/tests/cpp/plugins/omniglove/test_tactile.cpp b/tests/cpp/plugins/omniglove/test_tactile.cpp index c9fceeab37..48176df909 100644 --- a/tests/cpp/plugins/omniglove/test_tactile.cpp +++ b/tests/cpp/plugins/omniglove/test_tactile.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -109,6 +110,7 @@ struct Push std::map collections; std::vector pushed; std::mutex publication_mutex; +std::mutex collection_creation_mutex; uintptr_t next_handle = 10; std::string device_token = "test-token"; bool bone_matches = true; @@ -123,11 +125,27 @@ struct BlockedBoneRead }; BlockedBoneRead* blocked_bone_read = nullptr; +struct CollectionCreationProbe +{ + std::atomic in_flight{ 0 }; + std::atomic overlapped{ false }; +}; +CollectionCreationProbe* collection_creation_probe = nullptr; + XrResult XRAPI_PTR create_collection(XrSession, const XrPushTensorCollectionCreateInfoNV* info, XrPushTensorCollectionCreateResultNV*, XrPushTensorCollectionNV* output) { + if (auto* probe = collection_creation_probe) + { + if (probe->in_flight.fetch_add(1) != 0) + { + probe->overlapped.store(true); + } + std::this_thread::sleep_for(std::chrono::milliseconds(15)); + probe->in_flight.fetch_sub(1); + } const std::lock_guard lock(publication_mutex); *output = reinterpret_cast(++next_handle); collections[*output] = info->data.identifier; @@ -317,7 +335,7 @@ TEST_CASE("publisher announces metadata, retains SDK times and expires on silenc pushed.clear(); collections.clear(); device_token = "test-token"; - TactileSource source(config(), true, "/test/left"); + TactileSource source(config(), true, "/test/left", collection_creation_mutex); Sample s; s.sample.flags = OMNIGLOVE_STREAM_SAMPLE_DEVICE_TIME_VALID; s.sample.device_time_ms = 1'700'000'000'000; @@ -351,7 +369,7 @@ TEST_CASE("invalid samples withdraw collections and reconnect checks BONE", "[un bone_reads = 0; auto cfg = config(); cfg.bone.assign(OMNIGLOVE_BONE_MAX_SIZE, 7); - TactileSource source(std::move(cfg), true, "/test/left"); + TactileSource source(std::move(cfg), true, "/test/left", collection_creation_mutex); Sample s; source.on_sample(s.sample); source.pump(handles(), device(), core::os_monotonic_now_ns()); @@ -385,8 +403,8 @@ TEST_CASE("a BONE read timeout withholds only the reconnecting tactile source", bone_timeouts = 0; auto cfg = config(); cfg.bone.assign(OMNIGLOVE_BONE_MAX_SIZE, 7); - TactileSource reconnecting(std::move(cfg), true, "/test/reconnecting"); - TactileSource unaffected(config(), true, "/test/unaffected"); + TactileSource reconnecting(std::move(cfg), true, "/test/reconnecting", collection_creation_mutex); + TactileSource unaffected(config(), true, "/test/unaffected", collection_creation_mutex); Sample input; auto& sample = input.sample; reconnecting.on_sample(sample); @@ -435,8 +453,8 @@ TEST_CASE("a blocked BONE read leaves the other tactile worker publishing", "[un bone_matches = true; auto cfg = config(); cfg.bone.assign(OMNIGLOVE_BONE_MAX_SIZE, 7); - TactileSource reconnecting(std::move(cfg), true, "/test/reconnecting"); - TactileSource healthy(config(), false, "/test/healthy"); + TactileSource reconnecting(std::move(cfg), true, "/test/reconnecting", collection_creation_mutex); + TactileSource healthy(config(), false, "/test/healthy", collection_creation_mutex); const auto xr_handles = handles(); Sample reconnect_sample; reconnecting.on_sample(reconnect_sample.sample); @@ -500,12 +518,53 @@ TEST_CASE("a blocked BONE read leaves the other tactile worker publishing", "[un [](const Push& entry) { return entry.collection == "/test/healthy/metadata"; }) == 1); } } +TEST_CASE("tactile sources serialize collection creation on their shared session", "[unit][omniglove]") +{ + pushed.clear(); + collections.clear(); + device_token = "test-token"; + TactileSource left(config(), true, "/test/left", collection_creation_mutex); + TactileSource right(config(), false, "/test/right", collection_creation_mutex); + Sample left_sample; + Sample right_sample(false); + const auto xr_handles = handles(); + const auto publish_both = [&] + { + left_sample.sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); + right_sample.sample.sample_monotonic_ns = left_sample.sample.sample_monotonic_ns; + left.on_sample(left_sample.sample); + right.on_sample(right_sample.sample); + std::barrier start(2); + std::jthread left_worker( + [&] + { + start.arrive_and_wait(); + left.pump(xr_handles, device(), core::os_monotonic_now_ns()); + }); + start.arrive_and_wait(); + right.pump(xr_handles, device(false), core::os_monotonic_now_ns()); + }; + + CollectionCreationProbe probe; + collection_creation_probe = &probe; + publish_both(); + ++left_sample.sample.connection_generation; + ++right_sample.sample.connection_generation; + publish_both(); + collection_creation_probe = nullptr; + + CHECK_FALSE(probe.overlapped.load()); + CHECK(left.active()); + CHECK(right.active()); + CHECK(collections.size() == 4); + CHECK(pushed.size() == 8); +} TEST_CASE("bounded queues, future frames, metadata refresh and dual collection isolation", "[unit][omniglove]") { pushed.clear(); collections.clear(); device_token = "test-token"; - TactileSource first(config(), true, "/test/left"); + TactileSource first(config(), true, "/test/left", collection_creation_mutex); Sample s; for (uint64_t i = 0; i < 70; ++i) { @@ -532,7 +591,7 @@ TEST_CASE("bounded queues, future frames, metadata refresh and dual collection i REQUIRE(pushed.size() == 78); CHECK(std::count_if(pushed.begin(), pushed.end(), [](const Push& entry) { return entry.collection == "/test/left/metadata"; }) == 2); - TactileSource second(config(), true, "/test/other"); + TactileSource second(config(), true, "/test/other", collection_creation_mutex); s.sample.sample_monotonic_ns = static_cast(core::os_monotonic_now_ns()); second.on_sample(s.sample); second.pump(handles(), device(), core::os_monotonic_now_ns());