├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── release-build.yml │ ├── testlinux.yml │ └── testwindows.yml ├── .gitignore ├── CMakeLists.txt ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── src ├── config │ ├── config.hpp │ └── constants.hpp ├── dsu │ ├── dsu_protocol.cpp │ ├── dsu_protocol.hpp │ ├── dsu_server.cpp │ └── dsu_server.hpp ├── main.cpp ├── network │ ├── udp_server.cpp │ └── udp_server.hpp ├── psmove │ ├── psmove_manager.cpp │ ├── psmove_manager.hpp │ ├── psmove_pairing.cpp │ └── psmove_pairing.hpp └── utils │ ├── logging.cpp │ ├── logging.hpp │ ├── platform.hpp │ ├── signal_handler.cpp │ └── signal_handler.hpp └── test ├── DummyDSUServer.cpp └── dummy_dsu_sinewave.cpp /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help me improve PSMove-DSU 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Bug Description 11 | **A clear and concise description of what the bug is.** 12 | 13 | ## Steps to Reproduce 14 | 1. Go to '...' 15 | 2. Run command '...' 16 | 3. Connect controller '...' 17 | 4. See error 18 | 19 | ## Expected Behavior 20 | **What you expected to happen.** 21 | 22 | ## Actual Behavior 23 | **What actually happened instead.** 24 | 25 | ## System Information 26 | **Please complete the following information:** 27 | 28 | - **OS**: [e.g. Windows 11, Ubuntu 22.04, macOS 13.0] 29 | - **Architecture**: [e.g. x64, ARM64] 30 | - **PSMove-DSU Version**: [e.g. v2.1.0] 31 | - **Controller Model**: [e.g. CECH-ZCM1U, CECH-ZCM2U] 32 | - **Connection Type**: [e.g. Bluetooth, USB] 33 | 34 | ## Controller Information 35 | **Run with `--verbose` and provide controller details:** 36 | 37 | ``` 38 | Paste controller serial, connection type, and any relevant controller logs here 39 | ``` 40 | 41 | ## Performance Information 42 | **If related to latency/performance:** 43 | 44 | - **Latency warnings in logs**: [Yes/No - paste any latency warnings] 45 | - **CPU usage during issue**: [e.g. 15%, unknown] 46 | - **Other running applications**: [e.g. games, streaming software] 47 | 48 | ## Verbose Logs 49 | **Run `./dsu_server_psmove --verbose` and paste relevant log output:** 50 | 51 | ``` 52 | Paste verbose logs here, especially around the time the issue occurs. 53 | Include at least 10-20 lines before and after the problem. 54 | ``` 55 | 56 | ## Troubleshooting Attempted 57 | **What have you already tried?** 58 | 59 | - [ ] Restarted the application 60 | - [ ] Re-paired the controller (`--pair` mode) 61 | - [ ] Checked Bluetooth connection 62 | - [ ] Tested with different USB cable (if applicable) 63 | - [ ] Checked port 26760 availability 64 | - [ ] Tested with other DSU clients (Dolphin, Cemu, etc.) 65 | - [ ] Tested on different computer/OS 66 | 67 | ## DSU Client Information 68 | **If the issue involves DSU client connectivity:** 69 | 70 | - **Client Application**: [e.g. Dolphin 5.0, Cemu 1.27.1, Custom] 71 | - **Client OS**: [if different from server OS] 72 | - **Network Setup**: [same computer, different computer, IP addresses if relevant] 73 | 74 | ## 📎 Additional Context 75 | **Add any other context about the problem here.** 76 | 77 | - Screenshots (if applicable) 78 | - Configuration files (if modified) 79 | - Any recent system changes 80 | - Other controllers or software that might interfere 81 | 82 | ## Urgency Level 83 | - [ ] **Critical** - Application crashes or completely unusable 84 | - [ ] **High** - Major functionality broken, workaround exists 85 | - [ ] **Medium** - Minor functionality issues or performance problems 86 | - [ ] **Low** - Small inconveniences or feature improvements 87 | 88 | --- 89 | 90 | **Note**: For performance issues, please include `--verbose` logs as they contain critical latency measurements. Issues without sufficient information may be closed and tagged as "needs more info". 91 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for PSMove-DSU 4 | title: "[FEATURE]" 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/release-build.yml: -------------------------------------------------------------------------------- 1 | name: Build and Release 2 | 3 | on: 4 | release: 5 | types: [created] 6 | workflow_dispatch: 7 | 8 | permissions: 9 | contents: write 10 | actions: read 11 | 12 | jobs: 13 | build: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | include: 18 | - os: ubuntu-latest 19 | asset: psmoveapi-4.0.12-linux.tar.gz 20 | - os: macos-13 21 | asset: psmoveapi-4.0.12-macos.tar.gz 22 | - os: windows-latest 23 | asset: psmoveapi-4.0.12-windows-msvc2017-x64.zip 24 | 25 | steps: 26 | - uses: actions/checkout@v4 27 | 28 | - name: Install dependencies (Linux) 29 | if: runner.os == 'Linux' 30 | run: | 31 | sudo apt-get update 32 | sudo apt-get install -y libusb-1.0-0-dev libbluetooth-dev pkg-config 33 | 34 | - name: Install dependencies (macOS) 35 | if: runner.os == 'macOS' 36 | run: | 37 | brew update 38 | brew install libusb 39 | 40 | - name: Download psmoveapi (Linux/macOS) 41 | if: runner.os != 'Windows' 42 | run: | 43 | curl -L -o psmoveapi.${{ matrix.asset }} \ 44 | https://github.com/thp/psmoveapi/releases/download/4.0.12/${{ matrix.asset }} 45 | 46 | - name: Download psmoveapi (Windows) 47 | if: runner.os == 'Windows' 48 | run: | 49 | curl -L -o psmoveapi.${{ matrix.asset }} https://github.com/thp/psmoveapi/releases/download/4.0.12/${{ matrix.asset }} 50 | 51 | - name: Extract psmoveapi (Linux) 52 | if: runner.os == 'Linux' 53 | run: | 54 | mkdir -p psmoveapi_install 55 | tar -xzf psmoveapi.${{ matrix.asset }} -C psmoveapi_install --strip-components=1 56 | 57 | - name: Extract psmoveapi (macOS) 58 | if: runner.os == 'macOS' 59 | run: | 60 | mkdir -p psmoveapi_install 61 | tar -xzf psmoveapi.${{ matrix.asset }} -C psmoveapi_install --strip-components=1 62 | 63 | - name: Extract psmoveapi (Windows) 64 | if: runner.os == 'Windows' 65 | run: | 66 | mkdir -p psmoveapi_install 67 | tar -xf psmoveapi.${{ matrix.asset }} -C psmoveapi_install --strip-components=1 68 | 69 | - name: Configure with CMake (Windows) 70 | if: runner.os == 'Windows' 71 | run: cmake -S . -B build -DPSMOVE_ROOT=${{ github.workspace }}/psmoveapi_install 72 | 73 | - name: Configure with CMake (Linux/macOS) 74 | if: runner.os != 'Windows' 75 | run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DPSMOVE_ROOT=${{ github.workspace }}/psmoveapi_install 76 | 77 | - name: Build 78 | run: cmake --build build --config Release 79 | 80 | - name: List build directory contents (debug) 81 | run: | 82 | echo "Contents of build directory:" 83 | ls -la build/ 84 | if [ "${{ runner.os }}" = "Windows" ]; then 85 | echo "Contents of build/Release directory:" 86 | ls -la build/Release/ || echo "build/Release/ does not exist" 87 | echo "Contents of build/Debug directory:" 88 | ls -la build/Debug/ || echo "build/Debug/ does not exist" 89 | fi 90 | shell: bash 91 | 92 | - name: Get executable name from CMake 93 | id: cmake_info 94 | run: | 95 | if [ "${{ runner.os }}" = "Windows" ]; then 96 | # For Windows, we need to find the actual executable name 97 | if [ -f "build/Release/"*.exe ]; then 98 | EXEC_NAME=$(basename build/Release/*.exe) 99 | elif [ -f "build/Debug/"*.exe ]; then 100 | EXEC_NAME=$(basename build/Debug/*.exe) 101 | elif [ -f "build/"*.exe ]; then 102 | EXEC_NAME=$(basename build/*.exe) 103 | else 104 | echo "ERROR: Could not find Windows executable" 105 | exit 1 106 | fi 107 | else 108 | # For Linux/macOS, find the executable using portable commands 109 | # Look for files that are executable and not libraries 110 | EXEC_NAME="" 111 | for file in build/*; do 112 | if [ -f "$file" ] && [ -x "$file" ] && [[ ! "$file" =~ \.(so|dylib)$ ]]; then 113 | EXEC_NAME=$(basename "$file") 114 | break 115 | fi 116 | done 117 | 118 | if [ -z "$EXEC_NAME" ]; then 119 | echo "ERROR: Could not find executable" 120 | echo "Available files in build/:" 121 | ls -la build/ 122 | exit 1 123 | fi 124 | fi 125 | echo "executable_name=$EXEC_NAME" >> $GITHUB_OUTPUT 126 | echo "Found executable: $EXEC_NAME" 127 | shell: bash 128 | 129 | - name: Find executable 130 | id: artifact 131 | run: | 132 | mkdir -p artifacts 133 | EXEC_NAME="${{ steps.cmake_info.outputs.executable_name }}" 134 | 135 | if [ "${{ runner.os }}" = "Windows" ]; then 136 | # Try multiple possible locations for Windows executable 137 | if [ -f "build/Release/$EXEC_NAME" ]; then 138 | EXEC_PATH="build/Release/$EXEC_NAME" 139 | elif [ -f "build/Debug/$EXEC_NAME" ]; then 140 | EXEC_PATH="build/Debug/$EXEC_NAME" 141 | elif [ -f "build/$EXEC_NAME" ]; then 142 | EXEC_PATH="build/$EXEC_NAME" 143 | else 144 | echo "ERROR: Could not find Windows executable $EXEC_NAME" 145 | exit 1 146 | fi 147 | ARTIFACT_NAME="$EXEC_NAME" 148 | elif [ "${{ runner.os }}" = "macOS" ]; then 149 | EXEC_PATH="build/$EXEC_NAME" 150 | ARTIFACT_NAME="$EXEC_NAME" 151 | else 152 | EXEC_PATH="build/$EXEC_NAME" 153 | ARTIFACT_NAME="$EXEC_NAME" 154 | fi 155 | 156 | echo "name=$ARTIFACT_NAME" >> $GITHUB_OUTPUT 157 | echo "path=$EXEC_PATH" >> $GITHUB_OUTPUT 158 | 159 | # Copy to artifacts directory 160 | cp "$EXEC_PATH" "artifacts/$ARTIFACT_NAME" 161 | echo "Successfully created: artifacts/$ARTIFACT_NAME" 162 | shell: bash 163 | 164 | - name: Upload to release (on release event) 165 | if: github.event_name == 'release' 166 | uses: softprops/action-gh-release@v2 167 | with: 168 | files: artifacts/${{ steps.artifact.outputs.name }} 169 | env: 170 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 171 | 172 | - name: Get latest release (on workflow_dispatch) 173 | if: github.event_name == 'workflow_dispatch' 174 | id: latest_release 175 | shell: bash 176 | run: | 177 | # Try to get the latest release 178 | if LATEST_RELEASE=$(gh api repos/${{ github.repository }}/releases/latest --jq '.tag_name' 2>/dev/null); then 179 | echo "Found latest release: $LATEST_RELEASE" 180 | echo "tag_name=$LATEST_RELEASE" >> $GITHUB_OUTPUT 181 | echo "exists=true" >> $GITHUB_OUTPUT 182 | else 183 | echo "No releases found - will create a new one" 184 | echo "exists=false" >> $GITHUB_OUTPUT 185 | echo "tag_name=v1.0.0" >> $GITHUB_OUTPUT 186 | fi 187 | env: 188 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 189 | 190 | - name: Create release if none exists (on workflow_dispatch) 191 | if: github.event_name == 'workflow_dispatch' && steps.latest_release.outputs.exists == 'false' 192 | shell: bash 193 | run: | 194 | gh release create ${{ steps.latest_release.outputs.tag_name }} \ 195 | --title "Release ${{ steps.latest_release.outputs.tag_name }}" \ 196 | --notes "Automated release created by workflow dispatch" \ 197 | --repo ${{ github.repository }} 198 | env: 199 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 200 | 201 | - name: Upload to release (on workflow_dispatch) 202 | if: github.event_name == 'workflow_dispatch' 203 | shell: bash 204 | run: | 205 | gh release upload ${{ steps.latest_release.outputs.tag_name }} \ 206 | "artifacts/${{ steps.artifact.outputs.name }}" \ 207 | --repo ${{ github.repository }} \ 208 | --clobber 209 | env: 210 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 211 | -------------------------------------------------------------------------------- /.github/workflows/testlinux.yml: -------------------------------------------------------------------------------- 1 | name: Linux Test Build 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | branch_name: 7 | description: 'Branch to run the workflow on' 8 | required: true 9 | default: 'main' # Or your default branch 10 | 11 | permissions: 12 | contents: write 13 | actions: read 14 | 15 | jobs: 16 | build-linux: 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | 22 | - name: Install dependencies 23 | run: | 24 | sudo apt-get update 25 | sudo apt-get install -y libusb-1.0-0-dev libbluetooth-dev pkg-config 26 | 27 | - name: Download psmoveapi 28 | run: | 29 | curl -L -o psmoveapi.psmoveapi-4.0.12-linux.tar.gz \ 30 | https://github.com/thp/psmoveapi/releases/download/4.0.12/psmoveapi-4.0.12-linux.tar.gz 31 | 32 | - name: Extract psmoveapi 33 | run: | 34 | mkdir -p psmoveapi_install 35 | tar -xzf psmoveapi.psmoveapi-4.0.12-linux.tar.gz -C psmoveapi_install --strip-components=1 36 | 37 | - name: Configure with CMake 38 | run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DPSMOVE_ROOT=${{ github.workspace }}/psmoveapi_install 39 | 40 | - name: Build 41 | run: cmake --build build --config Release 42 | 43 | - name: List build directory contents (debug) 44 | run: | 45 | echo "Contents of build directory:" 46 | ls -la build/ 47 | 48 | - name: Check for specific executable 49 | run: | 50 | if [ -f "build/dsu_server_psmove_linux_x64" ]; then 51 | echo "Found dsu_server_psmove_linux_x64" 52 | ls -la build/dsu_server_psmove_linux_x64 53 | else 54 | echo "dsu_server_psmove_linux_x64 not found, listing all executables:" 55 | find build/ -type f -executable ! -name "*.so" ! -name "*.dylib" 56 | fi 57 | 58 | - name: Upload executable to repository 59 | run: | 60 | # Configure git 61 | git config --local user.email "action@github.com" 62 | git config --local user.name "GitHub Action" 63 | 64 | # Check if the executable exists 65 | if [ ! -f "build/dsu_server_psmove_linux_x64" ]; then 66 | echo "ERROR: build/dsu_server_psmove_linux_x64 not found" 67 | exit 1 68 | fi 69 | 70 | # Copy the executable to the root of the repository 71 | cp build/dsu_server_psmove_linux_x64 ./dsu_server_psmove_linux_x64 72 | 73 | # Add and commit the file 74 | git add dsu_server_psmove_linux_x64 75 | 76 | # Check if there are changes to commit 77 | if git diff --staged --quiet; then 78 | echo "No changes to commit - executable is already up to date" 79 | else 80 | git commit -m "Update Linux x64 executable from workflow run" 81 | git push 82 | echo "Successfully uploaded dsu_server_psmove_linux_x64 to repository" 83 | fi 84 | -------------------------------------------------------------------------------- /.github/workflows/testwindows.yml: -------------------------------------------------------------------------------- 1 | name: Windows Test Build 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | branch_name: 7 | description: 'Branch to run the workflow on' 8 | required: true 9 | default: 'main' # Or your default branch 10 | 11 | permissions: 12 | contents: write 13 | actions: read 14 | 15 | jobs: 16 | build-windows: 17 | runs-on: windows-latest 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | 22 | - name: Download psmoveapi 23 | run: | 24 | curl -L -o psmoveapi.psmoveapi-4.0.12-windows-msvc2017-x64.zip https://github.com/thp/psmoveapi/releases/download/4.0.12/psmoveapi-4.0.12-windows-msvc2017-x64.zip 25 | 26 | - name: Extract psmoveapi 27 | run: | 28 | mkdir -p psmoveapi_install 29 | tar -xf psmoveapi.psmoveapi-4.0.12-windows-msvc2017-x64.zip -C psmoveapi_install --strip-components=1 30 | 31 | - name: Configure with CMake 32 | run: cmake -S . -B build -DPSMOVE_ROOT=${{ github.workspace }}/psmoveapi_install 33 | 34 | - name: Build 35 | run: cmake --build build --config Release 36 | 37 | - name: List build directory contents (debug) 38 | run: | 39 | echo "Contents of build directory:" 40 | Get-ChildItem build/ -Recurse 41 | echo "Contents of build/Release directory:" 42 | if (Test-Path "build/Release") { 43 | Get-ChildItem build/Release/ 44 | } else { 45 | echo "build/Release/ does not exist" 46 | } 47 | echo "Contents of build/Debug directory:" 48 | if (Test-Path "build/Debug") { 49 | Get-ChildItem build/Debug/ 50 | } else { 51 | echo "build/Debug/ does not exist" 52 | } 53 | 54 | - name: Check for specific executable 55 | run: | 56 | $executableFound = $false 57 | if (Test-Path "build/Release/dsu_server_psmove_win64.exe") { 58 | echo "Found dsu_server_psmove_win64.exe in Release" 59 | Get-Item build/Release/dsu_server_psmove_win64.exe 60 | $executableFound = $true 61 | } elseif (Test-Path "build/Debug/dsu_server_psmove_win64.exe") { 62 | echo "Found dsu_server_psmove_win64.exe in Debug" 63 | Get-Item build/Debug/dsu_server_psmove_win64.exe 64 | $executableFound = $true 65 | } elseif (Test-Path "build/dsu_server_psmove_win64.exe") { 66 | echo "Found dsu_server_psmove_win64.exe in build root" 67 | Get-Item build/dsu_server_psmove_win64.exe 68 | $executableFound = $true 69 | } 70 | 71 | if (-not $executableFound) { 72 | echo "dsu_server_psmove_win64.exe not found, listing all .exe files:" 73 | Get-ChildItem build/ -Recurse -Filter "*.exe" 74 | } 75 | 76 | - name: Upload executable to repository 77 | run: | 78 | # Configure git 79 | git config --local user.email "action@github.com" 80 | git config --local user.name "GitHub Action" 81 | 82 | # Find the executable in the most likely locations 83 | $executablePath = $null 84 | $targetName = "dsu_server_psmove_win64.exe" 85 | 86 | if (Test-Path "build/Release/$targetName") { 87 | $executablePath = "build/Release/$targetName" 88 | } elseif (Test-Path "build/Debug/$targetName") { 89 | $executablePath = "build/Debug/$targetName" 90 | } elseif (Test-Path "build/$targetName") { 91 | $executablePath = "build/$targetName" 92 | } 93 | 94 | if (-not $executablePath) { 95 | echo "ERROR: $targetName not found" 96 | exit 1 97 | } 98 | 99 | echo "Found executable at: $executablePath" 100 | 101 | # Copy the executable to the root of the repository 102 | Copy-Item $executablePath ./$targetName 103 | 104 | # Add and commit the file 105 | git add $targetName 106 | 107 | # Check if there are changes to commit 108 | $changes = git diff --staged --quiet 109 | if ($LASTEXITCODE -eq 0) { 110 | echo "No changes to commit - executable is already up to date" 111 | } else { 112 | git commit -m "Update Windows x64 executable from workflow run" 113 | git push 114 | echo "Successfully uploaded $targetName to repository" 115 | } 116 | shell: powershell 117 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Linker files 15 | *.ilk 16 | 17 | # Debugger Files 18 | *.pdb 19 | 20 | # Compiled Dynamic libraries 21 | *.so 22 | *.dylib 23 | *.dll 24 | 25 | # Fortran module files 26 | *.mod 27 | *.smod 28 | 29 | # Compiled Static libraries 30 | *.lai 31 | *.la 32 | *.a 33 | *.lib 34 | 35 | # Executables 36 | *.exe 37 | *.out 38 | *.app 39 | 40 | # debug information files 41 | *.dwo 42 | test/** 43 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | project(dsu_server_psmove) 3 | set(CMAKE_CXX_STANDARD 17) 4 | 5 | # Determine platform suffix for executable name 6 | if(WIN32) 7 | if(CMAKE_SIZEOF_VOID_P EQUAL 8) 8 | set(PLATFORM_SUFFIX "win64") 9 | else() 10 | set(PLATFORM_SUFFIX "win32") 11 | endif() 12 | elseif(APPLE) 13 | if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64") 14 | set(PLATFORM_SUFFIX "macos_arm64") 15 | else() 16 | set(PLATFORM_SUFFIX "macos_x64") 17 | endif() 18 | else() 19 | # Linux and other Unix-like systems 20 | if(CMAKE_SIZEOF_VOID_P EQUAL 8) 21 | if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64") 22 | set(PLATFORM_SUFFIX "linux_arm64") 23 | else() 24 | set(PLATFORM_SUFFIX "linux_x64") 25 | endif() 26 | else() 27 | set(PLATFORM_SUFFIX "linux_x86") 28 | endif() 29 | endif() 30 | 31 | # Set the executable name with platform suffix 32 | set(EXECUTABLE_NAME "dsu_server_psmove_${PLATFORM_SUFFIX}") 33 | 34 | # Allow user to specify where psmoveapi is located 35 | if(NOT DEFINED PSMOVE_ROOT) 36 | set(PSMOVE_ROOT "${CMAKE_SOURCE_DIR}/psmoveapi_install") 37 | endif() 38 | 39 | # Check if psmoveapi exists 40 | if(NOT EXISTS "${PSMOVE_ROOT}/include/psmove.h") 41 | message(FATAL_ERROR "psmoveapi not found at ${PSMOVE_ROOT}. Please set PSMOVE_ROOT to the correct path.") 42 | endif() 43 | 44 | # Include headers 45 | include_directories(${PSMOVE_ROOT}/include) 46 | include_directories(src) 47 | 48 | # Add library search path 49 | link_directories(${PSMOVE_ROOT}/lib) 50 | 51 | # Source files 52 | set(SOURCES 53 | src/main.cpp 54 | src/dsu/dsu_server.cpp 55 | src/dsu/dsu_protocol.cpp 56 | src/psmove/psmove_manager.cpp 57 | src/psmove/psmove_pairing.cpp 58 | src/network/udp_server.cpp 59 | src/utils/logging.cpp 60 | src/utils/signal_handler.cpp 61 | ) 62 | 63 | # Create executable with platform-specific name 64 | add_executable(${EXECUTABLE_NAME} ${SOURCES}) 65 | 66 | # Platform-specific configurations 67 | if(WIN32) 68 | # Windows-specific compile definitions to prevent winsock conflicts 69 | target_compile_definitions(${EXECUTABLE_NAME} PRIVATE 70 | WIN32_LEAN_AND_MEAN 71 | NOMINMAX 72 | _WINSOCKAPI_ 73 | ) 74 | 75 | target_link_libraries(${EXECUTABLE_NAME} 76 | psmoveapi setupapi ws2_32 winmm 77 | ) 78 | elseif(APPLE) 79 | find_library(USB_LIBRARY usb-1.0 REQUIRED) 80 | find_library(COREFOUNDATION_LIBRARY CoreFoundation REQUIRED) 81 | find_library(IOKIT_LIBRARY IOKit REQUIRED) 82 | 83 | target_link_libraries(${EXECUTABLE_NAME} 84 | psmoveapi ${USB_LIBRARY} ${COREFOUNDATION_LIBRARY} ${IOKIT_LIBRARY} 85 | ) 86 | else() 87 | find_package(PkgConfig REQUIRED) 88 | pkg_check_modules(LIBUSB REQUIRED libusb-1.0) 89 | pkg_check_modules(BLUETOOTH REQUIRED bluez) 90 | pkg_check_modules(UDEV libudev) 91 | 92 | include_directories(${LIBUSB_INCLUDE_DIRS} ${BLUETOOTH_INCLUDE_DIRS}) 93 | link_directories(${LIBUSB_LIBRARY_DIRS} ${BLUETOOTH_LIBRARY_DIRS}) 94 | 95 | set(LINUX_LIBS psmoveapi ${LIBUSB_LIBRARIES} ${BLUETOOTH_LIBRARIES} pthread) 96 | 97 | if(UDEV_FOUND) 98 | list(APPEND LINUX_LIBS ${UDEV_LIBRARIES}) 99 | include_directories(${UDEV_INCLUDE_DIRS}) 100 | link_directories(${UDEV_LIBRARY_DIRS}) 101 | endif() 102 | 103 | target_link_libraries(${EXECUTABLE_NAME} ${LINUX_LIBS}) 104 | endif() 105 | 106 | # Set output directory 107 | set_target_properties(${EXECUTABLE_NAME} PROPERTIES 108 | RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} 109 | RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR} 110 | RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR} 111 | ) 112 | 113 | # Enable debug info for release builds 114 | if(CMAKE_BUILD_TYPE STREQUAL "Release") 115 | if(WIN32) 116 | target_compile_options(${EXECUTABLE_NAME} PRIVATE /Zi) 117 | target_link_options(${EXECUTABLE_NAME} PRIVATE /DEBUG) 118 | else() 119 | target_compile_options(${EXECUTABLE_NAME} PRIVATE -g) 120 | endif() 121 | endif() 122 | 123 | # Print the final executable name for confirmation 124 | message(STATUS "Building executable: ${EXECUTABLE_NAME}") 125 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to PSMove-DSU 2 | 3 | Thank you for your interest in contributing to PSMove-DSU! This project provides a high-performance DSU (DualShock UDP) server for PlayStation Move controllers, optimized for low-latency motion tracking in supported emulators. 4 | 5 | ## Quick Start 6 | 7 | 1. **Fork** the repository 8 | 2. **Clone** your fork locally 9 | 3. **Create a branch** for your feature/fix 10 | 4. **Make your changes** 11 | 5. **Test thoroughly** 12 | 6. **Submit a pull request** 13 | 14 | ## Development Setup 15 | 16 | ### Prerequisites 17 | 18 | - **C++17** compatible compiler 19 | - **CMake 3.10+** 20 | - **PSMoveAPI 4.0.12** (automatically downloaded by build system) 21 | 22 | ### Platform-Specific Dependencies 23 | 24 | #### Linux (Ubuntu/Debian) 25 | ```bash 26 | sudo apt-get update 27 | sudo apt-get install -y libusb-1.0-0-dev libbluetooth-dev pkg-config build-essential cmake 28 | ``` 29 | 30 | #### macOS 31 | ```bash 32 | brew install libusb cmake 33 | ``` 34 | 35 | #### Windows 36 | - **Visual Studio 2017+** or **Build Tools for Visual Studio** 37 | - **CMake** (can be installed via Visual Studio Installer) 38 | 39 | ### Building from Source 40 | 41 | ```bash 42 | # Clone the repository 43 | git clone https://github.com/YOUR-USERNAME/PSMove-DSU.git 44 | cd PSMove-DSU 45 | 46 | # Build 47 | cmake -S . -B build -DCMAKE_BUILD_TYPE=Release 48 | cmake --build build --config Release 49 | ``` 50 | 51 | The executable will be created as: 52 | - Linux: `dsu_server_psmove_linux_x64` 53 | - macOS: `dsu_server_psmove_macos_x64` or `dsu_server_psmove_macos_arm64` 54 | - Windows: `dsu_server_psmove_win64.exe` 55 | 56 | ## Contributing Guidelines 57 | 58 | ### Code Style 59 | 60 | - **Modern C++17** features encouraged 61 | - **RAII** for resource management 62 | - **Consistent naming**: `snake_case` for variables/functions, `PascalCase` for classes 63 | - **Clear comments** for complex algorithms, especially threading and timing code 64 | - **Platform-specific code** should be clearly marked with `#ifdef` guards 65 | 66 | ### Example Code Style 67 | ```cpp 68 | class PSMoveManager { 69 | private: 70 | // Use descriptive names 71 | std::atomic running_{false}; 72 | std::mutex controller_mutex_; 73 | 74 | // Clear function naming 75 | void integrate_pending_controllers(); 76 | std::string get_serial_safe(PSMove* controller); 77 | }; 78 | ``` 79 | 80 | ### Performance Considerations 81 | 82 | This is a **real-time, low-latency** application. When contributing: 83 | 84 | - **Avoid blocking operations** in the main polling thread 85 | - **Minimize mutex usage** in hot paths (prefer atomics) 86 | - **Profile timing-critical code** on Windows (most problematic platform) 87 | - **Measure latency impact** of changes 88 | - **Maintain 250Hz polling rate** (4ms intervals) 89 | 90 | ### Key Architecture Principles 91 | 92 | 1. **Background Operations**: Slow operations (controller scanning) run in background threads 93 | 2. **Lock-Free Data Access**: Main polling uses atomic operations where possible 94 | 3. **Platform Optimization**: Windows, Linux, and macOS each have specific optimizations 95 | 4. **Double Buffering**: Sensor data uses double buffering to avoid blocking readers 96 | 97 | ## Bug Reports 98 | 99 | ### Before Reporting 100 | - Check existing issues for duplicates 101 | - Test with **verbose mode**: `./executable --verbose` 102 | - Try on **different platforms** if possible 103 | 104 | ### Include in Bug Reports 105 | - **Platform**: OS version, architecture (x64/ARM) 106 | - **Controller Info**: Model, connection type (Bluetooth/USB) 107 | - **Verbose Logs**: Run with `--verbose` flag 108 | - **Latency Info**: Any high-latency warnings from logs 109 | - **Steps to Reproduce**: Detailed reproduction steps 110 | 111 | ### Example Bug Report 112 | ``` 113 | **Platform**: Windows 11 x64 114 | **Controller**: PS Move Navigation Controller via Bluetooth 115 | **Issue**: Controller disconnects after 30 seconds 116 | 117 | **Verbose Log Output:** 118 | [ERROR] Controller in slot 0 became invalid, removing 119 | [WARN] Windows: Flushed 47 buffered packets from slot 0 120 | 121 | **Steps to Reproduce:** 122 | 1. Pair controller using --pair mode 123 | 2. Start DSU server 124 | 3. Controller connects successfully 125 | 4. After ~30 seconds, controller disconnects 126 | 5. Must restart server to reconnect 127 | ``` 128 | 129 | ## Feature Requests 130 | 131 | ### Good Feature Requests 132 | - **Performance improvements** (latency reduction, CPU usage) 133 | - **Platform support** (new OS versions, ARM64) 134 | - **Controller compatibility** (new PlayStation Move variants) 135 | - **Debugging tools** (better diagnostics, monitoring) 136 | - **Configuration options** (new mapping modes, filters) 137 | 138 | ### Include in Feature Requests 139 | - **Use case**: What problem does this solve? 140 | - **Performance impact**: Will this affect real-time performance? 141 | - **Platform considerations**: Does this work on all platforms? 142 | - **Backward compatibility**: Will this break existing setups? 143 | 144 | ## Pull Request Process 145 | 146 | ### Before Submitting 147 | 1. **Test on multiple platforms** (at minimum your development platform) 148 | 2. **Run with verbose logging** to check for new warnings/errors 149 | 3. **Verify performance** hasn't regressed (check for new high-latency warnings) 150 | 4. **Update documentation** if changing user-facing behavior 151 | 152 | ### PR Description Template 153 | ```markdown 154 | ## Changes 155 | - Brief description of what changed 156 | 157 | ## Testing 158 | - [ ] Tested on Linux 159 | - [ ] Tested on Windows 160 | - [ ] Tested on macOS 161 | - [ ] No new latency warnings in verbose mode 162 | - [ ] Backward compatibility maintained 163 | 164 | ## Performance Impact 165 | - Describe any performance changes (positive or negative) 166 | - Include before/after measurements if applicable 167 | 168 | ## Platform-Specific Notes 169 | - Any platform-specific considerations or changes 170 | ``` 171 | 172 | ### Review Process 173 | 1. **Automated builds** must pass on all platforms 174 | 2. **Code review** by maintainers 175 | 3. **Performance validation** for timing-critical changes 176 | 4. **Testing** on real hardware when possible 177 | 178 | ## Priority Areas for Contributions 179 | 180 | ### High Priority 181 | - **Windows latency optimization**: Windows HID layer improvements 182 | - **Controller compatibility**: Support for new PlayStation Move variants 183 | - **Memory optimization**: Reducing CPU usage and memory footprint 184 | - **Cross-platform testing**: Ensuring consistent behavior across platforms 185 | - **Multiple controllers**: Enabling the use of multiple controllers 186 | 187 | ### Medium Priority 188 | - **Configuration system**: More flexible axis mapping and filtering 189 | - **Diagnostic tools**: Better debugging and monitoring capabilities 190 | - **Documentation**: Setup guides, troubleshooting, API documentation 191 | 192 | ### Low Priority 193 | - **UI/GUI**: Currently command-line focused 194 | - **Protocol extensions**: DSU protocol is well-established 195 | - **Alternative controllers**: Focus is on PlayStation Move devices 196 | 197 | ## Useful Resources 198 | 199 | - **PSMoveAPI Documentation**: https://github.com/thp/psmoveapi 200 | - **DSU Protocol Spec**: https://v1993.github.io/cemuhook-protocol/ 201 | - **Real-time Programming**: Understanding thread priorities and timing 202 | - **HID Protocol**: USB/Bluetooth Human Interface Device standards 203 | 204 | ## Testing 205 | 206 | ### Manual Testing Checklist 207 | - [ ] Controller pairing works (`--pair` mode) 208 | - [ ] Controller discovery and connection 209 | - [ ] Data transmission to DSU clients (test with Cemu, Dolphin, etc.) 210 | - [ ] Multiple controller support (up to 4) 211 | - [ ] Controller disconnect/reconnect handling 212 | - [ ] No memory leaks during extended operation 213 | 214 | ### Performance Testing 215 | ```bash 216 | # Run with verbose logging to monitor performance 217 | ./dsu_server_psmove_linux_x64 --verbose 218 | 219 | # Look for these in logs: 220 | # - Processing latency < 1000µs (normal) 221 | # - No "High end-to-end latency" warnings 222 | # - "Windows: Flushed" messages should be rare 223 | ``` 224 | 225 | ## Questions? 226 | 227 | - **General Questions**: Open a GitHub Discussion 228 | - **Bug Reports**: Open a GitHub Issue 229 | - **Feature Ideas**: Open a GitHub Issue with [FEATURE] tag 230 | - **Code Questions**: Comment on relevant pull requests 231 | 232 | ## Recognition 233 | 234 | Contributors will be acknowledged in: 235 | - **Release notes** for significant contributions 236 | - **README.md** contributor section 237 | - **Git commit history** (please use descriptive commit messages) 238 | 239 | Thank you for helping make PSMove-DSU better! 240 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PSMove-DSU 2 | 3 | A cross-platform DSU (DualShock UDP) / Cemuhook server for PlayStation Move controllers, enabling motion controls in games and emulators that support the DSU protocol. 4 | 5 | ## Overview 6 | 7 | PSMove-DSU bridges PlayStation Move controllers to applications that support the DSU/Cemuhook protocol, such as: 8 | - **Cemu** (Wii U emulator) 9 | - **Dolphin** (GameCube/Wii emulator) 10 | - **RPCS3** (PS3 emulator) 11 | - **Yuzu** (Nintendo Switch emulator) 12 | - **PCSX2** (PS2 emulator) 13 | - Any application supporting motion controls via DSU 14 | 15 | The server translates PS Move controller input (accelerometer, gyroscope, and buttons) into the standardized DSU protocol, allowing these controllers to provide motion control functionality in supported games. 16 | 17 | ## Features 18 | 19 | - **Cross-platform support**: Windows, macOS, and Linux 20 | - **Real-time motion data**: Accelerometer and gyroscope 21 | - **Button support**: All PS Move controller buttons 22 | - **DSU/Cemuhook protocol**: Compatible with all DSU-enabled applications 23 | - **Automatic controller detection**: Plug and play functionality 24 | 25 | ## Quick Start 26 | 27 | ### Using Pre-built Binaries 28 | 29 | 1. **Download** the latest release for your platform: 30 | - [Windows](https://github.com/Swordmaster3214/PSMove-DSU/releases/latest/) 31 | - [macOS](https://github.com/Swordmaster3214/PSMove-DSU/releases/latest/) 32 | - [Linux](https://github.com/Swordmaster3214/PSMove-DSU/releases/latest/) 33 | 34 | 2. **Connect your PS Move controller** via Bluetooth 35 | 36 | 3. **Run the executable**: 37 | #### Windows 38 | ```bash 39 | ./dsu_server_psmove_windows_win64.exe 40 | ``` 41 | #### macOS/Linux 42 | ```bash 43 | ./dsu_server_psmove_macos_x64 44 | ``` 45 | ```bash 46 | ./dsu_server_psmove_linux_x64 47 | ``` 48 | 49 | 5. **Configure your emulator** to connect to `127.0.0.1:26760` (default DSU port) 50 | 51 | ### Button Mappings 52 | 53 | Button | Mapping 54 | --- | --- 55 | X | Cross 56 | O | Circle 57 | □ | Square 58 | ∆ | Triangle 59 | Move | R1 60 | SELECT | Share 61 | START | Options 62 | T | R2 63 | PS | PS 64 | 65 | ### Controller Setup 66 | 67 | #### Bluetooth Pairing 68 | **Note:** You will not need to do the following if you have already paired your controller with your computer using [PSMoveAPI](https://github.com/thp/psmoveapi) 69 | ```bash 70 | ./dsu_server_psmove --pair 71 | ``` 72 | 73 | ## Building from Source 74 | 75 | ### File structure 76 | ``` 77 | dsu_server_psmove/ 78 | ├── CMakeLists.txt 79 | ├── README.md 80 | ├── src/ 81 | │ ├── main.cpp # Entry point and CLI parsing 82 | │ ├── dsu/ 83 | │ │ ├── dsu_server.hpp # DSU server interface 84 | │ │ ├── dsu_server.cpp # DSU server implementation 85 | │ │ ├── dsu_protocol.hpp # DSU protocol definitions 86 | │ │ └── dsu_protocol.cpp # DSU protocol implementation 87 | │ ├── psmove/ 88 | │ │ ├── psmove_manager.hpp # PSMove controller manager 89 | │ │ ├── psmove_manager.cpp # PSMove controller implementation 90 | │ │ ├── psmove_pairing.hpp # Pairing functionality 91 | │ │ └── psmove_pairing.cpp # Pairing implementation 92 | │ ├── network/ 93 | │ │ ├── udp_server.hpp # UDP networking interface 94 | │ │ └── udp_server.cpp # UDP networking implementation 95 | │ ├── utils/ 96 | │ │ ├── logging.hpp # Logging utilities 97 | │ │ ├── logging.cpp # Logging implementation 98 | │ │ ├── platform.hpp # Platform-specific definitions 99 | │ │ ├── signal_handler.hpp # Signal handling utilities 100 | │ │ └── signal_handler.cpp # Signal handling implementation 101 | │ └── config/ 102 | │ ├── constants.hpp # Global constants 103 | │ └── config.hpp # Configuration management 104 | ``` 105 | ### Prerequisites 106 | 107 | #### All Platforms 108 | - **CMake** 3.10 or higher 109 | - **C++ compiler** with C++17 support 110 | - **PSMoveAPI 4.0.12** [downloaded](https://github.com/thp/psmoveapi/releases/latest/) 111 | 112 | #### Linux 113 | ```bash 114 | sudo apt-get install libusb-1.0-0-dev libbluetooth-dev pkg-config 115 | ``` 116 | 117 | #### macOS 118 | ```bash 119 | brew install libusb 120 | ``` 121 | 122 | #### Windows 123 | - Visual Studio 2017 or higher 124 | - Windows SDK 125 | 126 | ### Build Instructions 127 | 128 | 1. **Clone the repository**: 129 | ```bash 130 | git clone https://github.com/Swordmaster3214/PSMove-DSU.git && cd PSMove-DSU 131 | ``` 132 | 133 | 2. **Create build directory**: 134 | ```bash 135 | mkdir build && cd build 136 | ``` 137 | 138 | 3. **Configure with CMake**: 139 | #### Linux/macOS 140 | ```bash 141 | cmake -DCMAKE_BUILD_TYPE=Release -DPSMOVE_ROOT=/path/to/psmoveapi .. 142 | ``` 143 | #### Windows 144 | ```bash 145 | cmake -DPSMOVE_ROOT=/path/to/psmoveapi .. 146 | ``` 147 | 148 | 5. **Build the project**: 149 | ```bash 150 | cmake --build . --config Release 151 | ``` 152 | 153 | 6. **Run the executable**: 154 | The executable will be in the build directory 155 | ```bash 156 | ./dsu_server_psmove 157 | ``` 158 | 159 | ### Custom PSMoveAPI Location 160 | 161 | If you have PSMoveAPI installed in a custom location: 162 | 163 | ```bash 164 | cmake -DPSMOVE_ROOT=/path/to/psmoveapi .. 165 | ``` 166 | ## Configuration 167 | 168 | ### DSU Server Settings 169 | The server runs on `127.0.0.1:26760` by default, which is the standard DSU port. Most applications will automatically detect the server at this address. 170 | 171 | ### Emulator Setup 172 | 173 | #### Cemu 174 | 1. Go to **Options** → **GamePad Motion Source** → **DSU1** 175 | 2. Set server IP to `127.0.0.1` and port to `26760` 176 | 177 | #### Dolphin 178 | 1. Go to **Controllers** → **Configure** → **Motion Input** 179 | 2. Set source to **DSU** with server `127.0.0.1:26760` 180 | 181 | #### Yuzu 182 | 1. Go to **Configure** → **Controls** → **Advanced** 183 | 2. Enable **Motion** and set to **DSU** with `127.0.0.1:26760` 184 | 185 | ## Troubleshooting 186 | 187 | ### Controller Not Detected 188 | - Ensure the PS Move controller is properly paired 189 | - On Linux, you may need to run with `sudo` for USB access permissions 190 | - Check that no other applications are using the controller 191 | 192 | ### Connection Issues 193 | - Verify the server is running and listening on port 26760 194 | - Check firewall settings if connecting from another machine 195 | - Ensure the emulator is configured with the correct IP and port 196 | 197 | ### Build Issues 198 | - Make sure all dependencies are installed 199 | - Verify CMake version is 3.10 or higher 200 | - On Windows, ensure you're using the correct Visual Studio toolchain 201 | 202 | ### Linux Permissions 203 | If you get permission errors accessing the controller: 204 | Add udev rules for PS Move controller 205 | ```bash 206 | sudo usermod -a -G plugdev $USER 207 | ``` 208 | Log out and back in for changes to take effect 209 | 210 | ## Technical Details 211 | 212 | ### Dependencies 213 | - **PSMoveAPI 4.0.12**: Core PlayStation Move controller interface 214 | - **System libraries**: Platform-specific USB and Bluetooth libraries 215 | - **CMake**: Build system 216 | - **C++17**: Modern C++ features for reliable performance 217 | 218 | ### Protocol Support 219 | - **DSU Protocol Version 1001**: Full compatibility with Cemuhook standard 220 | - **Motion Data**: 32-bit precision accelerometer and gyroscope 221 | - **Button Data**: All PS Move buttons including trigger 222 | - **Timestamp Synchronization**: Accurate timing for motion prediction 223 | 224 | ### Performance 225 | - **Low latency**: Direct USB/Bluetooth communication 226 | - **Multi-controller**: Support in the project is implemented for multiple controllers, but only one seems to be working 😅 227 | 228 | ## Contributing 229 | 230 | Contributions are welcome! Please feel free to submit pull requests, report issues, or suggest improvements. 231 | 232 | ### Development Setup 233 | 1. Fork the repository 234 | 2. Create a feature branch 235 | 3. Make your changes 236 | 4. Test on your target platform(s) 237 | 5. Submit a pull request 238 | 239 | ## Acknowledgments 240 | 241 | - **Thomas Perl** and contributors to [PSMoveAPI](https://github.com/thp/psmoveapi) 242 | - **Cemuhook developers** for the DSU protocol specification 243 | - **Emulator developers** for DSU protocol support 244 | 245 | ## Support 246 | 247 | - **Issues**: [GitHub Issues](https://github.com/Swordmaster3214/PSMove-DSU/issues) 248 | - **PSMoveAPI Documentation**: [psmoveapi.readthedocs.io](https://psmoveapi.readthedocs.io/) 249 | - **DSU Protocol**: [Cemuhook Documentation](https://cemuhook.sshnuke.net/) 250 | 251 | 252 | 253 | ## Licensing 254 | License details for this project are in the LICENSE file. 255 | 256 | The PS Move API library is licensed under the terms of the license below. 257 | However, some optional third party libraries might have a different license. 258 | Be sure to read the README file for details on third party licenses. 259 | 260 | ==== 261 | 262 | Copyright (c) 2011, 2012 Thomas Perl 263 | All rights reserved. 264 | 265 | Redistribution and use in source and binary forms, with or without 266 | modification, are permitted provided that the following conditions are met: 267 | 268 | 1. Redistributions of source code must retain the above copyright 269 | notice, this list of conditions and the following disclaimer. 270 | 271 | 2. Redistributions in binary form must reproduce the above copyright 272 | notice, this list of conditions and the following disclaimer in the 273 | documentation and/or other materials provided with the distribution. 274 | 275 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 276 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 277 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 278 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 279 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 280 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 281 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 282 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 283 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 284 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 285 | POSSIBILITY OF SUCH DAMAGE. 286 | -------------------------------------------------------------------------------- /src/config/config.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | struct Config { 4 | // Logging 5 | bool verbose = false; 6 | 7 | // Pairing 8 | bool pair_mode = false; 9 | 10 | // Axis mapping 11 | int map_pitch = 0; 12 | int map_yaw = 2; 13 | int map_roll = 1; 14 | 15 | // Axis flipping 16 | bool flip_pitch = false; 17 | bool flip_yaw = true; 18 | bool flip_roll = false; 19 | 20 | // Accelerometer mapping 21 | int map_accel_x = 0; 22 | int map_accel_y = 2; 23 | int map_accel_z = 1; 24 | 25 | // Accelerometer flipping 26 | bool flip_accel_x = true; 27 | bool flip_accel_y = true; 28 | bool flip_accel_z = false; 29 | }; 30 | -------------------------------------------------------------------------------- /src/config/constants.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | namespace Constants { 5 | // DSU Protocol 6 | constexpr uint16_t PROTO_VER = 1001; 7 | constexpr int DSU_PORT = 26760; 8 | constexpr uint32_t MSG_PROTOCOL_VER = 0x100000; 9 | constexpr uint32_t MSG_INFO = 0x100001; 10 | constexpr uint32_t MSG_DATA = 0x100002; 11 | 12 | // Controller limits 13 | constexpr int MAX_CONTROLLERS = 4; 14 | 15 | // Timing - OPTIMIZED FOR LOW LATENCY 16 | constexpr int PSMOVE_POLL_MS = 4; // ~250 Hz - increased frequency 17 | constexpr int DSU_SEND_MS = 4; // ~250 Hz - matched to polling rate 18 | constexpr int LATENCY_WARNING_US = 8000; // Warn if latency > 8ms 19 | 20 | // Trigger settings 21 | constexpr int ANALOG_TRIGGER_INDEX = 14; 22 | constexpr unsigned char TRIGGER_DIGITAL_THRESHOLD = 10; 23 | 24 | // PSMove button constants 25 | constexpr unsigned int Btn_TRIANGLE = 0x10; 26 | constexpr unsigned int Btn_SQUARE = 0x80; 27 | constexpr unsigned int Btn_CROSS = 0x40; 28 | constexpr unsigned int Btn_CIRCLE = 0x20; 29 | constexpr unsigned int Btn_MOVE = 0x08; 30 | constexpr unsigned int Btn_START = 0x01; 31 | constexpr unsigned int Btn_SELECT = 0x02; 32 | constexpr unsigned int Btn_PS = 0x04; 33 | } 34 | -------------------------------------------------------------------------------- /src/dsu/dsu_protocol.cpp: -------------------------------------------------------------------------------- 1 | #include "dsu/dsu_protocol.hpp" 2 | #include "config/constants.hpp" 3 | #include "config/config.hpp" 4 | #include 5 | 6 | uint32_t DSUProtocol::crc32_le(const uint8_t* data, size_t len) { 7 | uint32_t crc = 0xFFFFFFFFu; 8 | for (size_t i = 0; i < len; ++i) { 9 | crc ^= data[i]; 10 | for (int k = 0; k < 8; ++k) { 11 | crc = (crc & 1) ? (crc >> 1) ^ 0xEDB88320u : (crc >> 1); 12 | } 13 | } 14 | return ~crc; 15 | } 16 | 17 | void DSUProtocol::put_u16(std::vector& b, uint16_t v) { 18 | b.push_back(v & 0xFF); 19 | b.push_back((v >> 8) & 0xFF); 20 | } 21 | 22 | void DSUProtocol::put_u32(std::vector& b, uint32_t v) { 23 | for (int i = 0; i < 4; i++) { 24 | b.push_back((v >> (8 * i)) & 0xFF); 25 | } 26 | } 27 | 28 | void DSUProtocol::put_u64(std::vector& b, uint64_t v) { 29 | for (int i = 0; i < 8; i++) { 30 | b.push_back((v >> (8 * i)) & 0xFF); 31 | } 32 | } 33 | 34 | void DSUProtocol::put_f32(std::vector& b, float f) { 35 | uint32_t v; 36 | std::memcpy(&v, &f, 4); 37 | put_u32(b, v); 38 | } 39 | 40 | std::vector DSUProtocol::make_packet(uint32_t server_id, uint32_t msg_type, const std::vector& payload) { 41 | std::vector pkt; 42 | pkt.push_back('D'); pkt.push_back('S'); pkt.push_back('U'); pkt.push_back('S'); 43 | put_u16(pkt, Constants::PROTO_VER); 44 | put_u16(pkt, static_cast(payload.size() + 4)); 45 | put_u32(pkt, 0); // CRC placeholder 46 | put_u32(pkt, server_id); 47 | put_u32(pkt, msg_type); 48 | pkt.insert(pkt.end(), payload.begin(), payload.end()); 49 | 50 | pkt[8] = pkt[9] = pkt[10] = pkt[11] = 0; 51 | uint32_t crc = crc32_le(pkt.data(), pkt.size()); 52 | pkt[8] = crc & 0xFF; 53 | pkt[9] = (crc >> 8) & 0xFF; 54 | pkt[10] = (crc >> 16) & 0xFF; 55 | pkt[11] = (crc >> 24) & 0xFF; 56 | return pkt; 57 | } 58 | 59 | void DSUProtocol::put_shared_begin(std::vector& p, uint8_t slot, uint8_t state_connected, 60 | uint8_t model_fullgyro, uint8_t conn_bt, uint64_t mac48, uint8_t battery) { 61 | p.push_back(slot); 62 | p.push_back(state_connected); 63 | p.push_back(model_fullgyro); 64 | p.push_back(conn_bt); 65 | for (int i = 0; i < 6; i++) { 66 | p.push_back(uint8_t((mac48 >> (8 * i)) & 0xFF)); 67 | } 68 | p.push_back(battery); 69 | } 70 | 71 | std::vector DSUProtocol::make_protocol_response(uint32_t server_id) { 72 | std::vector payload; 73 | put_u16(payload, Constants::PROTO_VER); 74 | return make_packet(server_id, Constants::MSG_PROTOCOL_VER, payload); 75 | } 76 | 77 | std::vector DSUProtocol::make_info_response(uint32_t server_id, uint8_t slot, bool connected, int battery, uint64_t mac) { 78 | std::vector payload; 79 | uint8_t batt_byte = (battery >= 0 && battery <= 0xFF) ? uint8_t(battery) : 0x05u; 80 | uint8_t connected_state = connected ? 2 : 0; 81 | 82 | put_shared_begin(payload, slot, connected_state, 2, 2, mac, batt_byte); 83 | payload.push_back(0x00); 84 | return make_packet(server_id, Constants::MSG_INFO, payload); 85 | } 86 | 87 | std::vector DSUProtocol::make_data_packet(uint32_t server_id, uint8_t slot, const MoveSample& sample, 88 | uint32_t packet_no, int battery, uint64_t mac, const Config& config) { 89 | std::vector p; 90 | 91 | uint8_t batt_byte = (battery >= 0 && battery <= 0xFF) ? uint8_t(battery) : 0x05u; 92 | put_shared_begin(p, slot, 2, 2, 2, mac, batt_byte); 93 | p.push_back(1); 94 | put_u32(p, packet_no); 95 | p.push_back(0); // bitmask1 96 | p.push_back(0); // bitmask2 97 | p.push_back(0); // HOME 98 | p.push_back(0); // Touch 99 | 100 | // Analog sticks (16 bytes) 101 | for (int i = 0; i < 16; ++i) { 102 | if (i == 0 || i == 1 || i == 2 || i == 3) { 103 | p.push_back(128); 104 | } else { 105 | p.push_back(0); 106 | } 107 | } 108 | 109 | // Touch block (12 bytes) 110 | for (int i = 0; i < 12; ++i) { 111 | p.push_back(0); 112 | } 113 | 114 | put_u64(p, sample.timestamp_us); 115 | 116 | // Map accelerometer 117 | float accel_arr[3] = { sample.accel_x, sample.accel_y, sample.accel_z }; 118 | auto accel_get = [&](int idx, bool flip) -> float { 119 | if (idx < 0 || idx > 2) return 0.0f; 120 | float v = accel_arr[idx]; 121 | return flip ? -v : v; 122 | }; 123 | 124 | float ax = accel_get(config.map_accel_x, config.flip_accel_x); 125 | float ay = accel_get(config.map_accel_y, config.flip_accel_y); 126 | float az = accel_get(config.map_accel_z, config.flip_accel_z); 127 | put_f32(p, ax); put_f32(p, ay); put_f32(p, az); 128 | 129 | // Map gyro (convert to degrees) 130 | const float RAD_TO_DEG = 180.0f / 3.14159265358979323846f; 131 | float gyro_arr[3] = { sample.gyro_x * RAD_TO_DEG, sample.gyro_y * RAD_TO_DEG, sample.gyro_z * RAD_TO_DEG }; 132 | auto gyro_get = [&](int idx, bool flip) -> float { 133 | if (idx < 0 || idx > 2) return 0.0f; 134 | float v = gyro_arr[idx]; 135 | return flip ? -v : v; 136 | }; 137 | 138 | float pitch = gyro_get(config.map_pitch, config.flip_pitch); 139 | float yaw = gyro_get(config.map_yaw, config.flip_yaw); 140 | float roll = gyro_get(config.map_roll, config.flip_roll); 141 | put_f32(p, pitch); put_f32(p, yaw); put_f32(p, roll); 142 | 143 | // Button mapping 144 | uint8_t dsubitmask1 = 0; 145 | uint8_t dsubitmask2 = 0; 146 | uint8_t dsuhome = 0; 147 | 148 | using namespace Constants; 149 | if (sample.buttons & Btn_CROSS) dsubitmask2 |= 0x40u; 150 | if (sample.buttons & Btn_CIRCLE) dsubitmask2 |= 0x20u; 151 | if (sample.buttons & Btn_SQUARE) dsubitmask2 |= 0x80u; 152 | if (sample.buttons & Btn_TRIANGLE) dsubitmask2 |= 0x10u; 153 | if (sample.buttons & Btn_MOVE) dsubitmask2 |= 0x08u; 154 | if (sample.buttons & Btn_START) dsubitmask1 |= 0x08u; 155 | if (sample.buttons & Btn_SELECT) dsubitmask1 |= 0x01u; 156 | if (sample.buttons & Btn_PS) dsuhome = 1u; 157 | 158 | if (sample.trigger > Constants::TRIGGER_DIGITAL_THRESHOLD) { 159 | dsubitmask2 |= 0x02u; 160 | } 161 | 162 | // Write control bytes 163 | size_t control_offset = 14; 164 | if (p.size() >= control_offset + 4) { 165 | p[control_offset + 0] = dsubitmask1; 166 | p[control_offset + 1] = dsubitmask2; 167 | p[control_offset + 2] = dsuhome; 168 | } 169 | 170 | // Analog face buttons 171 | size_t analog_base = 18; 172 | if (p.size() >= analog_base + 16) { 173 | p[analog_base + 8] = (sample.buttons & Btn_TRIANGLE) ? 255u : 0u; 174 | p[analog_base + 9] = (sample.buttons & Btn_CIRCLE) ? 255u : 0u; 175 | p[analog_base + 10] = (sample.buttons & Btn_CROSS) ? 255u : 0u; 176 | p[analog_base + 11] = (sample.buttons & Btn_SQUARE) ? 255u : 0u; 177 | p[analog_base + 12] = (sample.buttons & Btn_MOVE) ? 255u : 0u; 178 | } 179 | 180 | // Trigger analog 181 | if (Constants::ANALOG_TRIGGER_INDEX >= 0 && Constants::ANALOG_TRIGGER_INDEX < 16 && 182 | p.size() >= analog_base + 16) { 183 | p[analog_base + Constants::ANALOG_TRIGGER_INDEX] = sample.trigger; 184 | } 185 | 186 | return make_packet(server_id, Constants::MSG_DATA, p); 187 | } 188 | -------------------------------------------------------------------------------- /src/dsu/dsu_protocol.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | struct MoveSample { 6 | float accel_x = 0, accel_y = 0, accel_z = 1.0f; 7 | float gyro_x = 0, gyro_y = 0, gyro_z = 0; 8 | uint64_t timestamp_us = 0; 9 | uint64_t poll_timestamp_us = 0; // NEW: When data was polled from PSMove 10 | uint64_t send_timestamp_us = 0; // NEW: When data was sent over network 11 | unsigned int buttons = 0; 12 | unsigned char trigger = 0; 13 | 14 | // NEW: Get end-to-end latency 15 | uint64_t get_latency_us() const { 16 | if (send_timestamp_us > poll_timestamp_us) { 17 | return send_timestamp_us - poll_timestamp_us; 18 | } 19 | return 0; 20 | } 21 | }; 22 | 23 | class DSUProtocol { 24 | public: 25 | static uint32_t crc32_le(const uint8_t* data, size_t len); 26 | static std::vector make_packet(uint32_t server_id, uint32_t msg_type, const std::vector& payload); 27 | 28 | static std::vector make_protocol_response(uint32_t server_id); 29 | static std::vector make_info_response(uint32_t server_id, uint8_t slot, bool connected, int battery, uint64_t mac); 30 | static std::vector make_data_packet(uint32_t server_id, uint8_t slot, const MoveSample& sample, 31 | uint32_t packet_no, int battery, uint64_t mac, const struct Config& config); 32 | 33 | private: 34 | static void put_u16(std::vector& b, uint16_t v); 35 | static void put_u32(std::vector& b, uint32_t v); 36 | static void put_u64(std::vector& b, uint64_t v); 37 | static void put_f32(std::vector& b, float f); 38 | static void put_shared_begin(std::vector& p, uint8_t slot, uint8_t state_connected, 39 | uint8_t model_fullgyro, uint8_t conn_bt, uint64_t mac48, uint8_t battery); 40 | }; 41 | -------------------------------------------------------------------------------- /src/dsu/dsu_server.cpp: -------------------------------------------------------------------------------- 1 | #include "dsu/dsu_server.hpp" 2 | #include "utils/logging.hpp" 3 | #include "utils/signal_handler.hpp" 4 | #include "config/constants.hpp" 5 | #include 6 | #include 7 | 8 | #ifdef _WIN32 9 | #include 10 | #include 11 | #endif 12 | 13 | DSUServer::DSUServer(const Config& config) 14 | : config_(config) 15 | , server_id_(0x12345678u) 16 | , base_mac_(0x665544332211ULL) 17 | , udp_server_(Constants::DSU_PORT) 18 | , running_(false) { 19 | 20 | for (int i = 0; i < Constants::MAX_CONTROLLERS; i++) { 21 | packet_counters_[i] = 0; 22 | } 23 | } 24 | 25 | DSUServer::~DSUServer() { 26 | stop(); 27 | } 28 | 29 | bool DSUServer::start() { 30 | if (running_.load()) return true; 31 | 32 | // Start PSMove manager 33 | if (!psmove_manager_.start()) { 34 | Logger::error("Failed to start PSMove manager"); 35 | return false; 36 | } 37 | 38 | // Start UDP server 39 | udp_server_.set_message_handler([this](const uint8_t* data, size_t len, const sockaddr_in& from) { 40 | handle_message(data, len, from); 41 | }); 42 | 43 | if (!udp_server_.start()) { 44 | Logger::error("Failed to start UDP server"); 45 | psmove_manager_.stop(); 46 | return false; 47 | } 48 | 49 | running_ = true; 50 | 51 | // Start worker threads 52 | send_thread_ = std::thread(&DSUServer::send_thread_main, this); 53 | 54 | if (!config_.verbose) { 55 | status_thread_ = std::thread(&DSUServer::status_thread_main, this); 56 | } 57 | 58 | Logger::info("DSU server started successfully (optimized for low latency)"); 59 | return true; 60 | } 61 | 62 | void DSUServer::run() { 63 | Logger::info("Multi-controller DSU server running (optimized timing)..."); 64 | if (!config_.verbose) { 65 | Logger::info("Use --verbose for detailed logs and latency monitoring."); 66 | } 67 | 68 | // Wait for shutdown signal 69 | while (SignalHandler::should_exit() == false && running_.load()) { 70 | std::this_thread::sleep_for(std::chrono::milliseconds(100)); 71 | } 72 | 73 | stop(); 74 | } 75 | 76 | void DSUServer::stop() { 77 | running_ = false; 78 | 79 | if (send_thread_.joinable()) send_thread_.join(); 80 | if (status_thread_.joinable()) status_thread_.join(); 81 | 82 | udp_server_.stop(); 83 | psmove_manager_.stop(); 84 | } 85 | 86 | void DSUServer::handle_message(const uint8_t* data, size_t len, const sockaddr_in& from) { 87 | if (len < 20) return; 88 | if (!(data[0] == 'D' && data[1] == 'S' && data[2] == 'U' && data[3] == 'C')) return; 89 | 90 | uint32_t msg_type = uint32_t(data[16]) | (uint32_t(data[17]) << 8) | 91 | (uint32_t(data[18]) << 16) | (uint32_t(data[19]) << 24); 92 | 93 | if (msg_type == Constants::MSG_PROTOCOL_VER) { 94 | auto response = DSUProtocol::make_protocol_response(server_id_); 95 | udp_server_.send_to(response, from); 96 | 97 | } else if (msg_type == Constants::MSG_INFO) { 98 | Logger::debug("Client requesting controller info"); 99 | 100 | // Send info for all controller slots 101 | for (int slot = 0; slot < Constants::MAX_CONTROLLERS; slot++) { 102 | int battery = psmove_manager_.get_battery_level_for_slot(slot); 103 | bool connected = psmove_manager_.has_controller_for_slot(slot); 104 | uint64_t slot_mac = base_mac_ + (static_cast(slot) << 8); 105 | 106 | auto response = DSUProtocol::make_info_response(server_id_, slot, connected, battery, slot_mac); 107 | udp_server_.send_to(response, from); 108 | 109 | Logger::debug("Replied INFO for slot " + std::to_string(slot) + 110 | " (connected: " + (connected ? "yes" : "no") + ")"); 111 | 112 | std::this_thread::sleep_for(std::chrono::microseconds(500)); // Reduced delay 113 | } 114 | 115 | } else if (msg_type == Constants::MSG_DATA) { 116 | std::lock_guard lock(subscription_mutex_); 117 | 118 | // Check if client is already subscribed 119 | bool found = false; 120 | for (const auto& sub : subscriptions_) { 121 | if (sub.addr.sin_addr.s_addr == from.sin_addr.s_addr && 122 | sub.addr.sin_port == from.sin_port) { 123 | found = true; 124 | break; 125 | } 126 | } 127 | 128 | if (!found) { 129 | Subscription new_sub; 130 | new_sub.addr = from; 131 | subscriptions_.push_back(new_sub); 132 | Logger::info("Client subscribed to DATA. Total: " + std::to_string(subscriptions_.size())); 133 | } 134 | } 135 | } 136 | 137 | void DSUServer::send_thread_main() { 138 | // OPTIMIZATION: Set high thread priority 139 | #ifdef _WIN32 140 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); 141 | #else 142 | struct sched_param param; 143 | param.sched_priority = 40; // Lower than PSMove thread but still high 144 | pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m); 145 | #endif 146 | 147 | uint64_t t_us = 0; 148 | int diag_counter = 0; 149 | int latency_warning_counter = 0; 150 | 151 | while (running_.load()) { 152 | auto loop_start = std::chrono::high_resolution_clock::now(); 153 | 154 | // Get copy of subscriptions (minimize lock time) 155 | std::vector subs_copy; 156 | { 157 | std::lock_guard lock(subscription_mutex_); 158 | subs_copy = subscriptions_; 159 | } 160 | 161 | if (!subs_copy.empty()) { 162 | t_us += Constants::DSU_SEND_MS * 1000ull; 163 | 164 | // OPTIMIZATION: Batch processing of all active controllers 165 | std::vector> active_controllers; 166 | std::vector> battery_levels; // slot, battery 167 | 168 | // Collect all data in one pass 169 | for (int slot = 0; slot < Constants::MAX_CONTROLLERS; slot++) { 170 | std::optional sample_opt = psmove_manager_.get_latest_for_slot(slot); 171 | if (sample_opt.has_value()) { 172 | MoveSample sample = sample_opt.value(); 173 | 174 | // OPTIMIZATION: Set send timestamp here for latency measurement 175 | sample.send_timestamp_us = std::chrono::duration_cast( 176 | std::chrono::high_resolution_clock::now().time_since_epoch()).count(); 177 | 178 | active_controllers.emplace_back(slot, sample); 179 | battery_levels.emplace_back(slot, psmove_manager_.get_battery_level_for_slot(slot)); 180 | 181 | // Monitor latency 182 | if (config_.verbose && sample.poll_timestamp_us > 0) { 183 | uint64_t total_latency = sample.get_latency_us(); 184 | if (total_latency > Constants::LATENCY_WARNING_US && 185 | (++latency_warning_counter % 250) == 0) { 186 | Logger::warn("High end-to-end latency for slot " + std::to_string(slot) + 187 | ": " + std::to_string(total_latency) + "µs"); 188 | } 189 | } 190 | } 191 | } 192 | 193 | // OPTIMIZATION: Convert subscribers to address vector for batch sending 194 | std::vector subscriber_addresses; 195 | for (const auto& sub : subs_copy) { 196 | subscriber_addresses.push_back(sub.addr); 197 | } 198 | 199 | // Send data for all active controllers 200 | for (size_t i = 0; i < active_controllers.size(); i++) { 201 | int slot = active_controllers[i].first; 202 | const MoveSample& sample = active_controllers[i].second; 203 | int battery = battery_levels[i].second; 204 | 205 | uint64_t slot_mac = base_mac_ + (static_cast(slot) << 8); 206 | 207 | auto data_packet = DSUProtocol::make_data_packet( 208 | server_id_, slot, sample, packet_counters_[slot]++, battery, slot_mac, config_); 209 | 210 | // OPTIMIZATION: Use batch send 211 | udp_server_.send_to_multiple(data_packet, subscriber_addresses); 212 | } 213 | 214 | // Debug output with performance metrics 215 | if (config_.verbose && !active_controllers.empty() && (++diag_counter % 250) == 0) { 216 | auto loop_end = std::chrono::high_resolution_clock::now(); 217 | auto loop_duration = std::chrono::duration_cast( 218 | loop_end - loop_start).count(); 219 | 220 | Logger::debug("Sent DATA for " + std::to_string(active_controllers.size()) + 221 | " controllers to " + std::to_string(subs_copy.size()) + 222 | " clients (loop: " + std::to_string(loop_duration) + "µs)"); 223 | } 224 | } 225 | 226 | // OPTIMIZATION: High-precision timing 227 | auto next_time = loop_start + std::chrono::microseconds(Constants::DSU_SEND_MS * 1000); 228 | std::this_thread::sleep_until(next_time); 229 | } 230 | } 231 | 232 | void DSUServer::status_thread_main() { 233 | int status_counter = 0; 234 | 235 | while (running_.load()) { 236 | std::this_thread::sleep_for(std::chrono::seconds(5)); 237 | 238 | int connected_count = psmove_manager_.get_connected_count(); 239 | int subscriber_count; 240 | { 241 | std::lock_guard lock(subscription_mutex_); 242 | subscriber_count = static_cast(subscriptions_.size()); 243 | } 244 | 245 | if ((++status_counter % 6) == 0 || connected_count > 0 || subscriber_count > 0) { 246 | Logger::info("Status: " + std::to_string(connected_count) + " controllers, " + 247 | std::to_string(subscriber_count) + " clients (optimized mode)"); 248 | } 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/dsu/dsu_server.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "config/config.hpp" 3 | #include "config/constants.hpp" 4 | #include "network/udp_server.hpp" 5 | #include "psmove/psmove_manager.hpp" 6 | #include "dsu/dsu_protocol.hpp" 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | struct Subscription { 13 | sockaddr_in addr{}; 14 | }; 15 | 16 | class DSUServer { 17 | public: 18 | DSUServer(const Config& config); 19 | ~DSUServer(); 20 | 21 | bool start(); 22 | void run(); 23 | void stop(); 24 | 25 | private: 26 | void handle_message(const uint8_t* data, size_t len, const sockaddr_in& from); 27 | void send_thread_main(); 28 | void status_thread_main(); 29 | 30 | Config config_; 31 | uint32_t server_id_; 32 | uint64_t base_mac_; 33 | 34 | UDPServer udp_server_; 35 | PSMoveManager psmove_manager_; 36 | 37 | std::vector subscriptions_; 38 | std::mutex subscription_mutex_; 39 | 40 | std::thread send_thread_; 41 | std::thread status_thread_; 42 | std::atomic running_; 43 | 44 | uint32_t packet_counters_[Constants::MAX_CONTROLLERS]; 45 | }; 46 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "config/constants.hpp" 2 | #include "config/config.hpp" 3 | #include "utils/logging.hpp" 4 | #include "utils/signal_handler.hpp" 5 | #include "psmove/psmove_pairing.hpp" 6 | #include "dsu/dsu_server.hpp" 7 | #include 8 | #include 9 | 10 | int main(int argc, char** argv) { 11 | Config config; 12 | 13 | // Parse command line arguments 14 | for (int i = 1; i < argc; i++) { 15 | if (std::strcmp(argv[i], "--verbose") == 0) { 16 | config.verbose = true; 17 | Logger::set_verbose(true); 18 | } else if (std::strcmp(argv[i], "--pair") == 0) { 19 | config.pair_mode = true; 20 | } else if (std::strcmp(argv[i], "--map") == 0 && i + 3 < argc) { 21 | config.map_pitch = std::atoi(argv[++i]); 22 | config.map_yaw = std::atoi(argv[++i]); 23 | config.map_roll = std::atoi(argv[++i]); 24 | std::cout << "Mapping set pitch=" << config.map_pitch 25 | << " yaw=" << config.map_yaw 26 | << " roll=" << config.map_roll << "\n"; 27 | } else if (std::strcmp(argv[i], "--flip") == 0 && i + 3 < argc) { 28 | config.flip_pitch = std::atoi(argv[++i]) != 0; 29 | config.flip_yaw = std::atoi(argv[++i]) != 0; 30 | config.flip_roll = std::atoi(argv[++i]) != 0; 31 | std::cout << "Flip set pitch=" << config.flip_pitch 32 | << " yaw=" << config.flip_yaw 33 | << " roll=" << config.flip_roll << "\n"; 34 | } 35 | } 36 | 37 | // Initialize logging 38 | Logger::initialize(config.verbose); 39 | 40 | // Handle pairing mode 41 | if (config.pair_mode) { 42 | PSMovePairing pairing; 43 | return pairing.run_pairing_mode(); 44 | } 45 | 46 | // Setup signal handling 47 | SignalHandler::setup(); 48 | 49 | // Start DSU server 50 | DSUServer server(config); 51 | 52 | Logger::info("DSU server starting..."); 53 | Logger::info("Make sure your controllers are paired using --pair mode first."); 54 | 55 | if (!server.start()) { 56 | Logger::error("Failed to start DSU server"); 57 | return 1; 58 | } 59 | 60 | // Main loop 61 | server.run(); 62 | 63 | Logger::info("DSU server shutdown complete."); 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /src/network/udp_server.cpp: -------------------------------------------------------------------------------- 1 | #include "network/udp_server.hpp" 2 | #include "utils/logging.hpp" 3 | #include 4 | 5 | #ifndef _WIN32 6 | #include 7 | #else 8 | #include 9 | #endif 10 | 11 | UDPServer::UDPServer(int port) : port_(port), sock_(-1), running_(false) { 12 | #ifdef _WIN32 13 | WSADATA wsaData; 14 | if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { 15 | Logger::error("WSAStartup failed"); 16 | } 17 | #endif 18 | } 19 | 20 | UDPServer::~UDPServer() { 21 | stop(); 22 | #ifdef _WIN32 23 | WSACleanup(); 24 | #endif 25 | } 26 | 27 | bool UDPServer::start() { 28 | if (running_.load()) return true; 29 | 30 | #ifdef _WIN32 31 | sock_ = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 32 | if (sock_ == INVALID_SOCKET) { 33 | Logger::error("socket() failed: " + std::to_string(WSAGetLastError())); 34 | return false; 35 | } 36 | #else 37 | sock_ = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 38 | if (sock_ < 0) { 39 | Logger::error("socket() failed"); 40 | return false; 41 | } 42 | #endif 43 | 44 | // OPTIMIZATION: Configure socket for low latency 45 | int opt = 1; 46 | #ifdef _WIN32 47 | setsockopt(sock_, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt)); 48 | 49 | // Increase send buffer size 50 | int sendbuf = 65536; 51 | if (setsockopt(sock_, SOL_SOCKET, SO_SNDBUF, (char*)&sendbuf, sizeof(sendbuf)) != 0) { 52 | Logger::warn("Failed to set send buffer size: " + std::to_string(WSAGetLastError())); 53 | } 54 | 55 | #else 56 | setsockopt(sock_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); 57 | 58 | // Increase send buffer size 59 | int sendbuf = 65536; 60 | if (setsockopt(sock_, SOL_SOCKET, SO_SNDBUF, &sendbuf, sizeof(sendbuf)) != 0) { 61 | Logger::warn("Failed to set send buffer size"); 62 | } 63 | 64 | // Set socket to non-blocking mode for better performance 65 | int flags = fcntl(sock_, F_GETFL, 0); 66 | if (flags >= 0) { 67 | fcntl(sock_, F_SETFL, flags | O_NONBLOCK); 68 | } 69 | 70 | // FIXED: Set high priority for UDP packets (Linux only) 71 | #ifdef __linux__ 72 | int priority = 7; 73 | if (setsockopt(sock_, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) != 0) { 74 | Logger::debug("Could not set socket priority (non-critical)"); 75 | } 76 | #endif 77 | // Note: macOS doesn't support SO_PRIORITY, but that's okay - it's just an optimization 78 | 79 | #endif 80 | 81 | sockaddr_in bind_addr{}; 82 | bind_addr.sin_family = AF_INET; 83 | bind_addr.sin_port = htons(port_); 84 | bind_addr.sin_addr.s_addr = INADDR_ANY; 85 | 86 | if (bind(sock_, (sockaddr*)&bind_addr, sizeof(bind_addr)) < 0) { 87 | #ifdef _WIN32 88 | Logger::error("bind() failed: " + std::to_string(WSAGetLastError())); 89 | CLOSE_SOCKET(sock_); 90 | #else 91 | Logger::error("bind() failed"); 92 | CLOSE_SOCKET(sock_); 93 | #endif 94 | return false; 95 | } 96 | 97 | running_ = true; 98 | receive_thread_ = std::thread(&UDPServer::receive_loop, this); 99 | 100 | Logger::info("UDP server started on port " + std::to_string(port_) + " (optimized for low latency)"); 101 | return true; 102 | } 103 | 104 | void UDPServer::stop() { 105 | running_ = false; 106 | if (receive_thread_.joinable()) { 107 | receive_thread_.join(); 108 | } 109 | if (sock_ >= 0) { 110 | CLOSE_SOCKET(sock_); 111 | sock_ = -1; 112 | } 113 | } 114 | 115 | void UDPServer::send_to(const std::vector& data, const sockaddr_in& addr) { 116 | if (!running_.load() || sock_ < 0) return; 117 | 118 | #ifdef _WIN32 119 | int result = sendto(sock_, (char*)data.data(), (int)data.size(), 0, (sockaddr*)&addr, sizeof(addr)); 120 | if (result == SOCKET_ERROR) { 121 | int error = WSAGetLastError(); 122 | if (error != WSAEWOULDBLOCK) { 123 | Logger::debug("sendto failed: " + std::to_string(error)); 124 | } 125 | } 126 | #else 127 | ssize_t result = sendto(sock_, data.data(), data.size(), MSG_DONTWAIT, (sockaddr*)&addr, sizeof(addr)); 128 | if (result < 0) { 129 | if (errno != EAGAIN && errno != EWOULDBLOCK) { 130 | Logger::debug("sendto failed: " + std::string(strerror(errno))); 131 | } 132 | } 133 | #endif 134 | } 135 | 136 | void UDPServer::send_to_multiple(const std::vector& data, const std::vector& addresses) { 137 | if (!running_.load() || sock_ < 0) return; 138 | 139 | // OPTIMIZATION: Batch send operations 140 | for (const auto& addr : addresses) { 141 | #ifdef _WIN32 142 | sendto(sock_, (char*)data.data(), (int)data.size(), 0, (sockaddr*)&addr, sizeof(addr)); 143 | #else 144 | sendto(sock_, data.data(), data.size(), MSG_DONTWAIT, (sockaddr*)&addr, sizeof(addr)); 145 | #endif 146 | } 147 | } 148 | 149 | void UDPServer::set_message_handler(MessageHandler handler) { 150 | message_handler_ = handler; 151 | } 152 | 153 | void UDPServer::receive_loop() { 154 | uint8_t buffer[2048]; 155 | 156 | // OPTIMIZATION: Set thread priority for network thread 157 | #ifdef _WIN32 158 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); 159 | #endif 160 | 161 | while (running_.load()) { 162 | sockaddr_in from{}; 163 | socklen_t from_len = sizeof(from); 164 | 165 | #ifdef _WIN32 166 | int bytes = recvfrom(sock_, (char*)buffer, sizeof(buffer), 0, (sockaddr*)&from, &from_len); 167 | if (bytes == SOCKET_ERROR) { 168 | int error = WSAGetLastError(); 169 | if (error == WSAEWOULDBLOCK || error == WSAEINTR) { 170 | std::this_thread::sleep_for(std::chrono::microseconds(100)); 171 | continue; 172 | } 173 | } 174 | #else 175 | ssize_t bytes = recvfrom(sock_, buffer, sizeof(buffer), MSG_DONTWAIT, (sockaddr*)&from, &from_len); 176 | if (bytes < 0) { 177 | if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { 178 | std::this_thread::sleep_for(std::chrono::microseconds(100)); 179 | continue; 180 | } 181 | } 182 | #endif 183 | 184 | if (!running_.load()) break; 185 | if (bytes < 0) continue; 186 | 187 | if (message_handler_) { 188 | message_handler_(buffer, bytes, from); 189 | } 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /src/network/udp_server.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "utils/platform.hpp" 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | class UDPServer { 9 | public: 10 | using MessageHandler = std::function; 11 | 12 | UDPServer(int port); 13 | ~UDPServer(); 14 | 15 | bool start(); 16 | void stop(); 17 | void send_to(const std::vector& data, const sockaddr_in& addr); 18 | 19 | // NEW: Batch send for better performance 20 | void send_to_multiple(const std::vector& data, const std::vector& addresses); 21 | 22 | void set_message_handler(MessageHandler handler); 23 | 24 | bool is_running() const { return running_.load(); } 25 | 26 | private: 27 | void receive_loop(); 28 | 29 | int port_; 30 | int sock_; 31 | std::atomic running_; 32 | MessageHandler message_handler_; 33 | std::thread receive_thread_; 34 | }; 35 | -------------------------------------------------------------------------------- /src/psmove/psmove_manager.cpp: -------------------------------------------------------------------------------- 1 | #include "psmove/psmove_manager.hpp" 2 | #include "utils/logging.hpp" 3 | #include 4 | #include 5 | #include 6 | 7 | #ifdef _WIN32 8 | #include 9 | #include // For timeBeginPeriod 10 | #include // For thread priority 11 | #pragma comment(lib, "winmm.lib") 12 | #endif 13 | 14 | PSMoveManager::PSMoveManager() : running_(false) { 15 | for (int i = 0; i < Constants::MAX_CONTROLLERS; i++) { 16 | controllers_[i] = nullptr; 17 | has_data_[i] = false; 18 | current_buffer_[i].store(0); 19 | latest_atomic_[i].store(nullptr); 20 | } 21 | } 22 | 23 | PSMoveManager::~PSMoveManager() { 24 | stop(); 25 | } 26 | 27 | bool PSMoveManager::start() { 28 | if (running_.load()) return true; 29 | 30 | #ifdef _WIN32 31 | // CRITICAL FIX: Set Windows to 1ms timer resolution 32 | if (timeBeginPeriod(1) != TIMERR_NOERROR) { 33 | Logger::warn("Failed to set 1ms timer resolution - may have higher latency"); 34 | } else { 35 | Logger::info("Windows 1ms timer resolution enabled"); 36 | } 37 | #endif 38 | 39 | running_ = true; 40 | 41 | // Start background scanner thread FIRST 42 | scanner_thread_ = std::thread(&PSMoveManager::scanner_thread_main, this); 43 | 44 | // Start main polling thread 45 | worker_ = std::thread(&PSMoveManager::thread_main, this); 46 | 47 | Logger::debug("PSMove manager started with background scanning (zero-latency)"); 48 | return true; 49 | } 50 | 51 | void PSMoveManager::stop() { 52 | running_ = false; 53 | 54 | // Join threads 55 | if (scanner_thread_.joinable()) { 56 | scanner_thread_.join(); 57 | } 58 | if (worker_.joinable()) { 59 | worker_.join(); 60 | } 61 | 62 | #ifdef _WIN32 63 | // Restore Windows timer resolution 64 | timeEndPeriod(1); 65 | #endif 66 | 67 | // Cleanup controllers 68 | std::lock_guard lk(mtx_); 69 | for (int i = 0; i < Constants::MAX_CONTROLLERS; i++) { 70 | if (controllers_[i]) { 71 | psmove_disconnect(controllers_[i]); 72 | controllers_[i] = nullptr; 73 | } 74 | latest_atomic_[i].store(nullptr); 75 | } 76 | 77 | // Cleanup pending controllers 78 | { 79 | std::lock_guard pending_lock(pending_controllers_mutex_); 80 | for (auto& pending : pending_controllers_) { 81 | if (pending.controller) { 82 | psmove_disconnect(pending.controller); 83 | } 84 | } 85 | pending_controllers_.clear(); 86 | } 87 | } 88 | 89 | std::optional PSMoveManager::get_latest_for_slot(int slot) { 90 | if (slot < 0 || slot >= Constants::MAX_CONTROLLERS) { 91 | Logger::debug("Invalid slot requested: " + std::to_string(slot)); 92 | return {}; 93 | } 94 | 95 | // OPTIMIZATION: Use atomic access instead of mutex 96 | MoveSample* current = latest_atomic_[slot].load(std::memory_order_acquire); 97 | if (!current) { 98 | return {}; 99 | } 100 | 101 | // Check data freshness 102 | auto now = std::chrono::duration_cast( 103 | std::chrono::steady_clock::now().time_since_epoch()).count(); 104 | 105 | if (now - current->timestamp_us > 100000) { // 100ms threshold for stale data warning 106 | Logger::debug("Potentially stale data for slot " + std::to_string(slot) + 107 | " (age: " + std::to_string((now - current->timestamp_us) / 1000) + "ms)"); 108 | } 109 | 110 | return *current; 111 | } 112 | 113 | int PSMoveManager::get_battery_level_for_slot(int slot) { 114 | if (slot < 0 || slot >= Constants::MAX_CONTROLLERS) return -1; 115 | std::lock_guard lk(mtx_); 116 | if (!controllers_[slot]) return -1; 117 | return psmove_get_battery(controllers_[slot]); 118 | } 119 | 120 | bool PSMoveManager::has_controller_for_slot(int slot) { 121 | if (slot < 0 || slot >= Constants::MAX_CONTROLLERS) return false; 122 | std::lock_guard lk(mtx_); 123 | return controllers_[slot] != nullptr; 124 | } 125 | 126 | std::string PSMoveManager::get_controller_serial_for_slot(int slot) { 127 | if (slot < 0 || slot >= Constants::MAX_CONTROLLERS) return "INVALID_SLOT"; 128 | std::lock_guard lk(mtx_); 129 | if (!controllers_[slot]) return "NO_CONTROLLER"; 130 | return get_serial_safe(controllers_[slot]); 131 | } 132 | 133 | int PSMoveManager::get_connected_count() { 134 | std::lock_guard lk(mtx_); 135 | int count = 0; 136 | for (int i = 0; i < Constants::MAX_CONTROLLERS; i++) { 137 | if (controllers_[i]) count++; 138 | } 139 | return count; 140 | } 141 | 142 | void PSMoveManager::thread_main() { 143 | // OPTIMIZATION: Set high thread priority for consistent timing 144 | #ifdef _WIN32 145 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); 146 | DWORD_PTR mask = 1; 147 | if (SetThreadAffinityMask(GetCurrentThread(), mask) == 0) { 148 | Logger::debug("Could not set thread affinity (non-critical)"); 149 | } else { 150 | Logger::debug("Polling thread pinned to CPU core 0"); 151 | } 152 | #else 153 | struct sched_param param; 154 | param.sched_priority = 50; 155 | if (pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m) != 0) { 156 | Logger::debug("Could not set real-time priority (try running as root)"); 157 | } 158 | #endif 159 | 160 | // REMOVED: auto last_scan and scan_interval - no longer needed! 161 | int debug_counter = 0; 162 | int latency_warning_counter = 0; 163 | int flush_counter = 0; 164 | 165 | // Request initial scan 166 | scan_requested_.store(true); 167 | 168 | while (running_) { 169 | auto loop_start = std::chrono::steady_clock::now(); 170 | 171 | // OPTIMIZATION: Integrate any newly discovered controllers (fast operation) 172 | integrate_pending_controllers(); 173 | 174 | // Poll all connected controllers (unchanged) 175 | { 176 | std::lock_guard lk(mtx_); 177 | for (int slot = 0; slot < Constants::MAX_CONTROLLERS; slot++) { 178 | if (!controllers_[slot]) { 179 | has_data_[slot] = false; 180 | latest_atomic_[slot].store(nullptr, std::memory_order_release); 181 | continue; 182 | } 183 | 184 | // Verify controller is still valid 185 | if (psmove_connection_type(controllers_[slot]) == Conn_Unknown) { 186 | Logger::error("Controller in slot " + std::to_string(slot) + " became invalid, removing"); 187 | psmove_disconnect(controllers_[slot]); 188 | controllers_[slot] = nullptr; 189 | has_data_[slot] = false; 190 | latest_atomic_[slot].store(nullptr, std::memory_order_release); 191 | 192 | // Request rescan after controller loss 193 | scan_requested_.store(true); 194 | continue; 195 | } 196 | 197 | uint64_t poll_timestamp = std::chrono::duration_cast( 198 | std::chrono::high_resolution_clock::now().time_since_epoch()).count(); 199 | 200 | // Windows polling logic (unchanged) 201 | bool got_data = false; 202 | int poll_attempts = 0; 203 | 204 | #ifdef _WIN32 205 | const int max_attempts = 5; 206 | for (int attempt = 0; attempt < max_attempts && !got_data; attempt++) { 207 | got_data = psmove_poll(controllers_[slot]); 208 | poll_attempts++; 209 | if (!got_data && attempt < max_attempts - 1) { 210 | std::this_thread::sleep_for(std::chrono::microseconds(200)); 211 | } 212 | } 213 | 214 | if ((++flush_counter % 200) == 0) { 215 | int flushed = 0; 216 | while (psmove_poll(controllers_[slot]) && flushed < 50) { 217 | flushed++; 218 | } 219 | if (flushed > 5) { 220 | Logger::warn("Windows: Flushed " + std::to_string(flushed) + 221 | " buffered packets from slot " + std::to_string(slot)); 222 | } 223 | } 224 | #else 225 | got_data = psmove_poll(controllers_[slot]); 226 | poll_attempts = 1; 227 | #endif 228 | 229 | if (!got_data) { 230 | continue; 231 | } 232 | 233 | // Read sensor data (unchanged) 234 | float ax = 0, ay = 0, az = 0; 235 | psmove_get_accelerometer_frame(controllers_[slot], Frame_SecondHalf, &ax, &ay, &az); 236 | 237 | float gx = 0, gy = 0, gz = 0; 238 | psmove_get_gyroscope_frame(controllers_[slot], Frame_SecondHalf, &gx, &gy, &gz); 239 | 240 | unsigned int btns = psmove_get_buttons(controllers_[slot]); 241 | unsigned char trig = psmove_get_trigger(controllers_[slot]); 242 | 243 | uint64_t ts = std::chrono::duration_cast( 244 | std::chrono::steady_clock::now().time_since_epoch()).count(); 245 | 246 | // Double buffering (unchanged) 247 | int current_buf = current_buffer_[slot].load(); 248 | int next_buf = 1 - current_buf; 249 | 250 | MoveSample& sample = samples_[slot][next_buf]; 251 | sample.accel_x = ax; sample.accel_y = ay; sample.accel_z = az; 252 | sample.gyro_x = gx; sample.gyro_y = gy; sample.gyro_z = gz; 253 | sample.buttons = btns; 254 | sample.trigger = trig; 255 | sample.timestamp_us = ts; 256 | sample.poll_timestamp_us = poll_timestamp; 257 | sample.send_timestamp_us = 0; 258 | 259 | current_buffer_[slot].store(next_buf); 260 | latest_atomic_[slot].store(&sample, std::memory_order_release); 261 | has_data_[slot] = true; 262 | 263 | // Debug output (unchanged) 264 | if (slot == 0 && (++debug_counter % 1000) == 0) { 265 | uint64_t processing_latency = ts - poll_timestamp; 266 | Logger::info("Slot " + std::to_string(slot) + " - " + 267 | get_serial_safe(controllers_[slot]) + 268 | " | Processing: " + std::to_string(processing_latency) + "µs" + 269 | " | Poll attempts: " + std::to_string(poll_attempts)); 270 | 271 | if (processing_latency > 50000) { 272 | Logger::error("CRITICAL: Very high processing latency: " + 273 | std::to_string(processing_latency) + "µs"); 274 | } 275 | } 276 | } 277 | } 278 | 279 | // High-precision timing (unchanged) 280 | auto next_time = loop_start + std::chrono::microseconds(Constants::PSMOVE_POLL_MS * 1000); 281 | 282 | #ifdef _WIN32 283 | while (std::chrono::steady_clock::now() < next_time) { 284 | std::this_thread::sleep_for(std::chrono::microseconds(50)); 285 | } 286 | #else 287 | std::this_thread::sleep_until(next_time); 288 | #endif 289 | } 290 | } 291 | 292 | // NEW: Background scanner thread 293 | void PSMoveManager::scanner_thread_main() { 294 | // Lower priority than main polling thread 295 | #ifdef _WIN32 296 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); 297 | #else 298 | struct sched_param param; 299 | param.sched_priority = 30; // Lower than polling thread 300 | pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m); 301 | #endif 302 | 303 | while (running_) { 304 | // Check if scan is requested 305 | if (scan_requested_.exchange(false)) { 306 | Logger::debug("=== BACKGROUND CONTROLLER SCAN START ==="); 307 | scan_for_controllers_async(); 308 | Logger::debug("=== BACKGROUND SCAN COMPLETE ==="); 309 | } 310 | 311 | // Check every 100ms, but also periodically request scans 312 | static int scan_timer = 0; 313 | if (++scan_timer >= 50) { // Every 5 seconds (50 * 100ms) 314 | scan_timer = 0; 315 | scan_requested_.store(true); 316 | } 317 | 318 | std::this_thread::sleep_for(std::chrono::milliseconds(100)); 319 | } 320 | } 321 | 322 | // NEW: Non-blocking controller scan 323 | void PSMoveManager::scan_for_controllers_async() { 324 | std::vector available_controllers; 325 | std::vector available_serials; 326 | 327 | // Scan for controllers (this is the slow part, but now in background) 328 | for (int id = 0; id < 8; id++) { 329 | PSMove* controller = psmove_connect_by_id(id); 330 | if (!controller) continue; 331 | 332 | std::string serial = get_serial_safe(controller); 333 | std::string conn_type = get_connection_type_string(controller); 334 | 335 | if (conn_type != "BT") { 336 | Logger::debug("Skipping " + serial + " (" + conn_type + ") - not Bluetooth"); 337 | psmove_disconnect(controller); 338 | continue; 339 | } 340 | 341 | // Check if already connected (need mutex for this check) 342 | bool already_connected = false; 343 | { 344 | std::lock_guard lk(mtx_); 345 | if (find_serial_slot(serial) >= 0) { 346 | already_connected = true; 347 | } 348 | } 349 | 350 | if (already_connected) { 351 | Logger::debug("Skipping " + serial + " - already connected"); 352 | psmove_disconnect(controller); 353 | continue; 354 | } 355 | 356 | available_controllers.push_back(controller); 357 | available_serials.push_back(serial); 358 | Logger::debug("Found " + serial + " (" + conn_type + ")"); 359 | } 360 | 361 | // Queue new controllers for integration 362 | { 363 | std::lock_guard pending_lock(pending_controllers_mutex_); 364 | 365 | for (size_t i = 0; i < available_controllers.size(); i++) { 366 | PSMove* controller = available_controllers[i]; 367 | std::string serial = available_serials[i]; 368 | 369 | // Find target slot 370 | int target_slot = -1; 371 | { 372 | std::lock_guard lk(mtx_); 373 | for (int slot = 0; slot < Constants::MAX_CONTROLLERS; slot++) { 374 | if (!controllers_[slot]) { 375 | target_slot = slot; 376 | break; 377 | } 378 | } 379 | } 380 | 381 | if (target_slot == -1) { 382 | Logger::warn("No free slots for " + serial); 383 | psmove_disconnect(controller); 384 | continue; 385 | } 386 | 387 | // Initialize controller in background 388 | #ifdef _WIN32 389 | psmove_set_leds(controller, 0, 0, 0); 390 | psmove_update_leds(controller); 391 | 392 | int drained = 0; 393 | while (psmove_poll(controller) && drained < 100) { 394 | drained++; 395 | } 396 | if (drained > 0) { 397 | Logger::info("Windows: Drained " + std::to_string(drained) + 398 | " initial buffered packets from " + serial); 399 | } 400 | #endif 401 | 402 | PendingController pending = {controller, serial, target_slot}; 403 | pending_controllers_.push_back(pending); 404 | 405 | Logger::info("Queued " + serial + " for assignment to Slot " + std::to_string(target_slot)); 406 | } 407 | } 408 | } 409 | 410 | // NEW: Fast integration of discovered controllers 411 | void PSMoveManager::integrate_pending_controllers() { 412 | std::lock_guard pending_lock(pending_controllers_mutex_); 413 | 414 | if (pending_controllers_.empty()) { 415 | return; 416 | } 417 | 418 | // Brief lock to integrate controllers 419 | { 420 | std::lock_guard lk(mtx_); 421 | 422 | for (auto& pending : pending_controllers_) { 423 | if (pending.target_slot >= 0 && pending.target_slot < Constants::MAX_CONTROLLERS && 424 | !controllers_[pending.target_slot]) { 425 | 426 | controllers_[pending.target_slot] = pending.controller; 427 | has_data_[pending.target_slot] = false; 428 | latest_atomic_[pending.target_slot].store(nullptr, std::memory_order_release); 429 | 430 | Logger::info("Integrated " + pending.serial + " -> Slot " + std::to_string(pending.target_slot)); 431 | } else { 432 | // Slot taken, disconnect 433 | Logger::warn("Slot " + std::to_string(pending.target_slot) + " taken, disconnecting " + pending.serial); 434 | psmove_disconnect(pending.controller); 435 | } 436 | } 437 | } 438 | 439 | pending_controllers_.clear(); 440 | } 441 | 442 | std::string PSMoveManager::get_serial_safe(PSMove* controller) { 443 | if (!controller) return ""; 444 | char* serial = psmove_get_serial(controller); 445 | return serial ? std::string(serial) : ""; 446 | } 447 | 448 | std::string PSMoveManager::get_connection_type_string(PSMove* controller) { 449 | if (!controller) return "NONE"; 450 | auto conn = psmove_connection_type(controller); 451 | return (conn == Conn_Bluetooth) ? "BT" : (conn == Conn_USB) ? "USB" : "UNKNOWN"; 452 | } 453 | 454 | int PSMoveManager::find_serial_slot(const std::string& serial) { 455 | if (serial.empty()) return -1; 456 | for (int i = 0; i < Constants::MAX_CONTROLLERS; i++) { 457 | if (controllers_[i] && get_serial_safe(controllers_[i]) == serial) { 458 | return i; 459 | } 460 | } 461 | return -1; 462 | } 463 | -------------------------------------------------------------------------------- /src/psmove/psmove_manager.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "dsu/dsu_protocol.hpp" 3 | #include "config/constants.hpp" 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #ifndef _WIN32 13 | #include 14 | #include 15 | #endif 16 | 17 | class PSMoveManager { 18 | public: 19 | PSMoveManager(); 20 | ~PSMoveManager(); 21 | 22 | bool start(); 23 | void stop(); 24 | 25 | std::optional get_latest_for_slot(int slot); 26 | int get_battery_level_for_slot(int slot); 27 | bool has_controller_for_slot(int slot); 28 | std::string get_controller_serial_for_slot(int slot); 29 | int get_connected_count(); 30 | 31 | private: 32 | void thread_main(); 33 | std::string get_serial_safe(PSMove* controller); 34 | std::string get_connection_type_string(PSMove* controller); 35 | int find_serial_slot(const std::string& serial); 36 | 37 | // NEW: Background scanning methods 38 | void scanner_thread_main(); 39 | void scan_for_controllers_async(); 40 | void integrate_scanned_controller(PSMove* controller, const std::string& serial, int target_slot); 41 | void integrate_pending_controllers(); 42 | 43 | PSMove* controllers_[Constants::MAX_CONTROLLERS]; 44 | bool has_data_[Constants::MAX_CONTROLLERS]; 45 | 46 | // OPTIMIZATION: Lock-free double buffering for sample data 47 | MoveSample samples_[Constants::MAX_CONTROLLERS][2]; // Double buffer per controller 48 | std::atomic current_buffer_[Constants::MAX_CONTROLLERS]; // Which buffer is current 49 | std::atomic latest_atomic_[Constants::MAX_CONTROLLERS]; // Atomic pointer to current data 50 | 51 | std::thread worker_; 52 | std::atomic running_; 53 | std::mutex mtx_; // Only for controller management, not data access 54 | 55 | // NEW: Scanner thread members 56 | std::thread scanner_thread_; 57 | std::atomic scan_requested_{false}; 58 | std::mutex pending_controllers_mutex_; 59 | 60 | struct PendingController { 61 | PSMove* controller; 62 | std::string serial; 63 | int target_slot; 64 | }; 65 | std::vector pending_controllers_; 66 | }; 67 | -------------------------------------------------------------------------------- /src/psmove/psmove_pairing.cpp: -------------------------------------------------------------------------------- 1 | #include "psmove/psmove_pairing.hpp" 2 | #include "utils/logging.hpp" 3 | #include "utils/platform.hpp" 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | void PSMovePairing::wait_for_keypress() { 11 | std::cout << "Press ENTER to continue..."; 12 | std::cout.flush(); 13 | 14 | while (true) { 15 | int ch = getchar(); 16 | if (ch == ' ' || ch == '\n' || ch == '\r') { 17 | break; 18 | } 19 | } 20 | std::cout << std::endl; 21 | } 22 | 23 | std::string PSMovePairing::format_mac_address(const char* serial) { 24 | if (!serial || strlen(serial) < 12) { 25 | return "UNKNOWN"; 26 | } 27 | 28 | std::string mac; 29 | for (int i = 0; i < 12; i += 2) { 30 | if (i > 0) mac += ":"; 31 | mac += serial[i]; 32 | mac += serial[i + 1]; 33 | } 34 | return mac; 35 | } 36 | 37 | int PSMovePairing::run_pairing_mode() { 38 | std::cout << "\n=== PS Move Controller Pairing Mode ===\n"; 39 | Logger::debug("Initializing PSMoveAPI..."); 40 | 41 | // Test basic functionality 42 | int initial_count = psmove_count_connected(); 43 | Logger::debug("Initial USB controller count: " + std::to_string(initial_count)); 44 | 45 | // Check existing Bluetooth controllers 46 | PSMove* test_bt = psmove_connect(); 47 | if (test_bt) { 48 | char* bt_serial = psmove_get_serial(test_bt); 49 | Logger::debug("Found existing Bluetooth controller: " + std::string(bt_serial ? bt_serial : "UNKNOWN")); 50 | psmove_disconnect(test_bt); 51 | } else { 52 | Logger::debug("No existing Bluetooth controllers found"); 53 | } 54 | 55 | std::cout << "\n"; 56 | 57 | // Step 1: Disconnect all controllers 58 | std::cout << "1. Disconnect all PS Move devices from your computer.\n"; 59 | wait_for_keypress(); 60 | 61 | // Step 2: Connect via USB 62 | std::cout << "2. Connect the controller you would like to pair to your computer using a USB cable.\n"; 63 | std::cout << " Do not power it on. Detecting...\n"; 64 | 65 | // Wait for USB controller 66 | PSMove* usb_controller = nullptr; 67 | std::cout << "Waiting for USB controller"; 68 | 69 | for (int attempts = 0; attempts < 60; attempts++) { 70 | std::this_thread::sleep_for(std::chrono::milliseconds(500)); 71 | std::cout << "." << std::flush; 72 | 73 | int count = psmove_count_connected(); 74 | if (count > 0) { 75 | if (attempts % 10 == 0) { 76 | std::cout << "\n Found " << count << " USB device(s), attempting connection..." << std::flush; 77 | } 78 | 79 | usb_controller = psmove_connect_by_id(0); 80 | if (usb_controller) { 81 | PSMove_Connection_Type conn_type = psmove_connection_type(usb_controller); 82 | if (conn_type == Conn_USB) { 83 | char* test_serial = psmove_get_serial(usb_controller); 84 | if (test_serial && strlen(test_serial) > 0) { 85 | break; // Success! 86 | } else { 87 | Logger::debug("Controller detected but not responsive, retrying..."); 88 | psmove_disconnect(usb_controller); 89 | usb_controller = nullptr; 90 | } 91 | } else { 92 | Logger::debug("Controller detected but not USB connection, retrying..."); 93 | psmove_disconnect(usb_controller); 94 | usb_controller = nullptr; 95 | } 96 | } 97 | } 98 | } 99 | 100 | std::cout << std::endl; 101 | 102 | if (!usb_controller) { 103 | Logger::error("No USB controller detected. Make sure the controller is connected via USB cable."); 104 | return 1; 105 | } 106 | 107 | // Step 3: Get controller info and pair 108 | char* serial = psmove_get_serial(usb_controller); 109 | if (!serial) { 110 | Logger::error("Could not read controller serial number."); 111 | psmove_disconnect(usb_controller); 112 | return 1; 113 | } 114 | 115 | std::string mac_addr = format_mac_address(serial); 116 | std::cout << "3. Detected! Pairing process initiated with controller " << mac_addr << ".\n"; 117 | 118 | if (psmove_connection_type(usb_controller) != Conn_USB) { 119 | Logger::error("Controller is not connected via USB."); 120 | psmove_disconnect(usb_controller); 121 | return 1; 122 | } 123 | 124 | std::cout << " Writing pairing data to controller...\n"; 125 | 126 | // Try standard pairing 127 | int pair_result = psmove_pair(usb_controller); 128 | if (pair_result != 1) { 129 | Logger::error("Pairing failed. This could indicate USB communication issue, controller malfunction, or Bluetooth adapter not working properly."); 130 | psmove_disconnect(usb_controller); 131 | return 1; 132 | } 133 | 134 | std::cout << " Pairing succeeded!\n"; 135 | std::cout << "4. Computer host address written to controller.\n"; 136 | psmove_disconnect(usb_controller); 137 | 138 | // Step 4: Disconnect USB and restart 139 | std::cout << "5. Disconnect the controller from your computer.\n"; 140 | std::cout << "6. RESTART YOUR COMPUTER for the pairing to take effect.\n"; 141 | std::cout << "7. After restart, power on your controller by pressing the PS button.\n\n"; 142 | 143 | std::cout << "=== Pairing Complete ===\n"; 144 | std::cout << "The pairing data has been written to your controller.\n"; 145 | std::cout << "Please restart your computer, then run the DSU server normally to use your paired controller.\n"; 146 | 147 | wait_for_keypress(); 148 | 149 | return 0; 150 | } 151 | -------------------------------------------------------------------------------- /src/psmove/psmove_pairing.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class PSMovePairing { 5 | public: 6 | int run_pairing_mode(); 7 | 8 | private: 9 | void wait_for_keypress(); 10 | std::string format_mac_address(const char* serial); 11 | }; 12 | -------------------------------------------------------------------------------- /src/utils/logging.cpp: -------------------------------------------------------------------------------- 1 | #include "utils/logging.hpp" 2 | #include 3 | #include 4 | 5 | bool Logger::verbose_ = false; 6 | std::mutex Logger::mutex_; 7 | 8 | void Logger::initialize(bool verbose) { 9 | verbose_ = verbose; 10 | } 11 | 12 | void Logger::set_verbose(bool verbose) { 13 | verbose_ = verbose; 14 | } 15 | 16 | void Logger::info(const std::string& message) { 17 | std::lock_guard lock(mutex_); 18 | std::cout << "[INFO] " << message << std::endl; 19 | } 20 | 21 | void Logger::debug(const std::string& message) { 22 | if (!verbose_) return; 23 | std::lock_guard lock(mutex_); 24 | std::cout << "[DEBUG] " << message << std::endl; 25 | } 26 | 27 | void Logger::error(const std::string& message) { 28 | std::lock_guard lock(mutex_); 29 | std::cerr << "[ERROR] " << message << std::endl; 30 | } 31 | 32 | void Logger::warn(const std::string& message) { 33 | std::lock_guard lock(mutex_); 34 | std::cout << "[WARN] " << message << std::endl; 35 | } 36 | -------------------------------------------------------------------------------- /src/utils/logging.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | 6 | class Logger { 7 | public: 8 | static void initialize(bool verbose); 9 | static void set_verbose(bool verbose); 10 | 11 | static void info(const std::string& message); 12 | static void debug(const std::string& message); 13 | static void error(const std::string& message); 14 | static void warn(const std::string& message); 15 | 16 | private: 17 | static bool verbose_; 18 | static std::mutex mutex_; 19 | }; 20 | -------------------------------------------------------------------------------- /src/utils/platform.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #ifdef _WIN32 4 | // Prevent old winsock.h from being included anywhere 5 | #ifndef _WINSOCKAPI_ 6 | #define _WINSOCKAPI_ 7 | #endif 8 | 9 | // Configure Windows headers 10 | #ifndef WIN32_LEAN_AND_MEAN 11 | #define WIN32_LEAN_AND_MEAN 12 | #endif 13 | #ifndef NOMINMAX 14 | #define NOMINMAX 15 | #endif 16 | 17 | // Include networking headers in correct order 18 | #include 19 | #include 20 | #include // For advanced TCP/UDP options 21 | 22 | // Now windows.h won't include winsock.h 23 | #include 24 | 25 | #pragma comment(lib, "ws2_32.lib") 26 | typedef int socklen_t; 27 | #define CLOSE_SOCKET closesocket 28 | #else 29 | #include 30 | #include 31 | #include // For TCP_NODELAY 32 | #include 33 | #include 34 | #include // For O_NONBLOCK 35 | #include // For errno 36 | #include // For strerror 37 | #define CLOSE_SOCKET close 38 | #endif 39 | -------------------------------------------------------------------------------- /src/utils/signal_handler.cpp: -------------------------------------------------------------------------------- 1 | #include "utils/signal_handler.hpp" 2 | 3 | std::atomic SignalHandler::exit_requested_(false); 4 | 5 | void SignalHandler::setup() { 6 | #ifdef _WIN32 7 | SetConsoleCtrlHandler(console_ctrl_handler, TRUE); 8 | #else 9 | signal(SIGINT, handle_sigint); 10 | signal(SIGTERM, handle_sigint); 11 | #endif 12 | } 13 | 14 | bool SignalHandler::should_exit() { 15 | return exit_requested_.load(); 16 | } 17 | 18 | #ifdef _WIN32 19 | BOOL WINAPI SignalHandler::console_ctrl_handler(DWORD dwCtrlType) { 20 | switch (dwCtrlType) { 21 | case CTRL_C_EVENT: 22 | case CTRL_BREAK_EVENT: 23 | case CTRL_CLOSE_EVENT: 24 | case CTRL_SHUTDOWN_EVENT: 25 | exit_requested_ = true; 26 | return TRUE; 27 | default: 28 | return FALSE; 29 | } 30 | } 31 | #else 32 | void SignalHandler::handle_sigint(int) { 33 | exit_requested_ = true; 34 | } 35 | #endif 36 | -------------------------------------------------------------------------------- /src/utils/signal_handler.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #ifdef _WIN32 6 | #include 7 | #endif 8 | 9 | class SignalHandler { 10 | public: 11 | static void setup(); 12 | static bool should_exit(); 13 | 14 | private: 15 | static std::atomic exit_requested_; 16 | 17 | #ifdef _WIN32 18 | static BOOL WINAPI console_ctrl_handler(DWORD dwCtrlType); 19 | #else 20 | static void handle_sigint(int); 21 | #endif 22 | }; 23 | -------------------------------------------------------------------------------- /test/DummyDSUServer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // DSU protocol constants 8 | constexpr int DSU_PORT = 26760; 9 | constexpr float DEG_TO_RAD = M_PI / 180.0f; 10 | 11 | #pragma pack(push, 1) 12 | struct DSUMotionPacket { 13 | uint8_t header[4]; // "DSUS" 14 | uint16_t protocol_version; 15 | uint8_t message_type; // 0x01 = motion data 16 | uint8_t slot; // Controller slot (0) 17 | uint64_t mac; // Fake MAC 18 | uint8_t connected; // 1 if connected 19 | uint8_t battery; // 0xEE = charging, 0xEF = full 20 | float gyro[3]; // rad/s 21 | float accel[3]; // m/s² 22 | uint64_t timestamp; // microseconds 23 | }; 24 | #pragma pack(pop) 25 | 26 | int main() { 27 | int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 28 | if (sock < 0) { 29 | perror("socket"); 30 | return 1; 31 | } 32 | 33 | sockaddr_in server_addr{}; 34 | server_addr.sin_family = AF_INET; 35 | server_addr.sin_port = htons(DSU_PORT); 36 | server_addr.sin_addr.s_addr = INADDR_ANY; 37 | 38 | if (bind(sock, (sockaddr*)&server_addr, sizeof(server_addr)) < 0) { 39 | perror("bind"); 40 | return 1; 41 | } 42 | 43 | std::cout << "DSU server running on port " << DSU_PORT << "\n"; 44 | 45 | sockaddr_in client_addr{}; 46 | socklen_t client_len = sizeof(client_addr); 47 | 48 | // Wait for a handshake packet from Dolphin 49 | char buf[1024]; 50 | ssize_t len = recvfrom(sock, buf, sizeof(buf), 0, 51 | (sockaddr*)&client_addr, &client_len); 52 | if (len > 0) { 53 | std::cout << "Handshake received from " 54 | << inet_ntoa(client_addr.sin_addr) << ":" 55 | << ntohs(client_addr.sin_port) << "\n"; 56 | } 57 | 58 | // Send dummy motion data in a loop 59 | while (true) { 60 | DSUMotionPacket packet{}; 61 | memcpy(packet.header, "DSUS", 4); 62 | packet.protocol_version = htons(1001); // DSU v1.01 63 | packet.message_type = 0x01; // Motion data 64 | packet.slot = 0; 65 | packet.mac = htobe64(0x112233445566); // Fake MAC 66 | packet.connected = 1; 67 | packet.battery = 0xEF; 68 | 69 | // Fake sine wave motion 70 | static float angle = 0.0f; 71 | packet.gyro[0] = sin(angle) * DEG_TO_RAD; 72 | packet.gyro[1] = cos(angle) * DEG_TO_RAD; 73 | packet.gyro[2] = 0.0f; 74 | packet.accel[0] = 0.0f; 75 | packet.accel[1] = 9.80665f; 76 | packet.accel[2] = 0.0f; 77 | packet.timestamp = htobe64((uint64_t)(angle * 1000000)); 78 | 79 | sendto(sock, &packet, sizeof(packet), 0, 80 | (sockaddr*)&client_addr, client_len); 81 | 82 | angle += 0.05f; 83 | if (angle > 2 * M_PI) angle -= 2 * M_PI; 84 | 85 | usleep(8000); // ~125 Hz 86 | } 87 | 88 | close(sock); 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /test/dummy_dsu_sinewave.cpp: -------------------------------------------------------------------------------- 1 | // dsu_server_touch_debug_fixed.cpp 2 | // DSU skeleton: single slot (0), sine-wave gyro, neutral sticks, touch zeroed, 3 | // with correct touch hexdump + decoding for debugging. 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | // DSU constants 23 | constexpr uint16_t PROTO_VER = 1001; 24 | constexpr int DSU_PORT = 26760; 25 | constexpr uint32_t MSG_PROTOCOL_VER = 0x100000; 26 | constexpr uint32_t MSG_INFO = 0x100001; 27 | constexpr uint32_t MSG_DATA = 0x100002; 28 | 29 | // CRC32 helper (standard polynomial 0xEDB88320) 30 | uint32_t crc32_le(const uint8_t* data, size_t len) { 31 | uint32_t crc = 0xFFFFFFFFu; 32 | for (size_t i = 0; i < len; ++i) { 33 | crc ^= data[i]; 34 | for (int k = 0; k < 8; ++k) 35 | crc = (crc & 1) ? (crc >> 1) ^ 0xEDB88320u : (crc >> 1); 36 | } 37 | return ~crc; 38 | } 39 | 40 | // Little-endian writers 41 | inline void put_u16(std::vector& b, uint16_t v) { b.push_back(v & 0xFF); b.push_back((v >> 8) & 0xFF); } 42 | inline void put_u32(std::vector& b, uint32_t v) { for (int i=0;i<4;i++) b.push_back((v>>(8*i))&0xFF); } 43 | inline void put_u64(std::vector& b, uint64_t v) { for (int i=0;i<8;i++) b.push_back((v>>(8*i))&0xFF); } 44 | inline void put_f32(std::vector& b, float f) { uint32_t v; std::memcpy(&v,&f,4); put_u32(b,v); } 45 | 46 | // Packet builder 47 | std::vector make_packet(uint32_t server_id, uint32_t msg_type, const std::vector& payload) { 48 | std::vector pkt; 49 | pkt.push_back('D'); pkt.push_back('S'); pkt.push_back('U'); pkt.push_back('S'); // magic 50 | put_u16(pkt, PROTO_VER); 51 | put_u16(pkt, static_cast(payload.size() + 4)); // length = msg_type + payload 52 | put_u32(pkt, 0); // CRC placeholder 53 | put_u32(pkt, server_id); 54 | put_u32(pkt, msg_type); 55 | pkt.insert(pkt.end(), payload.begin(), payload.end()); 56 | 57 | // Compute CRC (with CRC bytes zeroed) 58 | pkt[8] = pkt[9] = pkt[10] = pkt[11] = 0; 59 | uint32_t crc = crc32_le(pkt.data(), pkt.size()); 60 | pkt[8] = crc & 0xFF; 61 | pkt[9] = (crc >> 8) & 0xFF; 62 | pkt[10] = (crc >> 16) & 0xFF; 63 | pkt[11] = (crc >> 24) & 0xFF; 64 | return pkt; 65 | } 66 | 67 | // Shared beginning for INFO/DATA payloads 68 | void put_shared_begin(std::vector& p, uint8_t slot, uint8_t state_connected, 69 | uint8_t model_fullgyro, uint8_t conn_bt, uint64_t mac48, uint8_t battery) { 70 | p.push_back(slot); p.push_back(state_connected); p.push_back(model_fullgyro); p.push_back(conn_bt); 71 | for (int i=0;i<6;i++) p.push_back(uint8_t((mac48>>(8*i))&0xFF)); 72 | p.push_back(battery); 73 | } 74 | 75 | // Subscription structure (keeps client addr) 76 | struct Subscription { sockaddr_in addr{}; }; 77 | 78 | int main() { 79 | int sock = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 80 | if (sock < 0) { perror("socket"); return 1; } 81 | 82 | sockaddr_in addr{}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(DSU_PORT); 83 | if (bind(sock, (sockaddr*)&addr, sizeof(addr)) < 0) { perror("bind"); return 1; } 84 | 85 | uint32_t server_id = 0x12345678; 86 | std::cout << "DSU server (touch-debug-fixed) listening on UDP " << DSU_PORT << "\n"; 87 | 88 | std::vector subscriptions; 89 | std::mutex sub_mutex; 90 | uint8_t slot = 0; 91 | uint64_t mac48 = 0x665544332211ULL; 92 | 93 | std::atomic running{true}; 94 | 95 | // Receive thread: handle PROTOCOL_VER, INFO, DATA (subscribe) 96 | std::thread recv_thread([&](){ 97 | while (running) { 98 | uint8_t buf[2048]; sockaddr_in src{}; socklen_t sl = sizeof(src); 99 | ssize_t n = recvfrom(sock, buf, sizeof(buf), 0, (sockaddr*)&src, &sl); 100 | if (n >= 20 && buf[0]=='D' && buf[1]=='S' && buf[2]=='U' && buf[3]=='C') { 101 | uint32_t msg_type = uint32_t(buf[16]) | (uint32_t(buf[17])<<8) | (uint32_t(buf[18])<<16) | (uint32_t(buf[19])<<24); 102 | if (msg_type == MSG_PROTOCOL_VER) { 103 | std::cout << "[recv] MSG_PROTOCOL_VER\n"; 104 | std::vector payload; put_u16(payload, PROTO_VER); 105 | auto pkt = make_packet(server_id, MSG_PROTOCOL_VER, payload); 106 | sendto(sock, pkt.data(), pkt.size(), 0, (sockaddr*)&src, sl); 107 | } else if (msg_type == MSG_INFO) { 108 | std::cout << "[recv] MSG_INFO\n"; 109 | std::vector payload; 110 | put_shared_begin(payload, slot, 2, 2, 2, mac48, 0x05); 111 | payload.push_back(0x00); 112 | auto pkt = make_packet(server_id, MSG_INFO, payload); 113 | sendto(sock, pkt.data(), pkt.size(), 0, (sockaddr*)&src, sl); 114 | std::cout << "[send] Replied INFO\n"; 115 | } else if (msg_type == MSG_DATA) { 116 | std::cout << "[recv] MSG_DATA (subscribe)\n"; 117 | std::lock_guard lock(sub_mutex); 118 | bool found = false; 119 | for (auto &s : subscriptions) { 120 | if (s.addr.sin_addr.s_addr == src.sin_addr.s_addr && s.addr.sin_port == src.sin_port) { found = true; break; } 121 | } 122 | if (!found) { 123 | Subscription sub; sub.addr = src; subscriptions.push_back(sub); 124 | std::cout << "[info] Added subscription. Total: " << subscriptions.size() << "\n"; 125 | } 126 | } 127 | } 128 | } 129 | }); 130 | 131 | // Send thread: continuous motion data (~125 Hz) 132 | std::thread send_thread([&](){ 133 | float angle = 0.0f; 134 | uint32_t packet_no = 0; 135 | uint64_t t_us = 0; 136 | while (running) { 137 | std::this_thread::sleep_for(std::chrono::milliseconds(8)); // ~125 Hz 138 | 139 | std::vector subs_copy; 140 | { std::lock_guard lock(sub_mutex); subs_copy = subscriptions; } 141 | if (subs_copy.empty()) continue; 142 | 143 | // Build payload with correct layout: 144 | // 0..10 shared begin (11) 145 | // 11 connected (1) 146 | // 12..15 packet number (4) 147 | // 16..19 control bytes (4) 148 | // 20..35 sticks (16) 149 | // 36..47 touch1+touch2 (12) 150 | // 48..55 timestamp (8) 151 | // 56..67 accel (3 floats) 152 | // 68..79 gyro (3 floats) 153 | 154 | std::vector p; 155 | put_shared_begin(p, slot, 2, 2, 2, mac48, 0x05); 156 | 157 | // connected + packet # 158 | p.push_back(1); 159 | put_u32(p, packet_no++); 160 | 161 | // control bytes 162 | p.push_back(0); // bitmask1 163 | p.push_back(0); // bitmask2 164 | p.push_back(0); // HOME 165 | p.push_back(0); // Touch 166 | 167 | // sticks & analogs: set primary sticks neutral (128), other analogs zeroed 168 | // indices: 20..35 in payload 169 | for (int i = 0; i < 16; ++i) { 170 | if (i==0 || i==1 || i==2 || i==3) p.push_back(128); // LeftX, LeftY, RightX, RightY neutral 171 | else p.push_back(0); 172 | } 173 | 174 | // touch1 (6) + touch2 (6) : zeroed (inactive) 175 | for (int i = 0; i < 12; ++i) p.push_back(0); 176 | 177 | // DEBUG: correct touch hexdump + decode (touch block is at payload index 36..47) 178 | size_t touch_start = 36; 179 | if (p.size() >= touch_start + 12) { 180 | std::cout << "[dbg] raw touch bytes: "; 181 | for (size_t i = touch_start; i < touch_start + 12; ++i) { 182 | printf("%02X ", p[i]); 183 | } 184 | std::cout << "\n"; 185 | 186 | uint8_t t1_active = p[touch_start + 0]; 187 | uint8_t t1_id = p[touch_start + 1]; 188 | uint16_t t1_x = uint16_t(p[touch_start + 2]) | (uint16_t(p[touch_start + 3]) << 8); 189 | uint16_t t1_y = uint16_t(p[touch_start + 4]) | (uint16_t(p[touch_start + 5]) << 8); 190 | 191 | uint8_t t2_active = p[touch_start + 6]; 192 | uint8_t t2_id = p[touch_start + 7]; 193 | uint16_t t2_x = uint16_t(p[touch_start + 8]) | (uint16_t(p[touch_start + 9]) << 8); 194 | uint16_t t2_y = uint16_t(p[touch_start +10]) | (uint16_t(p[touch_start +11]) << 8); 195 | 196 | std::cout << "[dbg] touch1 a=" << (int)t1_active << " id=" << (int)t1_id 197 | << " x=" << t1_x << " y=" << t1_y << "\n"; 198 | std::cout << "[dbg] touch2 a=" << (int)t2_active << " id=" << (int)t2_id 199 | << " x=" << t2_x << " y=" << t2_y << "\n"; 200 | } 201 | 202 | // timestamp (u64 microseconds) 203 | t_us += 5000; // approx 5ms per packet 204 | put_u64(p, t_us); 205 | 206 | // accelerometer (g) 207 | float ax = 0.0f, ay = 0.0f, az = 1.0f; 208 | put_f32(p, ax); put_f32(p, ay); put_f32(p, az); 209 | 210 | // gyroscope (deg/s) — pitch, yaw, roll 211 | angle += 0.05f; if (angle > 6.2831853f) angle -= 6.2831853f; 212 | float pitch_dps = 50.0f * sinf(angle); 213 | float yaw_dps = 50.0f * cosf(angle); 214 | float roll_dps = 0.0f; 215 | put_f32(p, pitch_dps); put_f32(p, yaw_dps); put_f32(p, roll_dps); 216 | 217 | // finalize packet 218 | auto pkt = make_packet(server_id, MSG_DATA, p); 219 | for (auto &s : subs_copy) { 220 | sendto(sock, pkt.data(), pkt.size(), 0, (sockaddr*)&s.addr, sizeof(s.addr)); 221 | } 222 | 223 | std::cout << "[send] DATA #" << packet_no << " -> " << subs_copy.size() 224 | << " clients (payload " << p.size() << " bytes, pkt " << pkt.size() << ")\n"; 225 | } 226 | }); 227 | 228 | recv_thread.join(); 229 | send_thread.join(); 230 | close(sock); 231 | return 0; 232 | } 233 | --------------------------------------------------------------------------------