diff --git a/bindings-provider/CMakeLists.txt b/bindings-provider/CMakeLists.txt index e40667130..c6c76fd86 100644 --- a/bindings-provider/CMakeLists.txt +++ b/bindings-provider/CMakeLists.txt @@ -42,7 +42,8 @@ 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/bridge/BridgeClient.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/bridge/BridgeTransport.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/src/vr_utils.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp" ) diff --git a/bindings-provider/src/bridge/BridgeClient.cpp b/bindings-provider/src/bridge/BridgeClient.cpp new file mode 100644 index 000000000..8e67b19fb --- /dev/null +++ b/bindings-provider/src/bridge/BridgeClient.cpp @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors +#include "BridgeClient.hpp" +#include "BridgeTransport.hpp" + +#include + +using namespace std::literals::chrono_literals; +namespace fs = std::filesystem; + +void BridgeClient::CreateConnection() { + fs::path path = GetSocketPath(); + + Socket fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd == InvalidSocket) { + int err = GetLastSocketError(); + throw std::system_error(err, std::system_category(), "socket() failed"); + } + + if (last_path_ != path) { + Logger::get().info("Trying to connect to socket {}", path.string()); + last_path_ = path; + } + + struct sockaddr_un addr{ + .sun_family = AF_UNIX, + }; + + const std::u8string path_str = path.u8string(); + if (path_str.size() > std::size(addr.sun_path) - 1) { + CloseSocket(fd); + throw std::runtime_error("Socket path too long to fit in sun_path"); + } + memcpy(addr.sun_path, path_str.data(), path_str.size() + 1); + + int ret = connect(fd, reinterpret_cast(&addr), sizeof(addr)); + if (ret == SocketError) { + int err = GetLastSocketError(); + CloseSocket(fd); + throw std::system_error(err, std::system_category(), "connect() failed"); + } + + Logger::get().info("Connected to {}", path.string()); + + ret = SetNonBlocking(fd); + if (ret == SocketError) { + int err = GetLastSocketError(); + Logger::get().warning("Failed to set socket into non-blocking mode: {}", std::error_code(err, std::system_category()).message()); + } + + fd_ = fd; +} diff --git a/bindings-provider/src/bridge/BridgeClient.hpp b/bindings-provider/src/bridge/BridgeClient.hpp new file mode 100644 index 000000000..bdd3ca89e --- /dev/null +++ b/bindings-provider/src/bridge/BridgeClient.hpp @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors +#pragma once + +#include "BridgeTransport.hpp" + +/** + * @brief Client implementation of @ref BridgeTransport for communication with SlimeVR Server using unix sockets. + * + * @copydoc BridgeTransport + */ +class BridgeClient : public BridgeTransport { +public: + using BridgeTransport::BridgeTransport; + +private: + void CreateConnection() override; + + std::filesystem::path last_path_; +}; diff --git a/bindings-provider/src/bridge/BridgeTransport.cpp b/bindings-provider/src/bridge/BridgeTransport.cpp new file mode 100644 index 000000000..7bdf8b49b --- /dev/null +++ b/bindings-provider/src/bridge/BridgeTransport.cpp @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors +#include "BridgeTransport.hpp" +#include "Endianness.hpp" + +#include +#include + +#ifdef _WIN32 +#include +#endif + +using namespace std::chrono_literals; +namespace fs = std::filesystem; + +#define UNIX_XDG_DATA_HOME_DEFAULT ".local/share/" +#define SLIMEVR_IDENTIFIER "dev.slimevr.SlimeVR" +#define UNIX_DEFAULT_TMP_DIR "/tmp" +#define SOCKET_NAME "SlimeVRRpc" + +void BridgeTransport::Stop() { + if (!thread_.joinable() && !reconnect_thread_.joinable()) + return; + Logger::get().info("stopping"); + StopAsync(); + thread_ = std::jthread(); + reconnect_thread_ = std::jthread(); +} + +void BridgeTransport::StopAsync() { + thread_.request_stop(); + reconnect_thread_.request_stop(); + cv_.notify_all(); +} + +fs::path BridgeTransport::GetSocketPath() { + std::vector paths = {}; + + if (const char *dir_override = std::getenv("SLIMEVR_SOCKET_DIR")) { + paths.push_back(fs::path(dir_override) / SOCKET_NAME); + } + +#ifndef _WIN32 + if (const char *xdg_runtime = std::getenv("XDG_RUNTIME_DIR")) { + paths.push_back(fs::path(xdg_runtime) / SOCKET_NAME); + } + + if (const char *xdg_data = std::getenv("XDG_DATA_HOME")) { + paths.push_back(fs::path(xdg_data) / SLIMEVR_IDENTIFIER / SOCKET_NAME); + } + + if (const char *home = std::getenv("HOME")) { + paths.push_back(fs::path(home) / UNIX_XDG_DATA_HOME_DEFAULT / SLIMEVR_IDENTIFIER / SOCKET_NAME); + } +#endif + + std::error_code ec; + for (auto path : paths) { + if (fs::exists(path, ec) +#ifdef _WIN32 + || ec.value() == ERROR_CANT_ACCESS_FILE // Windows moment??? +#endif + ) { + return path; + } + } + +#ifdef _WIN32 + // This should work as long as the user's machine does not have + // the java.io.tmpdir system property overriden. + WCHAR tmp_dir[MAX_PATH + 1]; + GetTempPathW(std::size(tmp_dir), tmp_dir); + return fs::path(tmp_dir) / SOCKET_NAME; +#else + if (const char *tmp_dir = std::getenv("TMPDIR")) { + return fs::path(tmp_dir) / SOCKET_NAME; + } else { + return fs::path(UNIX_DEFAULT_TMP_DIR) / SOCKET_NAME; + } +#endif +} + +void BridgeTransport::OnRecv(std::span event) { + if (!message_callback_) + return; + + auto bundle = flatbuffers::GetRoot(event.data()); + + if (auto data_feed_msgs = bundle->data_feed_msgs()) { + for (auto msg : *data_feed_msgs) { + // Logger::get().debug("Got message DataFeedMessage::{}", EnumNameDataFeedMessage(msg->message_type())); + message_callback_(msg); + } + } + if (auto rpc_msgs = bundle->rpc_msgs()) { + for (auto msg : *rpc_msgs) { + Logger::get().debug("Got message RpcMessage::{}", EnumNameRpcMessage(msg->message_type())); + message_callback_(msg); + } + } + if (auto driver_msgs = bundle->driver_msgs()) { + for (auto msg : *driver_msgs) { + // Logger::get().debug("Got message DriverMessage::{}", EnumNameDriverMessage(msg->message_type())); + message_callback_(msg); + } + } +} + +void BridgeTransport::Start() { + thread_ = std::jthread([this](std::stop_token stop) { return RunThread(stop); }); +} + +void BridgeTransport::RunThread(std::stop_token stop) { + std::vector data; + data.reserve(0x10000); + + // Kick off connection. + ResetConnection(); + + while (!stop.stop_requested()) { + std::shared_lock fd_lock(fd_mutex_); + + if (fd_ == InvalidSocket) [[unlikely]] { + cv_.wait(fd_lock, stop, [this] { return fd_ != InvalidSocket; }); + if (stop.stop_requested()) + break; + } + + try { + ptrdiff_t ret = Poll(fd_, 1ms); + if (ret == 0) [[likely]] { + // No data on the socket after timeout + continue; + } + + uint32_t msg_len; + ret = ReadFully(fd_, stop, &msg_len, sizeof(msg_len)); + if (ret == 0) [[unlikely]] { + throw std::runtime_error("EOF"); + } + + msg_len = ConvertEndianness(msg_len); + // If we get something bigger than this, something's probably up + if (msg_len > 0x40000) [[unlikely]] { + throw std::runtime_error(std::format("Got too large message ({} bytes)", msg_len)); + } + + const uint32_t unwrapped_len = msg_len - 4; + data.reserve(unwrapped_len); + + ret = ReadFully(fd_, stop, data.data(), unwrapped_len); + if (ret == 0) [[unlikely]] { + throw std::runtime_error("EOF"); + } + + OnRecv({ data.data(), unwrapped_len }); + } catch (Cancelled &) { + continue; + } catch (std::exception &e) { + Logger::get().error("Error on socket: {}", e.what()); + error_callback_(e); + fd_lock.unlock(); + ResetConnection(); + } + } + + CloseConnectionHandles(); +} + +void BridgeTransport::ResetConnection() { + CloseConnectionHandles(); + + reconnect_thread_ = std::jthread([this](std::stop_token stop) { + while (!stop.stop_requested()) { + try { + std::unique_lock fd_lock(fd_mutex_); + CreateConnection(); + assert(fd_ != InvalidSocket); + + cv_.notify_all(); + + // connect callback may call a function that needs to block on the fd + fd_lock.unlock(); + OnConnect(); + + return; + } catch (std::system_error &e) { + if (last_error_ != e.code()) { + Logger::get().error("Error when trying to connect: {}", e.what()); + last_error_ = e.code(); + } + error_callback_(e); + } catch (std::exception &e) { + Logger::get().error("Error when trying to connect: {}", e.what()); + error_callback_(e); + } + + std::this_thread::sleep_for(100ms); + } + }); +} + +void BridgeTransport::CloseConnectionHandles() { + std::unique_lock fd_lock(fd_mutex_); + if (fd_ == InvalidSocket) + return; + + CloseSocket(fd_); + OnDisconnect(); + fd_ = InvalidSocket; +} + +void BridgeTransport::SendMessage(const flatbuffers::FlatBufferBuilder &fbb) { + std::shared_lock fd_lock(fd_mutex_); + if (fd_ == InvalidSocket) [[unlikely]] + return; + + std::lock_guard write_lock(write_mutex_); + + if (fbb.GetSize() + 4 > std::numeric_limits::max()) [[unlikely]] { + Logger::get().warning("Skipping send of message (wrapped size larger than 32-bit unsigned integer limit)"); + return; + } + + const uint32_t size = static_cast(fbb.GetSize()); + const uint32_t le_wrapped_size = ConvertEndianness(size + 4); + + try { + WriteFully(fd_, &le_wrapped_size, sizeof(le_wrapped_size)); + WriteFully(fd_, fbb.GetBufferPointer(), size); + } catch (std::exception &e) { + Logger::get().error("Failed to write message: {}", e.what()); + } +} diff --git a/bindings-provider/src/bridge/BridgeTransport.hpp b/bindings-provider/src/bridge/BridgeTransport.hpp new file mode 100644 index 000000000..846bde825 --- /dev/null +++ b/bindings-provider/src/bridge/BridgeTransport.hpp @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// Needs to be before anything that includes Windows.h to avoid macro clashes +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +// Microsoft why +#undef ERROR +#undef SendMessage +#else +#include +#include +#include +#include +#endif + +#include "../logger.hpp" + +/** + * @brief Passes messages between SlimeVR Server and SteamVR Driver using Unix sockets. + * + * Client or Server connection handling is implemented by extending this class. + * + * This class provides a set of methods to start, stop an IO thread, and send messages over a Unix socket. + * + * When a message is received and parsed from the pipe, the on_message_received function passed in the constructor is called + * from the bridge thread with the message as a parameter. + * + * @param logger A shared pointer to an Logger object to log messages from the transport. + * @param on_message_received A function to be called from event loop thread when a message is received and parsed from the pipe. + * @param on_connect A function to be called when the socket is connected to. + * @param on_disconnect A function to be called when the connection is ended. + */ +class BridgeTransport { +public: + using MessageHeader = std::variant; + +#ifdef _WIN32 + using Socket = SOCKET; + constexpr static Socket InvalidSocket = INVALID_SOCKET; + constexpr static int SocketError = SOCKET_ERROR; +#else + using Socket = int; + constexpr static Socket InvalidSocket = -1; + constexpr static int SocketError = -1; +#endif + + static inline int GetLastSocketError() { +#ifdef _WIN32 + return WSAGetLastError(); +#else + return errno; +#endif + } + + static inline int CloseSocket(Socket fd) { +#ifdef _WIN32 + return closesocket(fd); +#else + return close(fd); +#endif + } + + static inline bool IsBlockingError(int err) { +#ifdef _WIN32 + return err == WSAEWOULDBLOCK; +#else + return err == EAGAIN || err == EWOULDBLOCK; +#endif + } + + static inline int SetNonBlocking(Socket fd) { +#ifdef _WIN32 + u_long mode = 1; + return ioctlsocket(fd, FIONBIO, &mode); +#else + return fcntl(fd, F_SETFL, O_NONBLOCK); +#endif + } + + /** + * @brief Exception thrown when IO is cancelled by stop token. + */ + class Cancelled : public std::exception { + public: + Cancelled() noexcept { }; + ~Cancelled() { }; + + const char *what() const noexcept override { + return "IO operation cancelled"; + } + }; + + /** + * @brief Read @a size bytes from @a fd into @a data, retrying until all data is read or an error occurs. + * + * @throws @ref Cancelled stop was requested on @a stop + * @throws std::system_error error returned on socket + * @returns @ref SocketError on fail, otherwise number of bytes read + */ + static ptrdiff_t ReadFully(Socket fd, std::stop_token stop, void *data, size_t size) { + ptrdiff_t ret; + size_t received = 0; + while (!stop.stop_requested() && received < size) { + ret = recv(fd, reinterpret_cast(data) + received, size - received, 0); + if (ret == 0) // EOF + return ret; + + if (ret == SocketError) [[unlikely]] { + int err = GetLastSocketError(); + if (IsBlockingError(err)) [[likely]] { + // we couldn't read because it would block, just try again + continue; + } else { + throw std::system_error(err, std::system_category(), "recv() failed"); + } + } + + received += ret; + } + + if (stop.stop_requested()) + throw Cancelled(); + return received; + } + + /** + * @brief Write @a size bytes from @a data to @a fd, retrying until all data is written or an error occurs. + * + * @throws std::system_error error returned on socket + * + * @returns @ref SocketError on fail, otherwise number of bytes written + */ + static inline ptrdiff_t WriteFully(Socket fd, const void *data, size_t size) { +#ifdef __linux__ + constexpr int flags = MSG_NOSIGNAL; +#else + constexpr int flags = 0; +#endif + + ptrdiff_t ret; + size_t sent = 0; + while (sent < size) { + ret = send(fd, reinterpret_cast(data) + sent, size - sent, flags); + if (ret == SocketError) [[unlikely]] { + int err = GetLastSocketError(); + if (IsBlockingError(err)) [[likely]] { + // we couldn't write because it would block, just try again + continue; + } else { + throw std::system_error(err, std::system_category(), "send() failed"); + } + } + + sent += ret; + } + + return sent; + } + + /** + * @brief Wait for input to be ready on @a fd, timing out after @a timeout. + * + * @param fd file descriptor to poll + * @param timeout amount of time to wait before giving up + * + * @throws std::system_error error returned when polling + * @throws std::runtime_error error on socket, or hang up was detected + * + * @returns @ref 0 if there is no data, positive value if there is data + */ + template + static int Poll(Socket fd, std::chrono::duration timeout) noexcept(false) { + struct pollfd pollfd{ + .fd = fd, + .events = POLLIN, + }; + + int ret; + +#ifdef _WIN32 + ret = WSAPoll(&pollfd, 1, std::chrono::duration_cast(timeout).count()); +#else + { + auto s = std::chrono::duration_cast(timeout); + auto ns = std::chrono::duration_cast(timeout - s); + struct timespec ts{ + .tv_sec = s.count(), + .tv_nsec = ns.count(), + }; + ret = ppoll(&pollfd, 1, timeout == timeout.zero() ? nullptr : &ts, nullptr); + } +#endif + +#ifdef _WIN32 + constexpr int InterruptedErrno = WSAEINTR; +#else + constexpr int InterruptedErrno = EINTR; +#endif + + if (ret == SocketError) { + int err = GetLastSocketError(); + throw std::system_error(err, std::system_category(), "Poll() failed"); + } + + if ((pollfd.revents & (POLLERR | POLLHUP)) != 0) { + throw std::runtime_error("Socket connection lost"); + } + + return pollfd.revents & POLLIN; + } + + BridgeTransport(std::function on_message_received = {}, + std::function on_connect = {}, + std::function on_disconnect = {}, + std::function on_error = {}) + : connect_callback_(on_connect) + , message_callback_(on_message_received) + , disconnect_callback_(on_disconnect) + , error_callback_(on_error) { +#ifdef _WIN32 + WSADATA _ws_data; + if (int ret = WSAStartup(MAKEWORD(2, 2), &_ws_data); ret != 0) { + Logger::get().error("WSAStartup failed with code {}", ret); + return; + } +#endif + } + + virtual ~BridgeTransport() { + Stop(); +#ifdef _WIN32 + WSACleanup(); +#endif + } + + /** + * @brief Starts the channel by creating a thread. + * + * Connects and automatic reconnects with a timeout are implemented internally. + */ + void Start(); + + /** + * @brief Stops the channel by stopping the thread and closing the connection handles. + * + * Blocks until the thread is stopped and the connection handles are closed. + */ + void Stop(); + + /** + * @brief Stops the channel asynchronously and returns immediately. + */ + void StopAsync(); + + /** + * @brief Sends a message over the channel, you must Finish() the builder before calling this. + * + * @param message The message to send. + */ + void SendMessage(const flatbuffers::FlatBufferBuilder &fbb); + + /** + * @brief Checks if the channel is connected. + * + * @return true if the channel is connected, false otherwise. + */ + bool IsConnected() const { + std::shared_lock fd_lock(fd_mutex_); + return fd_ != InvalidSocket; + }; + +protected: + /** + * @brief Try to create a connection. + * + * Called while an exclusive lock is taken on @ref fd_mutex_. + * Make sure this doesn't block as it will hold up shutdown. + * + * @ref fd_ must be initialised if this returns without throwing. + * + * @throws std::system_error I/O error when creating connection + * @throws std::exception failed to create connection + */ + virtual void CreateConnection() = 0; + /** + * @brief Close the current socket if it's connected. + * + * Locks @ref fd_mutex_, do not call this with the mutex locked. + */ + void ResetConnection(); + + /** + * @brief Closes the current connection, must be called while an exclusive lock is taken on the mutex. + */ + void CloseConnectionHandles(); + + void OnConnect() { + if (connect_callback_) + connect_callback_(); + } + void OnRecv(std::span event); + void OnDisconnect() { + if (disconnect_callback_) + disconnect_callback_(); + } + + static std::filesystem::path GetSocketPath(); + + /// Guards @ref fd_ and the condition variable @ref cv_. + mutable std::shared_mutex fd_mutex_; + /// Guards write operations. + mutable std::mutex write_mutex_; + /// Signaled on connection, or when we're exiting. + std::condition_variable_any cv_; + Socket fd_ = InvalidSocket; + +private: + void RunThread(std::stop_token stop); + + std::function connect_callback_; + std::function message_callback_; + std::function disconnect_callback_; + std::function error_callback_; + + std::jthread thread_; + std::jthread reconnect_thread_; + std::optional last_error_; +}; diff --git a/bindings-provider/src/bridge/Endianness.hpp b/bindings-provider/src/bridge/Endianness.hpp new file mode 100644 index 000000000..810408268 --- /dev/null +++ b/bindings-provider/src/bridge/Endianness.hpp @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// SPDX-FileCopyrightText: (c) 2026 Eiren Rain and SlimeVR Contributors +#pragma once + +#include +#include + +template + requires(std::is_integral_v) +inline T ConvertEndianness(T v) { + // I don't really care about mixed endianness.. + if constexpr (std::endian::native == Endianness) { + return v; + } else { + return std::byteswap(v); + } +} \ No newline at end of file diff --git a/bindings-provider/src/main.cpp b/bindings-provider/src/main.cpp index 70c29e343..d41b9ae24 100644 --- a/bindings-provider/src/main.cpp +++ b/bindings-provider/src/main.cpp @@ -6,11 +6,11 @@ #include // These must be included before Windows.h because of some macro collisions. +#include "bridge/BridgeClient.hpp" #include "flatbuffers/flatbuffers.h" #include "solarxr_protocol/generated/all_generated.h" #include "logger.hpp" -#include "solarxr.hpp" #include "vr_utils.hpp" #include "openvr.h" @@ -29,7 +29,7 @@ using namespace solarxr_protocol; static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); } -static void onYawReset(SolarXRConnection &conn) { +static void onYawReset(BridgeTransport &conn) { flatbuffers::FlatBufferBuilder fbb; auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::YAW, 0, 0.f); @@ -39,9 +39,9 @@ static void onYawReset(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); fbb.Finish(bundle); - conn.sendMsg(fbb); + conn.SendMessage(fbb); } -static void onFullReset(SolarXRConnection &conn) { +static void onFullReset(BridgeTransport &conn) { flatbuffers::FlatBufferBuilder fbb; auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::FULL, 0, 0.f); @@ -51,9 +51,9 @@ static void onFullReset(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); fbb.Finish(bundle); - conn.sendMsg(fbb); + conn.SendMessage(fbb); } -static void onMountingCalibration(SolarXRConnection &conn) { +static void onMountingCalibration(BridgeTransport &conn) { flatbuffers::FlatBufferBuilder fbb; auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::POSE_MOUNTING, 0, 0.f); @@ -63,9 +63,9 @@ static void onMountingCalibration(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); fbb.Finish(bundle); - conn.sendMsg(fbb); + conn.SendMessage(fbb); } -static void onFeetMountingCalibration(SolarXRConnection &conn) { +static void onFeetMountingCalibration(BridgeTransport &conn) { flatbuffers::FlatBufferBuilder fbb; auto bodyParts = fbb.CreateVector( @@ -77,9 +77,9 @@ static void onFeetMountingCalibration(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); fbb.Finish(bundle); - conn.sendMsg(fbb); + conn.SendMessage(fbb); } -static void onToggleTracking(SolarXRConnection &conn) { +static void onToggleTracking(BridgeTransport &conn) { static bool shouldPause = false; flatbuffers::FlatBufferBuilder fbb; @@ -92,7 +92,7 @@ static void onToggleTracking(SolarXRConnection &conn) { auto rpcMsgs = fbb.CreateVector({ msgHeader }); auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs); fbb.Finish(bundle); - conn.sendMsg(fbb); + conn.SendMessage(fbb); } sig_atomic_t should_exit = 0; @@ -135,7 +135,9 @@ int main() { #endif try { - SolarXRConnection conn; + BridgeClient conn(nullptr, nullptr, [] { should_exit = 1; }, [](std::exception &) { should_exit = 1; }); + conn.Start(); + std::unique_ptr sys{ nullptr, shutdown_vr }; @@ -211,7 +213,7 @@ int main() { return 1; } - std::map>> + std::map>> actions{ { "/actions/main/in/YawReset", std::make_tuple(vr::k_ulInvalidActionHandle, onYawReset) }, @@ -281,11 +283,6 @@ int main() { } } - if (!conn.connected()) { - logger.warning("Connection to SlimeVR lost, exiting"); - break; - } - vr::VRActiveActionSet_t set{ .ulActionSet = action_set, .ulRestrictedToDevice = vr::k_ulInvalidInputValueHandle, diff --git a/bindings-provider/src/solarxr.cpp b/bindings-provider/src/solarxr.cpp deleted file mode 100644 index 2db669645..000000000 --- a/bindings-provider/src/solarxr.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include "solarxr.hpp" -#include "logger.hpp" -#include "paths.hpp" - -#include -#include -#include - -namespace fs = std::filesystem; - -static std::string getenvSafe(const char *env) { - char *v = getenv(env); - if (v == nullptr) - return {}; - - return v; -} - -fs::path SolarXRConnection::getSocketPath() { - using namespace std::string_view_literals; - - constexpr std::string_view socketName = "SlimeVRRpc"; - -#define MAKE_SOCKET_PATH(PATH) \ - std::make_pair(PATH##sv, getenvSafe(PATH)) - - std::vector> socketPaths{ - MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"), -#ifndef _WIN32 - { "Steam socket path", Paths::getDataPath() }, - MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"), -#endif - { "Temp directory", Paths::getTempPath() }, - }; - -#undef MAKE_SOCKET_PATH - - for (auto [name, path] : socketPaths) { - if (path.empty()) { - Logger::get().info( - "Skipping socket directory '{}' because it doesn't exist", name); - continue; - } - - fs::path socketPath = path / socketName; - - std::error_code ec; - if (fs::exists(socketPath, ec) -#ifdef _WIN32 - || ec.value() == ERROR_CANT_ACCESS_FILE // Windows moment??? -#endif - ) { - return socketPath; - } - - Logger::get().info( - "Skipping socket directory '{}' because socket does not exist", name); - } - - throw std::runtime_error("Failed to find socket directory"); -} - -SolarXRConnection::SolarXRConnection() { -#ifdef _WIN32 - WSADATA _ws_data; - if (int ret = WSAStartup(MAKEWORD(2, 2), &_ws_data); ret != 0) { - throw std::system_error(ret, std::system_category(), "WSAStartup() failed"); - } -#endif - - const fs::path path = getSocketPath(); - struct sockaddr_un addr{ - .sun_family = AF_UNIX, - }; - - const auto path_str = path.u8string(); - if (path_str.size() > std::size(addr.sun_path) - 1) { - throw std::runtime_error(std::format("Socket path ({}) is too long to fit in sun_path", path.string())); - } - memcpy(addr.sun_path, path_str.data(), path_str.size() + 1); - - fd = socket(AF_UNIX, SOCK_STREAM, 0); - if (fd == InvalidSocket) { - int e = GetLastSocketError(); - throw std::system_error(e, std::system_category(), "socket() failed"); - } - - if (connect(fd, reinterpret_cast(&addr), sizeof(addr)) == SocketError) { - int e = GetLastSocketError(); - CloseSocket(fd); - throw std::system_error(e, std::system_category(), std::format("connect() failed for path {}", path.string())); - } -} - -SolarXRConnection::~SolarXRConnection() { - if (fd != InvalidSocket) - CloseSocket(fd); - -#ifdef _WIN32 - WSACleanup(); -#endif -} - -bool SolarXRConnection::connected() { - if (recv(fd, nullptr, 0, 0) == SocketError) { - return !(errno == EBADF || errno == EINVAL); - } - - return true; -} - -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 - uint32_t 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 (send(fd, reinterpret_cast(&size), sizeof(size), 0) == SocketError) { - Logger::get().warning("Failed to write message size to socket: {}", - std::error_code(GetLastSocketError(), std::system_category()).message()); - return; - } - - if (send(fd, reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize(), 0) == SocketError) { - Logger::get().warning("Failed to write message to socket: {}", - std::error_code(GetLastSocketError(), std::system_category()).message()); - return; - } -} diff --git a/bindings-provider/src/solarxr.hpp b/bindings-provider/src/solarxr.hpp deleted file mode 100644 index e22d3a3db..000000000 --- a/bindings-provider/src/solarxr.hpp +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include - -#ifdef _WIN32 -#define WIN32_MEAN_AND_LEAN -#define NOMINMAX -#include -#include -#else -#include -#include -#endif - -#include "flatbuffers/flatbuffer_builder.h" - -class SolarXRConnection { -private: -#ifdef _WIN32 - using Socket = SOCKET; - constexpr static Socket InvalidSocket = INVALID_SOCKET; - constexpr static int SocketError = SOCKET_ERROR; -#else - using Socket = int; - constexpr static Socket InvalidSocket = -1; - constexpr static int SocketError = -1; -#endif - - static inline int GetLastSocketError() { -#ifdef _WIN32 - return WSAGetLastError(); -#else - return errno; -#endif - } - - static inline int CloseSocket(Socket fd) { -#ifdef _WIN32 - return closesocket(fd); -#else - return close(fd); -#endif - } - - Socket fd = InvalidSocket; - - static std::filesystem::path getSocketPath(); - -public: - SolarXRConnection() noexcept(false); - - ~SolarXRConnection(); - - bool connected(); - void sendMsg(flatbuffers::FlatBufferBuilder &fbb); -};