mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-20 00:51:20 -08:00
Deactivate feeder bridge when using new driver, add bindings provider (#1806)
This commit is contained in:
1 parent
15ff70dda2
commit
3288069ae5
41 files changed
+1776
-335
No files matched your search
@@ -13,6 +13,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
matrix-cpp: ${{ steps.set-matrix.outputs.matrix-cpp }}
|
||||
steps:
|
||||
- id: set-matrix
|
||||
shell: bash
|
||||
@@ -25,7 +26,44 @@ jobs:
|
||||
else
|
||||
RESULT=$(echo "$BASE" | jq -c '.')
|
||||
fi
|
||||
RESULT_CPP=$(echo "$RESULT" | jq -c '[ .[] | select ( (.platform != "macos") and ( (.platform != "windows") or (.os | endswith("-arm") | not) ) ) ]')
|
||||
|
||||
echo "matrix={\"include\":$RESULT}" >> "$GITHUB_OUTPUT"
|
||||
echo "matrix-cpp={\"include\":$RESULT_CPP}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build-bindings-provider:
|
||||
name: Build bindings provider for ${{ matrix.os }}
|
||||
needs: [setup-matrix]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix-cpp) }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
- if: matrix.platform == 'linux'
|
||||
name: Install GCC
|
||||
uses: egor-tensin/setup-gcc@v2
|
||||
with:
|
||||
version: 16
|
||||
- name: Get CMake
|
||||
uses: lukka/get-cmake@latest
|
||||
- name: Configure
|
||||
run: cmake -S bindings-provider/ -B bindings-provider/build -DCMAKE_BUILD_TYPE=Release
|
||||
- name: Build
|
||||
run: cmake --build bindings-provider/build --config Release -j6
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
|
||||
path: |
|
||||
bindings-provider/build/slimevr-bindings-provider
|
||||
bindings-provider/build/libopenvr_api.so
|
||||
bindings-provider/build/Release/SlimeVR-Bindings-Provider.exe
|
||||
bindings-provider/build/openvr_api.dll
|
||||
|
||||
gui-checks:
|
||||
name: Gui Checks
|
||||
runs-on: ubuntu-latest
|
||||
@@ -125,7 +163,7 @@ jobs:
|
||||
|
||||
package-desktop:
|
||||
name: Package Desktop (${{ matrix.platform }} - ${{ matrix.os }})
|
||||
needs: [setup-matrix, build-server-jar, build-gui-frontend]
|
||||
needs: [setup-matrix, build-server-jar, build-gui-frontend, build-bindings-provider]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }}
|
||||
@@ -149,6 +187,12 @@ jobs:
|
||||
with:
|
||||
name: server-jar
|
||||
path: server
|
||||
- if: contains(fromJson(needs.setup-matrix.outputs.matrix-cpp).include.*.os, matrix.os)
|
||||
name: Download bindings provider artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
|
||||
path: bindings-provider/build/${{ matrix.platform == 'windows' && 'win' || 'linux' }}-${{ endsWith(matrix.os, '-arm') && 'arm64' || 'x64' }}
|
||||
- name: Download GUI Dist
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
[submodule "solarxr-protocol"]
|
||||
path = solarxr-protocol
|
||||
url = https://github.com/SlimeVR/SolarXR-Protocol.git
|
||||
[submodule "svr-bindings-provider/openvr"]
|
||||
path = bindings-provider/openvr
|
||||
url = https://github.com/ValveSoftware/openvr.git
|
||||
@@ -0,0 +1,12 @@
|
||||
# Garbage left behind on Windows
|
||||
|
||||
.vs/
|
||||
out/
|
||||
CMakeFiles/
|
||||
vcpkg_installed/
|
||||
src/resources/resources.hpp
|
||||
CMakeCache.txt
|
||||
build.ninja
|
||||
*.cmake
|
||||
*.dll
|
||||
*.log
|
||||
@@ -0,0 +1,78 @@
|
||||
cmake_minimum_required(VERSION 3.26)
|
||||
|
||||
project(SlimeVR-Bindings-Provider)
|
||||
|
||||
set(SOLARXR_PROTOCOL_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol")
|
||||
set(FLATBUFFERS_GENERATED_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol/protocol/cpp")
|
||||
|
||||
# These are used to determine the OpenVR library path
|
||||
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
set(PROCESSOR_ARCH "64")
|
||||
else()
|
||||
set(PROCESSOR_ARCH "32")
|
||||
endif()
|
||||
if(WIN32)
|
||||
set(OPENVR_LIBRARY_NAME "openvr_api")
|
||||
set(OPENVR_LIBRARY_EXT "dll")
|
||||
set(PLATFORM_NAME "win")
|
||||
elseif(APPLE)
|
||||
set(OPENVR_LIBRARY_NAME "libopenvr_api")
|
||||
set(OPENVR_LIBRARY_EXT "dylib")
|
||||
set(PLATFORM_NAME "osx")
|
||||
elseif(LINUX)
|
||||
set(OPENVR_LIBRARY_NAME "libopenvr_api")
|
||||
set(OPENVR_LIBRARY_EXT "so")
|
||||
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
|
||||
set(PLATFORM_NAME "linuxarm")
|
||||
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
|
||||
set(PLATFORM_NAME "linux")
|
||||
else()
|
||||
message(FATAL_ERROR "Unknown/unsupported CPU architecture")
|
||||
endif()
|
||||
else()
|
||||
message(FATAL_ERROR "Unknown/unsupported platform")
|
||||
endif()
|
||||
|
||||
set(OPENVR_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/openvr")
|
||||
|
||||
message(STATUS "OpenVR library search path: ${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}")
|
||||
find_library(OPENVR_LIBRARY NAMES openvr_api REQUIRED PATHS "${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}/" NO_DEFAULT_PATH)
|
||||
message(STATUS "Found OpenVR library at: ${OPENVR_LIBRARY}")
|
||||
|
||||
add_executable("${PROJECT_NAME}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/paths.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/logger.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/solarxr.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/vr_utils.cpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp"
|
||||
)
|
||||
set_target_properties("${PROJECT_NAME}" PROPERTIES CXX_STANDARD 23)
|
||||
target_include_directories("${PROJECT_NAME}" PRIVATE "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/include" "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/" "${FLATBUFFERS_GENERATED_ROOT}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include" "${OPENVR_ROOT}/headers")
|
||||
target_link_libraries("${PROJECT_NAME}" PRIVATE "${OPENVR_LIBRARY}")
|
||||
|
||||
if(LINUX)
|
||||
set_target_properties("${PROJECT_NAME}" PROPERTIES OUTPUT_NAME slimevr-bindings-provider)
|
||||
endif()
|
||||
|
||||
set(OPENVR_RUNTIME_LIBRARY "${OPENVR_ROOT}/bin/${PLATFORM_NAME}${PROCESSOR_ARCH}/${OPENVR_LIBRARY_NAME}.${OPENVR_LIBRARY_EXT}")
|
||||
message(STATUS "Found OpenVR runtime library: ${OPENVR_RUNTIME_LIBRARY}")
|
||||
configure_file("${OPENVR_RUNTIME_LIBRARY}" "${CMAKE_CURRENT_BINARY_DIR}/." COPYONLY)
|
||||
|
||||
# Embed the resources into resources.hpp
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
|
||||
src/resources/manifest.vrmanifest
|
||||
src/resources/action_manifest.json
|
||||
src/resources/generic.json
|
||||
src/resources/knuckles.json
|
||||
src/resources/oculus_touch.json
|
||||
src/resources/vive_controller.json
|
||||
)
|
||||
file(STRINGS src/resources/manifest.vrmanifest SVR_VRAPP_MANIFEST NEWLINE_CONSUME)
|
||||
file(STRINGS src/resources/action_manifest.json SVR_VRAPP_ACTION_MANIFEST NEWLINE_CONSUME)
|
||||
file(STRINGS src/resources/generic.json SVR_VRAPP_GENERIC_BINDS NEWLINE_CONSUME)
|
||||
file(STRINGS src/resources/knuckles.json SVR_VRAPP_KNUCKLES_BINDS NEWLINE_CONSUME)
|
||||
file(STRINGS src/resources/oculus_touch.json SVR_VRAPP_OCULUS_BINDS NEWLINE_CONSUME)
|
||||
file(STRINGS src/resources/vive_controller.json SVR_VRAPP_VIVE_BINDS NEWLINE_CONSUME)
|
||||
|
||||
configure_file(src/resources/resources.hpp.in src/resources/resources.hpp @ONLY)
|
||||
target_include_directories("${PROJECT_NAME}" PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/src")
|
||||
Submodule
+1
Submodule bindings-provider/openvr added at 9182530513.
@@ -0,0 +1,22 @@
|
||||
#include "logger.hpp"
|
||||
#include "paths.hpp"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_MEAN_AND_LEAN
|
||||
#include <Windows.h>
|
||||
#endif
|
||||
|
||||
Logger::Logger()
|
||||
: log_stream(Paths::getLogPath() / "slimevr-bindings-provider.log",
|
||||
std::ios::out | std::ios::app)
|
||||
#ifdef _WIN32
|
||||
,
|
||||
should_log_to_std_streams(GetConsoleWindow() != nullptr)
|
||||
#endif
|
||||
{
|
||||
}
|
||||
|
||||
Logger &Logger::get() {
|
||||
static Logger logger;
|
||||
return logger;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
|
||||
class Logger {
|
||||
private:
|
||||
std::ofstream log_stream;
|
||||
#ifdef _WIN32
|
||||
bool should_log_to_std_streams;
|
||||
#endif
|
||||
|
||||
template <bool important, typename... Args>
|
||||
void log(std::string_view suffix, std::format_string<Args...> fmt,
|
||||
Args &&...args) {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto time_t = std::chrono::system_clock::to_time_t(now);
|
||||
|
||||
auto s = std::format(fmt, std::forward<Args>(args)...);
|
||||
#ifdef _WIN32
|
||||
if (should_log_to_std_streams) {
|
||||
#endif
|
||||
if constexpr (important)
|
||||
std::cerr << suffix << ' ' << s << '\n';
|
||||
else
|
||||
std::cout << suffix << ' ' << s << '\n';
|
||||
#ifdef _WIN32
|
||||
}
|
||||
#endif
|
||||
|
||||
log_stream << std::put_time(std::localtime(&time_t), "[%F %T]") //
|
||||
<< ' ' << suffix << ' ' << s << '\n';
|
||||
}
|
||||
|
||||
public:
|
||||
Logger();
|
||||
|
||||
template <typename... Args>
|
||||
void debug(std::format_string<Args...> fmt, Args &&...args) {
|
||||
#ifndef NDEBUG
|
||||
log<false>("[DEBUG]", fmt, std::forward<Args>(args)...);
|
||||
#endif
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void info(std::format_string<Args...> fmt, Args &&...args) {
|
||||
log<false>("[INFO]", fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void warning(std::format_string<Args...> fmt, Args &&...args) {
|
||||
log<true>("[WARN]", fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void error(std::format_string<Args...> fmt, Args &&...args) {
|
||||
log<true>("[ERROR]", fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
void flush() {
|
||||
#ifdef _WIN32
|
||||
if (should_log_to_std_streams) {
|
||||
#endif
|
||||
std::cerr.flush();
|
||||
std::cout.flush();
|
||||
#ifdef _WIN32
|
||||
}
|
||||
#endif
|
||||
log_stream.flush();
|
||||
}
|
||||
|
||||
static Logger &get();
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
#include <cassert>
|
||||
#include <csignal>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <tuple>
|
||||
|
||||
// These must be included before Windows.h because of some macro collisions.
|
||||
#include "flatbuffers/flatbuffers.h"
|
||||
#include "solarxr_protocol/generated/all_generated.h"
|
||||
|
||||
#include "logger.hpp"
|
||||
#include "solarxr.hpp"
|
||||
#include "vr_utils.hpp"
|
||||
|
||||
#include "openvr.h"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using namespace solarxr_protocol;
|
||||
|
||||
static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); }
|
||||
|
||||
static void onYawReset(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Yaw, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({msgHeader});
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void onFullReset(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Full, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({msgHeader});
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void onMountingCalibration(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto resetReq =
|
||||
rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, 0, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({msgHeader});
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void onFeetMountingCalibration(SolarXRConnection &conn) {
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
auto bodyParts = fbb.CreateVector(
|
||||
{datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT});
|
||||
auto resetReq =
|
||||
rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, bodyParts, 0.f);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({msgHeader});
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
static void onToggleTracking(SolarXRConnection &conn) {
|
||||
static bool shouldPause = false;
|
||||
flatbuffers::FlatBufferBuilder fbb;
|
||||
|
||||
shouldPause = !shouldPause;
|
||||
auto toggleReq = rpc::CreateSetPauseTrackingRequest(fbb, shouldPause);
|
||||
auto msgHeader = rpc::CreateRpcMessageHeader(
|
||||
fbb, nullptr, rpc::RpcMessage::SetPauseTrackingRequest,
|
||||
toggleReq.Union());
|
||||
|
||||
auto rpcMsgs = fbb.CreateVector({msgHeader});
|
||||
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
|
||||
fbb.Finish(bundle);
|
||||
conn.sendMsg(fbb);
|
||||
}
|
||||
|
||||
sig_atomic_t should_exit = 0;
|
||||
|
||||
static void signal_handler(int signal) {
|
||||
Logger::get().info("Received signal {}", signal);
|
||||
should_exit = 1;
|
||||
}
|
||||
|
||||
int main() {
|
||||
auto &logger = Logger::get();
|
||||
|
||||
try {
|
||||
SolarXRConnection conn;
|
||||
std::unique_ptr<vr::IVRSystem, decltype(&shutdown_vr)> sys{nullptr,
|
||||
shutdown_vr};
|
||||
|
||||
// On vrlink, VR_Init returns
|
||||
// VRInitError_Driver_WirelessHmdNotConnected while the connection
|
||||
// is initialising, so keep calling VR_Init until it ends up
|
||||
// succeeding
|
||||
|
||||
vr::EVRInitError err{vr::VRInitError_Driver_WirelessHmdNotConnected};
|
||||
while (err == vr::VRInitError_Driver_WirelessHmdNotConnected) {
|
||||
sys.reset(vr::VR_Init(&err, vr::VRApplication_Background));
|
||||
if (err == vr::VRInitError_Driver_WirelessHmdNotConnected)
|
||||
std::this_thread::sleep_for(500ms);
|
||||
}
|
||||
|
||||
if (sys == nullptr or err != vr::VRInitError_None) {
|
||||
logger.error("Failed to init OpenVR: {} ({})",
|
||||
vr::VR_GetVRInitErrorAsSymbol(err),
|
||||
vr::VR_GetVRInitErrorAsEnglishDescription(err));
|
||||
return 1;
|
||||
}
|
||||
|
||||
logger.info("Initialised OpenVR, HMD model '{}'",
|
||||
VRUtils::getStringProp(vr::k_unTrackedDeviceIndex_Hmd,
|
||||
vr::Prop_ModelNumber_String)
|
||||
.value_or("<unknown>"));
|
||||
|
||||
vr::IVRApplications *app = vr::VRApplications();
|
||||
vr::IVRInput *input = vr::VRInput();
|
||||
|
||||
auto [appManifestPath, actionManifestPath] = VRUtils::initialiseManifest();
|
||||
|
||||
if (auto err =
|
||||
app->AddApplicationManifest(appManifestPath.string().data(), true);
|
||||
err != vr::VRApplicationError_None) {
|
||||
logger.error("Failed to add application manifest: {}",
|
||||
app->GetApplicationsErrorNameFromEnum(err));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (auto err =
|
||||
input->SetActionManifestPath(actionManifestPath.string().data());
|
||||
err != vr::VRInputError_None) {
|
||||
logger.error("Failed to set action manifest path: {}",
|
||||
std::to_underlying(err));
|
||||
return 1;
|
||||
}
|
||||
|
||||
vr::VRActionSetHandle_t action_set;
|
||||
if (auto err = input->GetActionSetHandle("/actions/main", &action_set);
|
||||
err != vr::VRInputError_None) {
|
||||
logger.error("Failed to get main action set handle: {}",
|
||||
std::to_underlying(err));
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::map<std::string, std::tuple<vr::VRActionHandle_t,
|
||||
std::function<void(SolarXRConnection &)>>>
|
||||
actions{
|
||||
{"/actions/main/in/YawReset",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle, onYawReset)},
|
||||
{"/actions/main/in/FullReset",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle, onFullReset)},
|
||||
{"/actions/main/in/MountingCalibration",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle,
|
||||
onMountingCalibration)},
|
||||
{"/actions/main/in/FeetMountingCalibration",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle,
|
||||
onFeetMountingCalibration)},
|
||||
{"/actions/main/in/ToggleTracking",
|
||||
std::make_tuple(vr::k_ulInvalidActionHandle, onToggleTracking)},
|
||||
};
|
||||
|
||||
for (auto &[name, tuple] : actions) {
|
||||
auto &[handle, _] = tuple;
|
||||
if (auto err = input->GetActionHandle(name.c_str(), &handle);
|
||||
err != vr::VRInputError_None ||
|
||||
handle == vr::k_ulInvalidActionHandle) {
|
||||
logger.warning("Failed to get action handle for action {}: {}", name,
|
||||
std::to_underlying(err));
|
||||
}
|
||||
}
|
||||
|
||||
constexpr auto interval = 1000ms / 30;
|
||||
|
||||
signal(SIGINT, signal_handler);
|
||||
signal(SIGTERM, signal_handler);
|
||||
while (!should_exit) {
|
||||
vr::VREvent_t event{};
|
||||
while (sys->PollNextEvent(&event, sizeof(event))) {
|
||||
switch (event.eventType) {
|
||||
case vr::VREvent_Quit:
|
||||
logger.info("OpenVR runtime requested quit");
|
||||
should_exit = 1;
|
||||
break;
|
||||
case vr::VREvent_Input_BindingLoadFailed: {
|
||||
auto &loadData = event.data.inputBinding;
|
||||
logger.debug("Binding load failed (ulAppContainer={} "
|
||||
"pathMessage={} pathUrl={} pathControllerType={})",
|
||||
loadData.ulAppContainer, loadData.pathMessage,
|
||||
loadData.pathUrl, loadData.pathControllerType);
|
||||
break;
|
||||
}
|
||||
case vr::VREvent_Input_BindingLoadSuccessful: {
|
||||
auto &loadData = event.data.inputBinding;
|
||||
logger.debug("Binding load successful (ulAppContainer={} "
|
||||
"pathMessage={} pathUrl={} pathControllerType={})",
|
||||
loadData.ulAppContainer, loadData.pathMessage,
|
||||
loadData.pathUrl, loadData.pathControllerType);
|
||||
break;
|
||||
}
|
||||
case vr::VREvent_Input_ActionManifestReloaded:
|
||||
logger.debug("Action manifest reloaded");
|
||||
break;
|
||||
case vr::VREvent_Input_ActionManifestLoadFailed: {
|
||||
auto &manifestData = event.data.actionManifest;
|
||||
logger.debug(
|
||||
"Action manifest load failed (pathAppKey={} pathMessage={} "
|
||||
"pathMessageParam={} pathManifestPath={})",
|
||||
manifestData.pathAppKey, manifestData.pathMessage,
|
||||
manifestData.pathMessageParam, manifestData.pathManifestPath);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
vr::VRActiveActionSet_t set{
|
||||
.ulActionSet = action_set,
|
||||
.ulRestrictedToDevice = vr::k_ulInvalidInputValueHandle,
|
||||
.ulSecondaryActionSet = vr::k_ulInvalidActionSetHandle,
|
||||
.nPriority = 0,
|
||||
};
|
||||
if (auto err = input->UpdateActionState(&set, sizeof(set), 1);
|
||||
err != vr::VRInputError_None) {
|
||||
logger.warning("Error when updating action states: {}",
|
||||
std::to_underlying(err));
|
||||
}
|
||||
|
||||
for (auto &[name, tuple] : actions) {
|
||||
auto &[handle, callback] = tuple;
|
||||
vr::InputDigitalActionData_t action_data{};
|
||||
if (auto err = input->GetDigitalActionData(
|
||||
handle, &action_data, sizeof(action_data),
|
||||
vr::k_ulInvalidInputValueHandle);
|
||||
err != vr::VRInputError_None) {
|
||||
logger.warning("Failed to get action state for {} ({}): {}", name,
|
||||
handle, std::to_underlying(err));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (action_data.bActive && action_data.bChanged && action_data.bState) {
|
||||
logger.debug("Action {} triggered", name);
|
||||
callback(conn);
|
||||
}
|
||||
}
|
||||
|
||||
logger.flush();
|
||||
std::this_thread::sleep_for(interval);
|
||||
}
|
||||
|
||||
logger.info("Main loop done");
|
||||
} catch (std::exception &ex) {
|
||||
logger.error("Exception in main: {}", ex.what());
|
||||
logger.flush();
|
||||
return 1;
|
||||
}
|
||||
|
||||
logger.flush();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#include "paths.hpp"
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
fs::path Paths::getDataPath() {
|
||||
fs::path basePath{};
|
||||
|
||||
#if defined(__linux__)
|
||||
if (const char *dataHomeOverride = getenv("XDG_DATA_HOME")) {
|
||||
basePath = dataHomeOverride;
|
||||
} else {
|
||||
const char *homeDir = getenv("HOME");
|
||||
if (homeDir == nullptr)
|
||||
throw std::runtime_error("HOME is unset");
|
||||
|
||||
basePath = fs::path(homeDir) / ".local" / "share";
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
{
|
||||
const char *appData = getenv("APPDATA");
|
||||
if (appData == nullptr)
|
||||
throw std::runtime_error("APPDATA is unset");
|
||||
|
||||
basePath = appData;
|
||||
}
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
return basePath / "dev.slimevr.SlimeVR";
|
||||
}
|
||||
|
||||
fs::path Paths::getLogPath() { return Paths::getDataPath() / "logs"; }
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
|
||||
namespace Paths {
|
||||
// Throws when path cannot be found
|
||||
std::filesystem::path getDataPath() noexcept(false);
|
||||
|
||||
// Throws when path cannot be found
|
||||
std::filesystem::path getLogPath() noexcept(false);
|
||||
} // namespace Paths
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"default_bindings": [
|
||||
{
|
||||
"controller_type": "generic",
|
||||
"binding_url": "generic.json"
|
||||
},
|
||||
{
|
||||
"controller_type": "oculus_touch",
|
||||
"binding_url": "oculus_touch.json"
|
||||
},
|
||||
{
|
||||
"controller_type": "knuckles",
|
||||
"binding_url": "knuckles.json"
|
||||
},
|
||||
{
|
||||
"controller_type": "vive_controller",
|
||||
"binding_url": "vive_controller.json"
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"name": "/actions/main/in/YawReset",
|
||||
"requirement": "optional",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "/actions/main/in/FullReset",
|
||||
"requirement": "optional",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "/actions/main/in/MountingCalibration",
|
||||
"requirement": "optional",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "/actions/main/in/FeetMountingCalibration",
|
||||
"requirement": "optional",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"name": "/actions/main/in/ToggleTracking",
|
||||
"requirement": "optional",
|
||||
"type": "boolean"
|
||||
}
|
||||
],
|
||||
"action_sets": [
|
||||
{
|
||||
"name": "/actions/main",
|
||||
"usage": "leftright"
|
||||
}
|
||||
],
|
||||
"localization": [
|
||||
{
|
||||
"language_tag": "en_us",
|
||||
"/actions/main": "Utility Bindings",
|
||||
"/actions/main/in/YawReset": "Yaw Reset",
|
||||
"/actions/main/in/FullReset": "Full Reset",
|
||||
"/actions/main/in/MountingCalibration": "Mounting Calibration",
|
||||
"/actions/main/in/FeetMountingCalibration": "Feet Mounting Calibration",
|
||||
"/actions/main/in/ToggleTracking": "Toggle Tracking"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "Default Bindings for Generic",
|
||||
"controller_type": "generic",
|
||||
"bindings": {
|
||||
"/actions/main": {
|
||||
"sources": [],
|
||||
"skeleton": [],
|
||||
"haptics": [],
|
||||
"poses": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "Default Bindings for Knuckles",
|
||||
"controller_type": "knuckles",
|
||||
"bindings": {
|
||||
"/actions/main": {
|
||||
"sources": [],
|
||||
"skeleton": [],
|
||||
"haptics": [],
|
||||
"poses": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"source": "builtin",
|
||||
"applications": [{
|
||||
"app_key": "dev.slimevr.BindingsProvider",
|
||||
"is_dashboard_overlay": false,
|
||||
"action_manifest_path": "action_manifest.json",
|
||||
"strings": {
|
||||
"en_us": {
|
||||
"name": "SlimeVR Bindings Provider",
|
||||
"description": "SlimeVR Bindings Provider"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "Default Bindings for Oculus Touch",
|
||||
"controller_type": "oculus_touch",
|
||||
"bindings": {
|
||||
"/actions/main": {
|
||||
"sources": [],
|
||||
"skeleton": [],
|
||||
"haptics": [],
|
||||
"poses": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#cmakedefine SVR_VRAPP_MANIFEST R"(@SVR_VRAPP_MANIFEST@)"
|
||||
#cmakedefine SVR_VRAPP_ACTION_MANIFEST R"(@SVR_VRAPP_ACTION_MANIFEST@)"
|
||||
#cmakedefine SVR_VRAPP_GENERIC_BINDS R"(@SVR_VRAPP_GENERIC_BINDS@)"
|
||||
#cmakedefine SVR_VRAPP_KNUCKLES_BINDS R"(@SVR_VRAPP_KNUCKLES_BINDS@)"
|
||||
#cmakedefine SVR_VRAPP_OCULUS_BINDS R"(@SVR_VRAPP_OCULUS_BINDS@)"
|
||||
#cmakedefine SVR_VRAPP_VIVE_BINDS R"(@SVR_VRAPP_VIVE_BINDS@)"
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "Default Bindings for Vive Wands",
|
||||
"controller_type": "vive_controller",
|
||||
"bindings": {
|
||||
"/actions/main": {
|
||||
"sources": [],
|
||||
"skeleton": [],
|
||||
"haptics": [],
|
||||
"poses": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
#include "solarxr.hpp"
|
||||
#include "logger.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#elif defined(_WIN32)
|
||||
#include <Windows.h>
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
fs::path SolarXRConnection::getSocketPath() {
|
||||
using namespace std::string_view_literals;
|
||||
#if defined(__linux__)
|
||||
#define MAKE_SOCKET_PATH(PATH) \
|
||||
std::make_pair(PATH##sv, static_cast<const char *>(getenv(PATH)))
|
||||
|
||||
constexpr std::string_view socketName = "SlimeVRRpc";
|
||||
std::array<std::pair<std::string_view, const char *>, 4> socketPaths{
|
||||
MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"),
|
||||
MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"),
|
||||
MAKE_SOCKET_PATH("TMPDIR"),
|
||||
{"/tmp", "/tmp"}};
|
||||
|
||||
#undef MAKE_SOCKET_PATH
|
||||
|
||||
for (auto [name, path] : socketPaths) {
|
||||
if (path == nullptr) {
|
||||
Logger::get().info(
|
||||
"Skipping socket directory {} because it doesn't exist", name);
|
||||
continue;
|
||||
}
|
||||
fs::path socketPath = fs::path(path) / socketName;
|
||||
if (fs::exists(socketPath))
|
||||
return socketPath;
|
||||
|
||||
Logger::get().info(
|
||||
"Skipping socket directory {} because socket does not exist", name);
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
throw std::logic_error(
|
||||
"SolarXRConnection::getSocketPath should not be called on Windows");
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
throw std::runtime_error("Failed to find socket directory");
|
||||
}
|
||||
|
||||
SolarXRConnection::SolarXRConnection() {
|
||||
#if defined(__linux__)
|
||||
sockaddr_un addr{};
|
||||
addr.sun_family = AF_UNIX;
|
||||
strcpy(addr.sun_path, getSocketPath().string().data());
|
||||
|
||||
fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd == -1) {
|
||||
throw std::runtime_error(
|
||||
std::format("Failed to create listen socket: {}", strerror(errno)));
|
||||
}
|
||||
|
||||
if (connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
|
||||
int e = errno;
|
||||
close(fd);
|
||||
throw std::runtime_error(std::format("Failed to connect to socket {}: {}",
|
||||
addr.sun_path, strerror(e)));
|
||||
}
|
||||
|
||||
#elif defined(_WIN32)
|
||||
const char *pipeName = R"(\\.\pipe\SlimeVRRpc)";
|
||||
if (!WaitNamedPipe(pipeName, 5000)) {
|
||||
throw std::runtime_error("Timed out waiting for pipe");
|
||||
}
|
||||
|
||||
pipe = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr,
|
||||
OPEN_EXISTING, 0, nullptr);
|
||||
if (pipe == INVALID_HANDLE_VALUE) {
|
||||
throw std::runtime_error(
|
||||
std::format("Unable to open pipe (error={})", GetLastError()));
|
||||
}
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
||||
SolarXRConnection::~SolarXRConnection() {
|
||||
#if defined(__linux__)
|
||||
if (fd != -1)
|
||||
close(fd);
|
||||
#elif defined(_WIN32)
|
||||
if (pipe != INVALID_HANDLE_VALUE)
|
||||
CloseHandle(pipe);
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
||||
void SolarXRConnection::sendMsg(flatbuffers::FlatBufferBuilder &fbb) {
|
||||
// The server expects the total size of the buffer to be written at the
|
||||
// start of the packet, including the first 4 bytes for the size
|
||||
int size = fbb.GetSize() + 4;
|
||||
// This may be wrong on mixed-endianness, but oh well...
|
||||
if constexpr (std::endian::native != std::endian::little)
|
||||
size = std::byteswap(size);
|
||||
|
||||
#if defined(__linux__)
|
||||
if (write(fd, &size, sizeof(size)) == -1) {
|
||||
Logger::get().warning("Failed to write message size to socket: {}",
|
||||
strerror(errno));
|
||||
return;
|
||||
}
|
||||
|
||||
if (write(fd, fbb.GetBufferPointer(), fbb.GetSize()) == -1) {
|
||||
Logger::get().warning("Failed to write message to socket: {}",
|
||||
strerror(errno));
|
||||
return;
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
uint8_t tempBuf[2048];
|
||||
if (fbb.GetSize() > 2048 - 4) {
|
||||
Logger::get().warning("Message is too big for temporary buffer");
|
||||
return;
|
||||
}
|
||||
|
||||
*reinterpret_cast<int *>(&tempBuf[0]) = size;
|
||||
memcpy(&tempBuf[4], fbb.GetBufferPointer(), fbb.GetSize());
|
||||
if (!WriteFile(pipe, tempBuf, fbb.GetSize() + 4, nullptr, nullptr)) {
|
||||
Logger::get().warning("Failed to write message to pipe (error={})",
|
||||
GetLastError());
|
||||
return;
|
||||
}
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define WIN32_MEAN_AND_LEAN
|
||||
#include <Windows.h>
|
||||
#endif
|
||||
|
||||
#include "flatbuffers/flatbuffer_builder.h"
|
||||
|
||||
class SolarXRConnection {
|
||||
private:
|
||||
#if defined(__linux__)
|
||||
int fd{-1};
|
||||
#elif defined(_WIN32)
|
||||
HANDLE pipe{INVALID_HANDLE_VALUE};
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
|
||||
static std::filesystem::path getSocketPath();
|
||||
|
||||
public:
|
||||
SolarXRConnection() noexcept(false);
|
||||
|
||||
~SolarXRConnection();
|
||||
|
||||
void sendMsg(flatbuffers::FlatBufferBuilder &fbb);
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "vr_utils.hpp"
|
||||
#include "logger.hpp"
|
||||
#include "paths.hpp"
|
||||
#include "resources/resources.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <fstream>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
std::optional<std::string>
|
||||
VRUtils::getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
vr::ETrackedDeviceProperty prop) {
|
||||
vr::IVRSystem *sys = vr::VRSystem();
|
||||
vr::ETrackedPropertyError err{vr::TrackedProp_Success};
|
||||
|
||||
uint32_t required_len =
|
||||
sys->GetStringTrackedDeviceProperty(deviceIndex, prop, nullptr, 0, &err);
|
||||
if (err != vr::TrackedProp_BufferTooSmall) {
|
||||
Logger::get().info(
|
||||
"Failed to get size of string property {} for device {}: {}",
|
||||
std::to_underlying(prop), deviceIndex,
|
||||
sys->GetPropErrorNameFromEnum(err));
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string s(required_len - 1, '\0');
|
||||
sys->GetStringTrackedDeviceProperty(deviceIndex, prop, s.data(), required_len,
|
||||
&err);
|
||||
if (err != vr::TrackedProp_Success) {
|
||||
Logger::get().info("Failed to get string property {} for device {}: {}",
|
||||
std::to_underlying(prop), deviceIndex,
|
||||
sys->GetPropErrorNameFromEnum(err));
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
std::tuple<fs::path, fs::path> VRUtils::initialiseManifest() {
|
||||
fs::path manifestDir = Paths::getDataPath() / "bindings-provider";
|
||||
std::error_code ec;
|
||||
fs::create_directories(manifestDir, ec);
|
||||
if (ec) {
|
||||
throw std::runtime_error(
|
||||
std::format("Failed to create manifest folder: {}", ec.message()));
|
||||
}
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
// Make sure the vrmanifest and action manifest are 1st and 2nd respectively
|
||||
// in the array
|
||||
std::array requiredFiles{
|
||||
std::make_pair("manifest.vrmanifest"sv, SVR_VRAPP_MANIFEST),
|
||||
std::make_pair("action_manifest.json"sv, SVR_VRAPP_ACTION_MANIFEST),
|
||||
std::make_pair("generic.json"sv, SVR_VRAPP_GENERIC_BINDS),
|
||||
std::make_pair("knuckles.json"sv, SVR_VRAPP_KNUCKLES_BINDS),
|
||||
std::make_pair("oculus_touch.json"sv, SVR_VRAPP_OCULUS_BINDS),
|
||||
std::make_pair("vive_controller.json"sv, SVR_VRAPP_VIVE_BINDS),
|
||||
};
|
||||
|
||||
for (auto &[name, contents] : requiredFiles) {
|
||||
fs::path path = manifestDir / name;
|
||||
if (!fs::exists(path)) {
|
||||
std::ofstream stream(path);
|
||||
stream << contents;
|
||||
}
|
||||
}
|
||||
|
||||
return {manifestDir / requiredFiles.at(0).first,
|
||||
manifestDir / requiredFiles.at(1).first};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
|
||||
#include "openvr.h"
|
||||
|
||||
namespace VRUtils {
|
||||
std::optional<std::string> getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
|
||||
vr::ETrackedDeviceProperty prop);
|
||||
|
||||
// Returns <app vrmanifest path, action manifest json path>
|
||||
std::tuple<std::filesystem::path, std::filesystem::path> initialiseManifest();
|
||||
} // namespace VRUtils
|
||||
@@ -35,6 +35,10 @@ linux:
|
||||
extraFiles:
|
||||
- from: "../server/desktop/build/libs/slimevr.jar"
|
||||
to: "."
|
||||
- from: "../bindings-provider/build/linux-${arch}/slimevr-bindings-provider"
|
||||
to: "."
|
||||
- from: "../bindings-provider/build/linux-${arch}/libopenvr_api.so"
|
||||
to: "."
|
||||
- from: "./electron/resources/69-slimevr-devices.rules"
|
||||
to: "."
|
||||
icon: "./electron/resources/icons"
|
||||
@@ -59,6 +63,10 @@ win:
|
||||
- from: "../server/core/resources"
|
||||
to: "."
|
||||
filter: ["**/*"]
|
||||
- from: "../bindings-provider/build/${os}-${arch}/Release/SlimeVR-Bindings-Provider.exe"
|
||||
to: "."
|
||||
- from: "../bindings-provider/build/${os}-${arch}/openvr_api.dll"
|
||||
to: "."
|
||||
|
||||
mac:
|
||||
target: dmg
|
||||
|
||||
@@ -404,18 +404,16 @@ const spawnServer = async () => {
|
||||
|
||||
logger.info({ javaBin, serverJar }, 'Found Java and server jar');
|
||||
const platform = getPlatform();
|
||||
const serverWorkdir = getServerDataFolder()
|
||||
|
||||
const serverArgs = ['-Xmx128M', '-jar', serverJar]
|
||||
if (options.steam) serverArgs.push(`--steam`)
|
||||
if (options.install) serverArgs.push(`--install`)
|
||||
if (options.noUdev) serverArgs.push(`--no-udev`)
|
||||
|
||||
serverArgs.push('run')
|
||||
const serverArgs = ['-Xmx128M', '-jar', serverJar];
|
||||
if (options.steam) serverArgs.push(`--steam`);
|
||||
if (options.install) serverArgs.push(`--install`);
|
||||
if (options.noUdev) serverArgs.push(`--no-udev`);
|
||||
|
||||
serverArgs.push('run');
|
||||
|
||||
const serverProcess = spawn(javaBin, serverArgs, {
|
||||
cwd: serverWorkdir,
|
||||
cwd: sharedDir,
|
||||
shell: false,
|
||||
env:
|
||||
platform === 'windows'
|
||||
|
||||
@@ -195,19 +195,20 @@ class VRServer @JvmOverloads constructor(
|
||||
return false
|
||||
}
|
||||
|
||||
// FIXME: Code using this function normally uses this to get the SteamVR driver but
|
||||
// that's because we first save the SteamVR driver bridge and then the feeder in the array.
|
||||
// Not really a great thing to have.
|
||||
@ThreadSafe
|
||||
fun <E : Bridge?> getVRBridge(bridgeClass: Class<E>): E? {
|
||||
fun getVRBridge(pred: (Bridge) -> Boolean): Bridge? {
|
||||
for (bridge in bridges) {
|
||||
if (bridgeClass.isAssignableFrom(bridge.javaClass)) {
|
||||
return bridgeClass.cast(bridge)
|
||||
}
|
||||
if (pred(bridge)) return bridge
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun removeVRBridge(bridge: Bridge) {
|
||||
bridge.stopBridge()
|
||||
bridges.remove(bridge)
|
||||
}
|
||||
|
||||
fun addOnTick(runnable: Runnable) {
|
||||
onTick.add(runnable)
|
||||
}
|
||||
@@ -305,7 +306,11 @@ class VRServer @JvmOverloads constructor(
|
||||
queueTask {
|
||||
humanPoseManager.updateSkeletonModelFromServer()
|
||||
vrcOSCHandler.setHeadTracker(TrackerUtils.getTrackerForSkeleton(trackers, TrackerPosition.HEAD))
|
||||
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
|
||||
|
||||
val bridge = this.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
bridge?.updateShareSettingsAutomatically()
|
||||
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
|
||||
}
|
||||
}
|
||||
@@ -332,7 +337,10 @@ class VRServer @JvmOverloads constructor(
|
||||
queueTask {
|
||||
humanPoseManager.setPauseTracking(pauseTracking, sourceName)
|
||||
// Toggle trackers as they don't toggle when tracking is paused
|
||||
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
|
||||
val bridge = this.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
bridge?.updateShareSettingsAutomatically()
|
||||
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
|
||||
}
|
||||
}
|
||||
@@ -341,7 +349,10 @@ class VRServer @JvmOverloads constructor(
|
||||
queueTask {
|
||||
humanPoseManager.togglePauseTracking(sourceName)
|
||||
// Toggle trackers as they don't toggle when tracking is paused
|
||||
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
|
||||
val bridge = this.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
bridge?.updateShareSettingsAutomatically()
|
||||
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,9 @@ interface Bridge {
|
||||
@VRServerThread
|
||||
fun startBridge()
|
||||
|
||||
@VRServerThread
|
||||
fun stopBridge()
|
||||
|
||||
fun isConnected(): Boolean
|
||||
}
|
||||
|
||||
|
||||
@@ -163,6 +163,9 @@ fun createTapDetectionSettings(
|
||||
tapDetectionConfig.mountingResetTaps,
|
||||
tapDetectionConfig.setupMode,
|
||||
tapDetectionConfig.numberTrackersOverThreshold,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
|
||||
fun createSteamVRSettings(fbb: FlatBufferBuilder, bridge: ISteamVRBridge?): Int {
|
||||
@@ -372,7 +375,9 @@ fun createArmsResetModeSettings(
|
||||
)
|
||||
|
||||
fun createSettingsResponse(fbb: FlatBufferBuilder, server: VRServer): Int {
|
||||
val bridge = server.getVRBridge(ISteamVRBridge::class.java)
|
||||
val bridge = server.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
|
||||
return SettingsResponse
|
||||
.createSettingsResponse(
|
||||
|
||||
@@ -32,8 +32,9 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
|
||||
.message(ChangeSettingsRequest()) as? ChangeSettingsRequest ?: return
|
||||
|
||||
if (req.steamVrTrackers() != null) {
|
||||
val bridge = api.server
|
||||
.getVRBridge(ISteamVRBridge::class.java)
|
||||
val bridge = api.server.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
|
||||
if (bridge != null) {
|
||||
bridge.changeShareSettings(TrackerRole.WAIST, req.steamVrTrackers().waist())
|
||||
@@ -371,8 +372,9 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
|
||||
companion object {
|
||||
fun sendSteamVRUpdatedSettings(api: ProtocolAPI, rpcHandler: RPCHandler) {
|
||||
val fbb = FlatBufferBuilder(32)
|
||||
val bridge: ISteamVRBridge =
|
||||
api.server.getVRBridge(ISteamVRBridge::class.java) ?: return
|
||||
val bridge = api.server.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge ?: return
|
||||
|
||||
val settings = SettingsResponse
|
||||
.createSettingsResponse(
|
||||
|
||||
@@ -273,7 +273,9 @@ class TrackingChecklistManager(private val vrServer: VRServer) : VRCConfigListen
|
||||
}
|
||||
}
|
||||
|
||||
val steamVRBridge = vrServer.getVRBridge(ISteamVRBridge::class.java)
|
||||
val steamVRBridge = vrServer.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
if (steamVRBridge != null) {
|
||||
val steamvrConnected = steamVRBridge.isConnected()
|
||||
updateValidity(
|
||||
|
||||
@@ -231,6 +231,10 @@ class WebSocketVRBridge(
|
||||
start()
|
||||
}
|
||||
|
||||
override fun stopBridge() {
|
||||
stop()
|
||||
}
|
||||
|
||||
override fun isConnected(): Boolean = super.getConnections().isNotEmpty()
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -15,6 +15,7 @@ import dev.slimevr.desktop.platform.SteamVRBridge
|
||||
import dev.slimevr.desktop.platform.linux.UnixSocketBridge
|
||||
import dev.slimevr.desktop.platform.linux.UnixSocketRpcBridge
|
||||
import dev.slimevr.desktop.platform.windows.WindowsNamedPipeBridge
|
||||
import dev.slimevr.desktop.platform.windows.WindowsNamedPipeRpcBridge
|
||||
import dev.slimevr.desktop.serial.DesktopSerialHandler
|
||||
import dev.slimevr.desktop.tracking.trackers.hid.DesktopHIDManager
|
||||
import dev.slimevr.tracking.trackers.Tracker
|
||||
@@ -211,18 +212,26 @@ fun provideBridges(
|
||||
FastList(),
|
||||
),
|
||||
)
|
||||
|
||||
yield(
|
||||
WindowsNamedPipeRpcBridge(
|
||||
server,
|
||||
"""\\.\pipe\SlimeVRRpc""",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
OperatingSystem.LINUX -> {
|
||||
var linuxBridge: SteamVRBridge? = null
|
||||
try {
|
||||
linuxBridge = UnixSocketBridge(
|
||||
server,
|
||||
"steamvr",
|
||||
"SteamVR Driver Bridge",
|
||||
Paths.get(OperatingSystem.socketDirectory, "SlimeVRDriver")
|
||||
.toString(),
|
||||
computedTrackers,
|
||||
yield(
|
||||
UnixSocketBridge(
|
||||
server,
|
||||
"steamvr",
|
||||
"SteamVR Driver Bridge",
|
||||
Paths.get(OperatingSystem.socketDirectory, "SlimeVRDriver")
|
||||
.toString(),
|
||||
computedTrackers,
|
||||
),
|
||||
)
|
||||
} catch (ex: Exception) {
|
||||
LogManager.severe(
|
||||
@@ -230,19 +239,7 @@ fun provideBridges(
|
||||
ex,
|
||||
)
|
||||
}
|
||||
if (linuxBridge != null) {
|
||||
// Close the named socket on shutdown, or otherwise it's not going to get removed
|
||||
Runtime.getRuntime().addShutdownHook(
|
||||
Thread {
|
||||
try {
|
||||
(linuxBridge as? UnixSocketBridge)?.close()
|
||||
} catch (e: Exception) {
|
||||
throw RuntimeException(e)
|
||||
}
|
||||
},
|
||||
)
|
||||
yield(linuxBridge)
|
||||
}
|
||||
|
||||
yield(
|
||||
UnixSocketBridge(
|
||||
server,
|
||||
|
||||
@@ -9,7 +9,6 @@ class Linux {
|
||||
|
||||
fun updateLinux() {
|
||||
updateLinuxSteamVRDriver()
|
||||
feeder()
|
||||
}
|
||||
|
||||
fun updateLinuxSteamVRDriver() {
|
||||
@@ -33,28 +32,7 @@ class Linux {
|
||||
LogManager.info("SteamVR driver successfully installed")
|
||||
}
|
||||
|
||||
fun feeder() {
|
||||
executeShellCommand("chmod", "+x", "$path/$LINUX_FEEDER_DIRECTORY/SlimeVR-Feeder-App")
|
||||
|
||||
val command = if (featureFlags.steam) {
|
||||
arrayOf("steam-runtime-launch-client", "--alongside-steam", "--", "$path/$LINUX_FEEDER_DIRECTORY/SlimeVR-Feeder-App", "--install")
|
||||
} else {
|
||||
arrayOf("$path/$LINUX_FEEDER_DIRECTORY/SlimeVR-Feeder-App", "--install")
|
||||
}
|
||||
val feederOutput = executeShellCommand(*command)
|
||||
if (feederOutput == null) {
|
||||
LogManager.warning("Error installing feeder")
|
||||
return
|
||||
}
|
||||
if (feederOutput.lowercase().contains("manifest is not installed")) {
|
||||
LogManager.warning("Could not install feeder application")
|
||||
} else {
|
||||
LogManager.info("Successfully installed feeder application")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val LINUX_STEAM_DRIVER_DIRECTORY = "slimevr-openvr-driver-x64-linux"
|
||||
private const val LINUX_FEEDER_DIRECTORY = "SlimeVR-Feeder-App-Linux"
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,6 @@ class Windows {
|
||||
|
||||
fun updateWindows() {
|
||||
steamVRDriver()
|
||||
feeder()
|
||||
}
|
||||
|
||||
fun feeder() {
|
||||
val feederOutput = executeShellCommand("${path}\\${WINDOWS_FEEDER_DIRECTORY}\\SlimeVR-Feeder-App.exe", "--install")
|
||||
if (feederOutput == null) {
|
||||
LogManager.warning("Error installing feeder")
|
||||
return
|
||||
}
|
||||
if (feederOutput.lowercase().contains("manifest is not installed")) {
|
||||
LogManager.warning("Could not install feeder application")
|
||||
} else {
|
||||
LogManager.info("Successfully installed feeder application")
|
||||
}
|
||||
}
|
||||
|
||||
fun steamVRDriver() {
|
||||
@@ -57,6 +43,5 @@ class Windows {
|
||||
|
||||
companion object {
|
||||
private const val WINDOWS_STEAMVR_DRIVER_DIRECTORY = "slimevr-openvr-driver-win64"
|
||||
private const val WINDOWS_FEEDER_DIRECTORY = "SlimeVR-Feeder-App-win64"
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ abstract class ProtobufBridge(@JvmField protected val bridgeName: String) : ISte
|
||||
@BridgeThread
|
||||
protected abstract fun sendMessageReal(message: ProtobufMessage?): Boolean
|
||||
|
||||
private var remoteProtocolVersion: Int = 0
|
||||
protected var remoteProtocolVersion: Int = 0
|
||||
|
||||
@BridgeThread
|
||||
protected fun messageReceived(message: ProtobufMessage) {
|
||||
@@ -295,6 +295,6 @@ abstract class ProtobufBridge(@JvmField protected val bridgeName: String) : ISte
|
||||
|
||||
companion object {
|
||||
private const val resetSourceNamePrefix = "ProtobufBridge"
|
||||
private const val PROTOCOL_VERSION = 1
|
||||
private const val PROTOCOL_VERSION = 2
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import dev.slimevr.VRServer
|
||||
import dev.slimevr.VRServer.Companion.getNextLocalTrackerId
|
||||
import dev.slimevr.VRServer.Companion.instance
|
||||
import dev.slimevr.bridge.BridgeThread
|
||||
import dev.slimevr.bridge.ISteamVRBridge
|
||||
import dev.slimevr.config.BridgeConfig
|
||||
import dev.slimevr.desktop.platform.ProtobufMessages.*
|
||||
import dev.slimevr.protocol.rpc.settings.RPCSettingsHandler
|
||||
@@ -14,7 +15,83 @@ import dev.slimevr.tracking.trackers.TrackerRole
|
||||
import dev.slimevr.tracking.trackers.TrackerRole.Companion.getById
|
||||
import dev.slimevr.tracking.trackers.TrackerUtils.getTrackerForSkeleton
|
||||
import dev.slimevr.util.ann.VRServerThread
|
||||
import io.eiren.util.OperatingSystem
|
||||
import io.eiren.util.collections.FastList
|
||||
import io.eiren.util.logging.LogManager
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.Path
|
||||
import kotlin.io.path.exists
|
||||
|
||||
class BindingsProviderManager : Runnable {
|
||||
private var process: Process? = null
|
||||
private var watcherThread: Thread? = null
|
||||
|
||||
private fun getBinaryPath(): Path? {
|
||||
// First we want to try to find it in the working directory, its location on
|
||||
// Steam/Windows/portable.
|
||||
val binaryName = if (OperatingSystem.currentPlatform == OperatingSystem.WINDOWS) {
|
||||
"SlimeVR-Bindings-Provider.exe"
|
||||
} else {
|
||||
"slimevr-bindings-provider"
|
||||
}
|
||||
val workingDir = System.getProperty("user.dir")!!
|
||||
|
||||
val binaryPath = Path(workingDir, binaryName)
|
||||
if (binaryPath.exists()) return binaryPath
|
||||
|
||||
// Then look through PATH to find the binary.
|
||||
// PATH shouldn't be null, but if it is just gracefully fail
|
||||
val path = System.getenv("PATH") ?: return null
|
||||
val pathSeparator = System.getProperty("path.separator")!!
|
||||
for (path in path.split(pathSeparator)) {
|
||||
val binaryPath = Path(path, binaryName)
|
||||
if (binaryPath.exists()) return binaryPath
|
||||
}
|
||||
|
||||
// :(
|
||||
return null
|
||||
}
|
||||
|
||||
fun start() {
|
||||
check(process == null && watcherThread == null) {
|
||||
"BindingsProviderManager already running"
|
||||
}
|
||||
|
||||
val binaryPath = getBinaryPath() ?: throw RuntimeException("Unable to find bindings provider binary")
|
||||
process = ProcessBuilder(binaryPath.toString())
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
LogManager.info("[BindingsProviderManager] Started process")
|
||||
watcherThread = Thread(this, "Bindings provider watcher")
|
||||
watcherThread!!.start()
|
||||
}
|
||||
fun stop() {
|
||||
process?.let {
|
||||
it.destroy()
|
||||
}
|
||||
process = null
|
||||
watcherThread?.interrupt()
|
||||
watcherThread = null
|
||||
}
|
||||
|
||||
override fun run() {
|
||||
try {
|
||||
val interval = 1000L / 30L
|
||||
while (process?.isAlive == true) {
|
||||
Thread.sleep(interval)
|
||||
}
|
||||
|
||||
val exitCode = process?.exitValue()
|
||||
if (exitCode != null) {
|
||||
LogManager.info("[BindingsProviderManager] Process has exited with exit code $exitCode")
|
||||
} else {
|
||||
LogManager.info("[BindingsProviderManager] Process has exited")
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
// Ignore it
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abstract class SteamVRBridge(
|
||||
protected val server: VRServer,
|
||||
@@ -25,6 +102,7 @@ abstract class SteamVRBridge(
|
||||
) : ProtobufBridge(bridgeName),
|
||||
Runnable {
|
||||
protected val runnerThread: Thread = Thread(this, threadName)
|
||||
private var bindingsProviderManager: BindingsProviderManager? = null
|
||||
protected val config: BridgeConfig = server.configManager.vrConfig.getBridge(bridgeSettingsKey)
|
||||
var connected: Boolean = false
|
||||
|
||||
@@ -40,6 +118,13 @@ abstract class SteamVRBridge(
|
||||
runnerThread.start()
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
override fun stopBridge() {
|
||||
bindingsProviderManager?.stop()
|
||||
bindingsProviderManager = null
|
||||
runnerThread.interrupt()
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
override fun getShareSetting(role: TrackerRole): Boolean {
|
||||
for (tr in shareableTrackers) {
|
||||
@@ -150,10 +235,10 @@ abstract class SteamVRBridge(
|
||||
|
||||
// Display name, needsReset and isHmd
|
||||
val displayName: String = trackerAdded.trackerName
|
||||
val isHmd = trackerAdded.trackerId == 0
|
||||
|
||||
// trackerPosition
|
||||
val role = getById(trackerAdded.trackerRole)
|
||||
val isHmd = trackerAdded.trackerId == 0
|
||||
val trackerPosition = if (role != null) {
|
||||
getByTrackerRole(role)
|
||||
} else {
|
||||
@@ -181,6 +266,33 @@ abstract class SteamVRBridge(
|
||||
return tracker
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
override fun versionReceived(versionMessage: Version) {
|
||||
super.versionReceived(versionMessage)
|
||||
if (bridgeSettingsKey == "steamvr" && remoteProtocolVersion >= 2) {
|
||||
instance.queueTask {
|
||||
// Shut off the feeder bridge if the connected driver is recent enough
|
||||
val bridge = instance.getVRBridge {
|
||||
it is ISteamVRBridge && it.getBridgeConfigKey() == "steamvr_feeder"
|
||||
} as? SteamVRBridge
|
||||
bridge?.let {
|
||||
LogManager.info("[$bridgeName] Driver version is new enough, deactivating feeder bridge")
|
||||
instance.removeVRBridge(it)
|
||||
}
|
||||
|
||||
// Start the bindings utility when the driver starts up
|
||||
if (bindingsProviderManager == null) {
|
||||
bindingsProviderManager = BindingsProviderManager()
|
||||
}
|
||||
try {
|
||||
bindingsProviderManager!!.start()
|
||||
} catch (e: Exception) {
|
||||
LogManager.warning("[$bridgeName] Failed to start bindings provider", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Battery Status
|
||||
@VRServerThread
|
||||
override fun writeBatteryUpdate(localTracker: Tracker) {
|
||||
@@ -412,6 +524,7 @@ abstract class SteamVRBridge(
|
||||
|
||||
@BridgeThread
|
||||
protected fun reportDisconnected() {
|
||||
bindingsProviderManager?.stop()
|
||||
connected = false
|
||||
}
|
||||
|
||||
|
||||
+8
-7
@@ -16,10 +16,7 @@ import java.net.StandardProtocolFamily;
|
||||
import java.net.UnixDomainSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.nio.channels.Selector;
|
||||
import java.nio.channels.SelectionKey;
|
||||
import java.nio.channels.*;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@@ -30,6 +27,7 @@ public class UnixSocketBridge extends SteamVRBridge implements AutoCloseable {
|
||||
private final ByteBuffer dst = ByteBuffer.allocate(2048).order(ByteOrder.LITTLE_ENDIAN);
|
||||
private final ByteBuffer src = ByteBuffer.allocate(2048).order(ByteOrder.LITTLE_ENDIAN);
|
||||
|
||||
private File socketFile;
|
||||
private ServerSocketChannel server;
|
||||
private SocketChannel channel;
|
||||
private Selector selector;
|
||||
@@ -47,7 +45,7 @@ public class UnixSocketBridge extends SteamVRBridge implements AutoCloseable {
|
||||
this.socketPath = socketPath;
|
||||
this.socketAddress = UnixDomainSocketAddress.of(socketPath);
|
||||
|
||||
File socketFile = new File(socketPath);
|
||||
socketFile = new File(socketPath);
|
||||
if (socketFile.exists()) {
|
||||
if (SocketUtils.isSocketInUse(socketPath)) {
|
||||
throw new RuntimeException(
|
||||
@@ -110,10 +108,13 @@ public class UnixSocketBridge extends SteamVRBridge implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ClosedByInterruptException e) {
|
||||
// We've been told to stop
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
LogManager.severe("[" + bridgeName + "] Exception in runner thread", e);
|
||||
}
|
||||
|
||||
this.socketFile.delete();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+6
@@ -92,6 +92,12 @@ public class UnixSocketRpcBridge implements dev.slimevr.bridge.Bridge,
|
||||
this.runnerThread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void stopBridge() {
|
||||
this.runnerThread.interrupt();
|
||||
}
|
||||
|
||||
@Override
|
||||
@BridgeThread
|
||||
public void run() {
|
||||
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
package dev.slimevr.desktop.platform.windows;
|
||||
|
||||
import com.sun.jna.Native;
|
||||
import com.sun.jna.platform.win32.*;
|
||||
import com.sun.jna.ptr.IntByReference;
|
||||
import com.sun.jna.win32.W32APIOptions;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
|
||||
|
||||
interface Kernel32IO extends Kernel32 {
|
||||
Kernel32IO INSTANCE = Native.load("kernel32", Kernel32IO.class, W32APIOptions.DEFAULT_OPTIONS);
|
||||
|
||||
boolean GetOverlappedResult(
|
||||
/* [in] */ HANDLE hFile,
|
||||
/* [in] */ WinBase.OVERLAPPED lpOverlapped,
|
||||
/* [out] */ IntByReference lpNumberOfBytesTransferred,
|
||||
/* [in] */ boolean bWait
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
public class WindowsNamedPipe implements AutoCloseable {
|
||||
private static final Kernel32 k32 = Kernel32.INSTANCE;
|
||||
private static final Kernel32IO k32io = Kernel32IO.INSTANCE;
|
||||
private static final Advapi32 adv32 = Advapi32.INSTANCE;
|
||||
|
||||
public interface PipeMessageReader {
|
||||
void onMessage(PipeConnection conn, ByteBuffer buf);
|
||||
}
|
||||
|
||||
public static class PipeConnection implements AutoCloseable {
|
||||
private final String pipeName;
|
||||
private WinNT.HANDLE handle;
|
||||
private PipeState state;
|
||||
|
||||
protected WinNT.HANDLE openEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE readEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE writeEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE rxEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE wakeEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE[] events = new WinNT.HANDLE[] { openEvent, rxEvent, wakeEvent };
|
||||
private final WinBase.OVERLAPPED overlappedOpen = new WinBase.OVERLAPPED();
|
||||
private final WinBase.OVERLAPPED overlappedWrite = new WinBase.OVERLAPPED();
|
||||
private final WinBase.OVERLAPPED overlappedRead = new WinBase.OVERLAPPED();
|
||||
private final WinBase.OVERLAPPED overlappedWait = new WinBase.OVERLAPPED();
|
||||
private final ByteBuffer buf = ByteBuffer.allocate(2048);
|
||||
private final IntByReference bytesWritten = new IntByReference(0);
|
||||
private final IntByReference bytesAvailable = new IntByReference(0);
|
||||
private final IntByReference bytesRead = new IntByReference(0);
|
||||
private boolean pendingWait = false;
|
||||
|
||||
PipeConnection(String pipeName, WinNT.HANDLE pipeHandle) {
|
||||
this.pipeName = pipeName;
|
||||
this.handle = pipeHandle;
|
||||
this.state = PipeState.CREATED;
|
||||
|
||||
// Kick off pipe connection.
|
||||
tryConnect();
|
||||
}
|
||||
|
||||
protected void tryConnect() {
|
||||
overlappedOpen.clear();
|
||||
overlappedOpen.hEvent = openEvent;
|
||||
|
||||
boolean ok = k32.ConnectNamedPipe(handle, overlappedOpen);
|
||||
int err = k32.GetLastError();
|
||||
if (!ok && err != WinError.ERROR_IO_PENDING) {
|
||||
if (!k32io.GetOverlappedResult(handle, overlappedOpen, bytesRead, true)) {
|
||||
setError("ConnectNamedPipe failed: " + err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true when:
|
||||
// Pipe has just been opened.
|
||||
// Pipe is open and we got data.
|
||||
public boolean update(PipeMessageReader reader) {
|
||||
switch (state) {
|
||||
case ERROR: {
|
||||
// Do nothing.
|
||||
return false;
|
||||
}
|
||||
case CREATED: {
|
||||
// Check if any events are signaled.
|
||||
int evIdx = k32.WaitForMultipleObjects(events.length, events, false, 0);
|
||||
if (evIdx == WinError.WAIT_TIMEOUT) {
|
||||
// Do nothing if timed out.
|
||||
return false;
|
||||
}
|
||||
if (evIdx == WinBase.WAIT_FAILED) {
|
||||
setError("Wait failed: " + k32.GetLastError());
|
||||
}
|
||||
|
||||
// Did open succeed?
|
||||
if (evIdx == 0) {
|
||||
LogManager
|
||||
.info("[WindowsNamedPipeConnection] Pipe " + pipeName + " opened");
|
||||
state = PipeState.OPEN;
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case OPEN: {
|
||||
// Did we get data?
|
||||
if (waitForData(0)) {
|
||||
return tryRead(reader);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (state == PipeState.OPEN)
|
||||
disconnect();
|
||||
|
||||
if (wakeEvent != null) {
|
||||
k32.CloseHandle(wakeEvent);
|
||||
wakeEvent = null;
|
||||
}
|
||||
if (rxEvent != null) {
|
||||
k32.CloseHandle(rxEvent);
|
||||
rxEvent = null;
|
||||
}
|
||||
if (writeEvent != null) {
|
||||
k32.CloseHandle(writeEvent);
|
||||
writeEvent = null;
|
||||
}
|
||||
if (readEvent != null) {
|
||||
k32.CloseHandle(readEvent);
|
||||
readEvent = null;
|
||||
}
|
||||
if (openEvent != null) {
|
||||
k32.CloseHandle(openEvent);
|
||||
openEvent = null;
|
||||
}
|
||||
if (handle != null) {
|
||||
k32.CloseHandle(handle);
|
||||
handle = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setError(String err) {
|
||||
pendingWait = false;
|
||||
state = PipeState.ERROR;
|
||||
LogManager
|
||||
.severe("[WindowsNamedPipeConnection] Error on pipe " + pipeName + ": " + err);
|
||||
}
|
||||
|
||||
// Wake up immediately from waitForData.
|
||||
// Could be used by the caller to pump a message queue immediately.
|
||||
public void wakeUp() {
|
||||
k32.SetEvent(wakeEvent);
|
||||
}
|
||||
|
||||
// Try to wait timeoutMs for something to be written to the pipe.
|
||||
public boolean waitForData(int timeoutMs) {
|
||||
if (state != PipeState.OPEN)
|
||||
return false;
|
||||
if (!pendingWait) {
|
||||
overlappedWait.clear();
|
||||
overlappedWait.hEvent = rxEvent;
|
||||
boolean immediate = k32.ReadFile(handle, null, 0, null, overlappedWait);
|
||||
int err = k32.GetLastError();
|
||||
if (!immediate && err != WinError.ERROR_IO_PENDING) {
|
||||
if (err == WinError.ERROR_BROKEN_PIPE || err == WinError.ERROR_NO_DATA) {
|
||||
setError("Pipe closed");
|
||||
} else {
|
||||
setError("ReadFile failed: " + err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
pendingWait = true;
|
||||
}
|
||||
|
||||
// Did we get data?
|
||||
int evIdx = k32.WaitForMultipleObjects(events.length, events, false, timeoutMs);
|
||||
if (evIdx == 1) {
|
||||
// events[0] == overlappedWait.hEvent == rxEvent
|
||||
pendingWait = false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Send a message to the pipe.
|
||||
public boolean sendBuffer(byte[] buffer, int len) {
|
||||
overlappedWrite.clear();
|
||||
overlappedWrite.hEvent = writeEvent;
|
||||
boolean immediate = k32
|
||||
.WriteFile(handle, buffer, len, null, overlappedWrite);
|
||||
int err = k32.GetLastError();
|
||||
if (!immediate && err != WinError.ERROR_IO_PENDING) {
|
||||
setError("WriteFile failed: " + err);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!k32io.GetOverlappedResult(handle, overlappedWrite, bytesWritten, true)) {
|
||||
setError(
|
||||
"sendMessageReal/GetOverlappedResult failed: " + k32.GetLastError()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (bytesWritten.getValue() != len) {
|
||||
setError("Bytes written " + bytesWritten.getValue() + ", expected " + len);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Try to read messages from the buffer into reader.
|
||||
protected boolean tryRead(PipeMessageReader reader) {
|
||||
if (state != PipeState.OPEN) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean anyReceived = false;
|
||||
buf.clear();
|
||||
while (k32.PeekNamedPipe(handle, buf.array(), 4, null, bytesAvailable, null)) {
|
||||
if (bytesAvailable.getValue() < 4) {
|
||||
return anyReceived; // Wait for more data
|
||||
}
|
||||
buf.position(0);
|
||||
buf.order(ByteOrder.LITTLE_ENDIAN);
|
||||
int messageLength = buf.getInt();
|
||||
if (messageLength > 1024) { // Overflow
|
||||
setError("Pipe overflow. Message length: " + messageLength);
|
||||
return anyReceived;
|
||||
}
|
||||
if (bytesAvailable.getValue() < messageLength) {
|
||||
return anyReceived; // Wait for more data
|
||||
}
|
||||
|
||||
overlappedRead.clear();
|
||||
overlappedRead.hEvent = readEvent;
|
||||
buf.position(0);
|
||||
boolean immediate = k32
|
||||
.ReadFile(handle, buf.array(), messageLength, null, overlappedRead);
|
||||
int err = k32.GetLastError();
|
||||
if (!immediate && err != WinError.ERROR_IO_PENDING) {
|
||||
setError("ReadFile failed: " + err);
|
||||
return anyReceived;
|
||||
}
|
||||
|
||||
if (!k32io.GetOverlappedResult(handle, overlappedRead, bytesRead, true)) {
|
||||
setError(
|
||||
"updatePipe/GetOverlappedResult failed: " + k32.GetLastError()
|
||||
);
|
||||
return anyReceived;
|
||||
}
|
||||
|
||||
if (bytesRead.getValue() != messageLength) {
|
||||
setError(
|
||||
"Bytes read " + bytesRead.getValue() + ", expected " + messageLength
|
||||
);
|
||||
return anyReceived;
|
||||
}
|
||||
|
||||
buf.clear();
|
||||
buf.position(4); // skip size
|
||||
buf.limit(messageLength);
|
||||
reader.onMessage(this, buf);
|
||||
anyReceived = true;
|
||||
|
||||
if (state != PipeState.OPEN)
|
||||
return anyReceived;
|
||||
}
|
||||
|
||||
int err = k32.GetLastError();
|
||||
if (err == WinError.ERROR_BROKEN_PIPE) {
|
||||
setError("Pipe closed");
|
||||
} else {
|
||||
setError("Pipe error: " + err);
|
||||
}
|
||||
return anyReceived;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (!k32.DisconnectNamedPipe(handle)) {
|
||||
LogManager
|
||||
.warning(
|
||||
"[WindowsNamedPipeConnection] Disconnect failed: " + k32.GetLastError()
|
||||
);
|
||||
}
|
||||
|
||||
state = PipeState.CREATED;
|
||||
tryConnect();
|
||||
}
|
||||
|
||||
public PipeState getState() {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
protected final String pipeName;
|
||||
private final PipeConnection[] pipeConnections;
|
||||
|
||||
public WindowsNamedPipe(String pipeName, int maxConnections) throws IOException {
|
||||
this.pipeName = pipeName;
|
||||
this.pipeConnections = new PipeConnection[maxConnections];
|
||||
|
||||
try {
|
||||
WinNT.SECURITY_DESCRIPTOR descriptor = new WinNT.SECURITY_DESCRIPTOR(64 * 1024);
|
||||
adv32.InitializeSecurityDescriptor(descriptor, WinNT.SECURITY_DESCRIPTOR_REVISION);
|
||||
adv32.SetSecurityDescriptorDacl(descriptor, true, null, false);
|
||||
adv32
|
||||
.SetSecurityDescriptorControl(
|
||||
descriptor,
|
||||
(short) WinNT.SE_DACL_PROTECTED,
|
||||
(short) WinNT.SE_DACL_PROTECTED
|
||||
);
|
||||
|
||||
WinBase.SECURITY_ATTRIBUTES attributes = new WinBase.SECURITY_ATTRIBUTES();
|
||||
attributes.lpSecurityDescriptor = descriptor.getPointer();
|
||||
attributes.bInheritHandle = false;
|
||||
|
||||
for (int i = 0; i < maxConnections; i++) {
|
||||
WinNT.HANDLE pipeHandle = k32
|
||||
.CreateNamedPipe(
|
||||
pipeName,
|
||||
WinBase.PIPE_ACCESS_DUPLEX | WinNT.FILE_FLAG_OVERLAPPED, // dwOpenMode
|
||||
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT, // dwPipeMode
|
||||
maxConnections, // nMaxInstances,
|
||||
1024 * 16, // nOutBufferSize,
|
||||
1024 * 16, // nInBufferSize,
|
||||
0, // nDefaultTimeOut,
|
||||
attributes // lpSecurityAttributes
|
||||
);
|
||||
if (WinBase.INVALID_HANDLE_VALUE.equals(pipeHandle)) {
|
||||
throw new IOException(
|
||||
"Failed to open " + pipeName + " pipe: " + k32.GetLastError()
|
||||
);
|
||||
}
|
||||
this.pipeConnections[i] = new PipeConnection(pipeName, pipeHandle);
|
||||
}
|
||||
LogManager.info("[WindowsNamedPipe] Pipe " + pipeName + " created");
|
||||
|
||||
} catch (IOException e) {
|
||||
for (PipeConnection conn : this.pipeConnections) {
|
||||
if (conn != null)
|
||||
conn.close();
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public PipeConnection tryAccept() {
|
||||
for (PipeConnection conn : this.pipeConnections) {
|
||||
if (conn.getState() == PipeState.CREATED && conn.update(null)) {
|
||||
// We got the pipe.
|
||||
return conn;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
for (PipeConnection pipeConnection : this.pipeConnections) {
|
||||
pipeConnection.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
-241
@@ -2,11 +2,6 @@ package dev.slimevr.desktop.platform.windows;
|
||||
|
||||
import com.google.protobuf.CodedOutputStream;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.sun.jna.Native;
|
||||
import com.sun.jna.platform.win32.*;
|
||||
import com.sun.jna.platform.win32.Kernel32;
|
||||
import com.sun.jna.ptr.IntByReference;
|
||||
import com.sun.jna.win32.W32APIOptions;
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.bridge.BridgeThread;
|
||||
import dev.slimevr.desktop.platform.ProtobufMessages.ProtobufMessage;
|
||||
@@ -17,44 +12,17 @@ import io.eiren.util.logging.LogManager;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
interface Kernel32IO extends Kernel32 {
|
||||
Kernel32IO INSTANCE = Native.load("kernel32", Kernel32IO.class, W32APIOptions.DEFAULT_OPTIONS);
|
||||
|
||||
boolean GetOverlappedResult(
|
||||
/* [in] */ HANDLE hFile,
|
||||
/* [in] */ WinBase.OVERLAPPED lpOverlapped,
|
||||
/* [out] */ IntByReference lpNumberOfBytesTransferred,
|
||||
/* [in] */ boolean bWait
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
public class WindowsNamedPipeBridge extends SteamVRBridge {
|
||||
private static final Kernel32 k32 = Kernel32.INSTANCE;
|
||||
private static final Kernel32IO k32io = Kernel32IO.INSTANCE;
|
||||
private static final Advapi32 adv32 = Advapi32.INSTANCE;
|
||||
|
||||
public class WindowsNamedPipeBridge extends SteamVRBridge
|
||||
implements WindowsNamedPipe.PipeMessageReader {
|
||||
protected final String pipeName;
|
||||
protected final String bridgeSettingsKey;
|
||||
private final byte[] buffArray = new byte[2048];
|
||||
protected WindowsPipe pipe;
|
||||
protected WinNT.HANDLE openEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE readEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE writeEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE rxEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE txEvent = k32.CreateEvent(null, false, false, null);
|
||||
protected WinNT.HANDLE[] events = new WinNT.HANDLE[] { rxEvent, txEvent };
|
||||
private final WinBase.OVERLAPPED overlappedOpen = new WinBase.OVERLAPPED();
|
||||
private final WinBase.OVERLAPPED overlappedWrite = new WinBase.OVERLAPPED();
|
||||
private final WinBase.OVERLAPPED overlappedRead = new WinBase.OVERLAPPED();
|
||||
private final WinBase.OVERLAPPED overlappedWait = new WinBase.OVERLAPPED();
|
||||
private final IntByReference bytesWritten = new IntByReference(0);
|
||||
private final IntByReference bytesAvailable = new IntByReference(0);
|
||||
private final IntByReference bytesRead = new IntByReference(0);
|
||||
private boolean pendingWait = false;
|
||||
protected WindowsNamedPipe pipe = null;
|
||||
protected WindowsNamedPipe.PipeConnection connection = null;
|
||||
private final byte[] buf = new byte[2048];
|
||||
|
||||
public WindowsNamedPipeBridge(
|
||||
VRServer server,
|
||||
@@ -63,266 +31,115 @@ public class WindowsNamedPipeBridge extends SteamVRBridge {
|
||||
String pipeName,
|
||||
List<Tracker> shareableTrackers
|
||||
) {
|
||||
super(server, "Named pipe thread", bridgeName, bridgeSettingsKey, shareableTrackers);
|
||||
super(
|
||||
server,
|
||||
bridgeName + " named pipe thread",
|
||||
bridgeName,
|
||||
bridgeSettingsKey,
|
||||
shareableTrackers
|
||||
);
|
||||
this.pipeName = pipeName;
|
||||
this.bridgeSettingsKey = bridgeSettingsKey;
|
||||
overlappedWait.hEvent = rxEvent;
|
||||
}
|
||||
|
||||
@Override
|
||||
@BridgeThread
|
||||
public void run() {
|
||||
try {
|
||||
createPipe();
|
||||
pipe = new WindowsNamedPipe(this.pipeName, 1);
|
||||
while (true) {
|
||||
boolean pipesUpdated = false;
|
||||
if (pipe.state == PipeState.CREATED) {
|
||||
if (connection == null) {
|
||||
// Report that our pipe is disconnected right now
|
||||
reportDisconnected();
|
||||
tryOpeningPipe(pipe);
|
||||
if ((connection = pipe.tryAccept()) != null)
|
||||
VRServer.Companion.getInstance().queueTask(this::reconnected);
|
||||
}
|
||||
if (pipe.state == PipeState.OPEN) {
|
||||
pipesUpdated = updatePipe();
|
||||
if (pipesUpdated) {
|
||||
reportConnected();
|
||||
if (connection != null) {
|
||||
if (connection.getState() == PipeState.OPEN) {
|
||||
pipesUpdated = connection.update(this);
|
||||
if (pipesUpdated) {
|
||||
reportConnected();
|
||||
}
|
||||
updateMessageQueue();
|
||||
}
|
||||
if (connection.getState() == PipeState.ERROR) {
|
||||
connection.disconnect();
|
||||
connection = null;
|
||||
disconnected();
|
||||
}
|
||||
updateMessageQueue();
|
||||
}
|
||||
if (pipe.state == PipeState.ERROR) {
|
||||
resetPipe();
|
||||
}
|
||||
if (!pipesUpdated) {
|
||||
if (pipe.state == PipeState.OPEN) {
|
||||
waitForData(10);
|
||||
if (connection != null && connection.getState() == PipeState.OPEN) {
|
||||
connection.waitForData(10);
|
||||
} else {
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
// Do nothing.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
LogManager.severe("[" + bridgeName + "] Exception in runner thread", e);
|
||||
}
|
||||
pipe.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
@ThreadSafe
|
||||
protected void signalSend() {
|
||||
k32.SetEvent(txEvent);
|
||||
if (connection != null)
|
||||
connection.wakeUp();
|
||||
}
|
||||
|
||||
@BridgeThread
|
||||
private void waitForData(int timeoutMs) {
|
||||
if (pipe.state != PipeState.OPEN)
|
||||
@Override
|
||||
public void onMessage(WindowsNamedPipe.PipeConnection connection, ByteBuffer buf) {
|
||||
if (this.connection != connection) {
|
||||
LogManager
|
||||
.severe("[" + bridgeName + "] Got message from connection we don't know about");
|
||||
return;
|
||||
if (!pendingWait) {
|
||||
k32.ReadFile(pipe.pipeHandle, null, 0, null, overlappedWait);
|
||||
pendingWait = true;
|
||||
}
|
||||
int evIdx = k32.WaitForMultipleObjects(events.length, events, false, timeoutMs);
|
||||
if (evIdx == 0) {
|
||||
// events[0] == overlappedWait.hEvent == rxEvent
|
||||
pendingWait = false;
|
||||
|
||||
try {
|
||||
ProtobufMessage message = ProtobufMessage
|
||||
.parser()
|
||||
.parseFrom(buf);
|
||||
messageReceived(message);
|
||||
} catch (InvalidProtocolBufferException parseEx) {
|
||||
LogManager.severe("[" + bridgeName + "] Failed to parse message", parseEx);
|
||||
connection.setError("Failed to parse message");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@BridgeThread
|
||||
protected boolean sendMessageReal(ProtobufMessage message) {
|
||||
if (pipe.state != PipeState.OPEN) {
|
||||
if (connection == null || connection.getState() != PipeState.OPEN) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
int size = message.getSerializedSize();
|
||||
CodedOutputStream os = CodedOutputStream.newInstance(buffArray, 4, size);
|
||||
CodedOutputStream os = CodedOutputStream.newInstance(buf, 4, size);
|
||||
message.writeTo(os);
|
||||
size += 4;
|
||||
buffArray[0] = (byte) (size & 0xFF);
|
||||
buffArray[1] = (byte) ((size >> 8) & 0xFF);
|
||||
buffArray[2] = (byte) ((size >> 16) & 0xFF);
|
||||
buffArray[3] = (byte) ((size >> 24) & 0xFF);
|
||||
|
||||
overlappedWrite.clear();
|
||||
overlappedWrite.hEvent = writeEvent;
|
||||
boolean immediate = k32
|
||||
.WriteFile(pipe.pipeHandle, buffArray, size, null, overlappedWrite);
|
||||
int err = k32.GetLastError();
|
||||
if (!immediate && err != WinError.ERROR_IO_PENDING) {
|
||||
setPipeError("WriteFile failed: " + err);
|
||||
return false;
|
||||
}
|
||||
buf[0] = (byte) (size & 0xFF);
|
||||
buf[1] = (byte) ((size >> 8) & 0xFF);
|
||||
buf[2] = (byte) ((size >> 16) & 0xFF);
|
||||
buf[3] = (byte) ((size >> 24) & 0xFF);
|
||||
|
||||
if (!k32io.GetOverlappedResult(pipe.pipeHandle, overlappedWrite, bytesWritten, true)) {
|
||||
setPipeError(
|
||||
"sendMessageReal/GetOverlappedResult failed: " + k32.GetLastError()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (bytesWritten.getValue() != size) {
|
||||
setPipeError("Bytes written " + bytesWritten.getValue() + ", expected " + size);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return connection.sendBuffer(buf, size);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean updatePipe() throws IOException {
|
||||
if (pipe.state != PipeState.OPEN) {
|
||||
return false;
|
||||
}
|
||||
boolean readAnything = false;
|
||||
while (k32.PeekNamedPipe(pipe.pipeHandle, buffArray, 4, null, bytesAvailable, null)) {
|
||||
if (bytesAvailable.getValue() < 4) {
|
||||
return readAnything; // Wait for more data
|
||||
}
|
||||
int messageLength = (Byte.toUnsignedInt(buffArray[3]) << 24)
|
||||
| (Byte.toUnsignedInt(buffArray[2]) << 16)
|
||||
| (Byte.toUnsignedInt(buffArray[1]) << 8)
|
||||
| Byte.toUnsignedInt(buffArray[0]);
|
||||
if (messageLength > 1024) { // Overflow
|
||||
setPipeError("Pipe overflow. Message length: " + messageLength);
|
||||
return readAnything;
|
||||
}
|
||||
if (bytesAvailable.getValue() < messageLength) {
|
||||
return readAnything; // Wait for more data
|
||||
}
|
||||
|
||||
overlappedRead.clear();
|
||||
overlappedRead.hEvent = readEvent;
|
||||
boolean immediate = k32
|
||||
.ReadFile(pipe.pipeHandle, buffArray, messageLength, null, overlappedRead);
|
||||
int err = k32.GetLastError();
|
||||
if (!immediate && err != WinError.ERROR_IO_PENDING) {
|
||||
setPipeError("ReadFile failed: " + err);
|
||||
return readAnything;
|
||||
}
|
||||
|
||||
if (!k32io.GetOverlappedResult(pipe.pipeHandle, overlappedRead, bytesRead, true)) {
|
||||
setPipeError(
|
||||
"updatePipe/GetOverlappedResult failed: " + k32.GetLastError()
|
||||
);
|
||||
return readAnything;
|
||||
}
|
||||
|
||||
if (bytesRead.getValue() != messageLength) {
|
||||
setPipeError(
|
||||
"Bytes read " + bytesRead.getValue() + ", expected " + messageLength
|
||||
);
|
||||
return readAnything;
|
||||
}
|
||||
|
||||
try {
|
||||
ProtobufMessage message = ProtobufMessage
|
||||
.parser()
|
||||
.parseFrom(buffArray, 4, messageLength - 4);
|
||||
messageReceived(message);
|
||||
readAnything = true;
|
||||
} catch (InvalidProtocolBufferException parseEx) {
|
||||
parseEx.printStackTrace();
|
||||
setPipeError("Failed to parse message: " + parseEx.getMessage());
|
||||
return readAnything;
|
||||
}
|
||||
}
|
||||
|
||||
int err = k32.GetLastError();
|
||||
if (err == WinError.ERROR_BROKEN_PIPE) {
|
||||
setPipeError("Pipe closed");
|
||||
} else {
|
||||
setPipeError("Pipe error: " + err);
|
||||
}
|
||||
return readAnything;
|
||||
}
|
||||
|
||||
private void setPipeError(String message) {
|
||||
pipe.state = PipeState.ERROR;
|
||||
LogManager.severe("[" + bridgeName + "] " + message);
|
||||
}
|
||||
|
||||
private void resetPipe() {
|
||||
WindowsPipe.safeDisconnect(pipe);
|
||||
pipe.state = PipeState.CREATED;
|
||||
VRServer.Companion.getInstance().queueTask(this::disconnected);
|
||||
}
|
||||
|
||||
private void createPipe() throws IOException {
|
||||
try {
|
||||
WinNT.SECURITY_DESCRIPTOR descriptor = new WinNT.SECURITY_DESCRIPTOR(64 * 1024);
|
||||
adv32.InitializeSecurityDescriptor(descriptor, WinNT.SECURITY_DESCRIPTOR_REVISION);
|
||||
adv32.SetSecurityDescriptorDacl(descriptor, true, null, false);
|
||||
adv32
|
||||
.SetSecurityDescriptorControl(
|
||||
descriptor,
|
||||
(short) WinNT.SE_DACL_PROTECTED,
|
||||
(short) WinNT.SE_DACL_PROTECTED
|
||||
);
|
||||
|
||||
WinBase.SECURITY_ATTRIBUTES attributes = new WinBase.SECURITY_ATTRIBUTES();
|
||||
attributes.lpSecurityDescriptor = descriptor.getPointer();
|
||||
attributes.bInheritHandle = false;
|
||||
|
||||
pipe = new WindowsPipe(
|
||||
k32
|
||||
.CreateNamedPipe(
|
||||
pipeName,
|
||||
WinBase.PIPE_ACCESS_DUPLEX | WinNT.FILE_FLAG_OVERLAPPED, // dwOpenMode
|
||||
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT, // dwPipeMode
|
||||
1, // nMaxInstances,
|
||||
1024 * 16, // nOutBufferSize,
|
||||
1024 * 16, // nInBufferSize,
|
||||
0, // nDefaultTimeOut,
|
||||
attributes // lpSecurityAttributes
|
||||
),
|
||||
pipeName
|
||||
);
|
||||
LogManager.info("[" + bridgeName + "] Pipe " + pipe.name + " created");
|
||||
if (WinBase.INVALID_HANDLE_VALUE.equals(pipe.pipeHandle)) {
|
||||
throw new IOException("Can't open " + pipeName + " pipe: " + k32.GetLastError());
|
||||
}
|
||||
LogManager.info("[" + bridgeName + "] Pipes are created");
|
||||
} catch (IOException e) {
|
||||
WindowsPipe.safeDisconnect(pipe);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tryOpeningPipe(WindowsPipe pipe) {
|
||||
overlappedOpen.clear();
|
||||
overlappedOpen.hEvent = openEvent;
|
||||
|
||||
boolean ok = k32.ConnectNamedPipe(pipe.pipeHandle, overlappedOpen);
|
||||
int err = k32.GetLastError();
|
||||
if (!ok && err != WinError.ERROR_PIPE_CONNECTED) {
|
||||
if (err != WinError.ERROR_IO_PENDING) {
|
||||
setPipeError("ConnectNamedPipe failed: " + err);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!k32io.GetOverlappedResult(pipe.pipeHandle, overlappedOpen, bytesRead, true)) {
|
||||
setPipeError(
|
||||
"tryOpeningPipe/GetOverlappedResult failed: " + k32.GetLastError()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
pipe.state = PipeState.OPEN;
|
||||
LogManager.info("[" + bridgeName + "] Pipe " + pipe.name + " is open");
|
||||
VRServer.Companion.getInstance().queueTask(this::reconnected);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return pipe != null && pipe.state == PipeState.OPEN;
|
||||
return connection != null && connection.getState() == PipeState.OPEN;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package dev.slimevr.desktop.platform.windows;
|
||||
|
||||
import dev.slimevr.VRServer;
|
||||
import dev.slimevr.bridge.BridgeThread;
|
||||
import dev.slimevr.protocol.GenericConnection;
|
||||
import dev.slimevr.protocol.ProtocolAPI;
|
||||
import dev.slimevr.tracking.trackers.Tracker;
|
||||
import dev.slimevr.util.ann.VRServerThread;
|
||||
import io.eiren.util.collections.FastList;
|
||||
import io.eiren.util.logging.LogManager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
|
||||
public class WindowsNamedPipeRpcBridge implements WindowsNamedPipe.PipeMessageReader,
|
||||
dev.slimevr.bridge.Bridge, dev.slimevr.protocol.ProtocolAPIServer, Runnable, AutoCloseable {
|
||||
private static final int maxConnections = 16;
|
||||
private final Thread runnerThread = new Thread(this, "Named pipe RPC thread");
|
||||
private final String pipePath;
|
||||
private final ProtocolAPI protocolAPI;
|
||||
private WindowsNamedPipe pipe;
|
||||
private FastList<WindowsNamedPipeRpcConnection> connections = new FastList(maxConnections);
|
||||
|
||||
public WindowsNamedPipeRpcBridge(VRServer server, String pipePath) {
|
||||
this.pipePath = pipePath;
|
||||
this.protocolAPI = server.protocolAPI;
|
||||
|
||||
server.protocolAPI.registerAPIServer(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
@BridgeThread
|
||||
public void run() {
|
||||
try {
|
||||
this.pipe = new WindowsNamedPipe(pipePath, maxConnections);
|
||||
FastList<WindowsNamedPipeRpcConnection> removedConnections = new FastList(
|
||||
maxConnections
|
||||
);
|
||||
while (true) {
|
||||
WindowsNamedPipe.PipeConnection newConnection = this.pipe.tryAccept();
|
||||
if (newConnection != null) {
|
||||
this.connections.add(new WindowsNamedPipeRpcConnection(newConnection));
|
||||
}
|
||||
|
||||
for (WindowsNamedPipeRpcConnection connection : this.connections) {
|
||||
if (connection.getState() == PipeState.OPEN) {
|
||||
connection.update(this);
|
||||
}
|
||||
|
||||
if (connection.getState() == PipeState.ERROR) {
|
||||
connection.disconnect();
|
||||
removedConnections.add(connection);
|
||||
}
|
||||
}
|
||||
|
||||
this.connections.removeAll(removedConnections);
|
||||
removedConnections.clear();
|
||||
Thread.sleep(2);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LogManager.severe("[SolarXR RPC Bridge] Exception in runner thread", e);
|
||||
} catch (InterruptedException e) {
|
||||
// Do nothing.
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@BridgeThread
|
||||
public void onMessage(WindowsNamedPipe.PipeConnection conn, ByteBuffer buf) {
|
||||
for (WindowsNamedPipeRpcConnection connection : this.connections) {
|
||||
if (connection.getConnection() == conn) {
|
||||
this.protocolAPI.onMessage(connection, buf);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
LogManager.severe("[SolarXR RPC Bridge] Got message from connection we don't know about");
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void dataRead() {
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void dataWrite() {
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void addSharedTracker(Tracker tracker) {
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void removeSharedTracker(Tracker tracker) {
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void startBridge() {
|
||||
this.runnerThread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
@VRServerThread
|
||||
public void stopBridge() {
|
||||
this.runnerThread.interrupt();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
this.connections.clear();
|
||||
if (this.pipe != null)
|
||||
this.pipe.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return !this.connections.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.stream.Stream<GenericConnection> getApiConnections() {
|
||||
return this.connections.stream().map(conn -> (GenericConnection) conn);
|
||||
}
|
||||
}
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package dev.slimevr.desktop.platform.windows;
|
||||
|
||||
import dev.slimevr.protocol.ConnectionContext;
|
||||
import dev.slimevr.protocol.GenericConnection;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
public class WindowsNamedPipeRpcConnection implements GenericConnection {
|
||||
private final UUID id;
|
||||
private final ConnectionContext context;
|
||||
private final WindowsNamedPipe.PipeConnection connection;
|
||||
|
||||
WindowsNamedPipeRpcConnection(WindowsNamedPipe.PipeConnection connection) {
|
||||
this.id = UUID.randomUUID();
|
||||
this.context = new ConnectionContext();
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getConnectionId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConnectionContext getContext() {
|
||||
return this.context;
|
||||
}
|
||||
|
||||
public boolean update(WindowsNamedPipe.PipeMessageReader reader) {
|
||||
return this.connection.update(reader);
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
this.connection.disconnect();
|
||||
}
|
||||
|
||||
public PipeState getState() {
|
||||
return this.connection.getState();
|
||||
}
|
||||
|
||||
public WindowsNamedPipe.PipeConnection getConnection() {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ByteBuffer bytes) {
|
||||
if (this.connection.getState() != PipeState.OPEN)
|
||||
return;
|
||||
|
||||
ByteBuffer src = ByteBuffer.allocate(4 + bytes.remaining());
|
||||
src.order(ByteOrder.LITTLE_ENDIAN);
|
||||
src.putInt(4 + bytes.remaining());
|
||||
src.put(bytes);
|
||||
src.flip();
|
||||
synchronized (this) {
|
||||
this.connection.sendBuffer(bytes.array(), bytes.remaining());
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule solarxr-protocol updated: 740ead6df2...5d572629c9.
Reference in new issue
Block a user