feat: add SDK-free 3DoF tracking for VITURE Pro 2 (#1115)

* feat: itch.io store, library and installs for DRM-free Windows builds (#1064)

* feat: add experimental SDK-free VITURE Pro 2 tracking

* docs: record full-app Pro 2 hardware validation

* docs: record successful Pro 2 user game test

* fix: translate Pro 2 tracking notice for all supported locales

* fix: respect model capabilities for glasses controls

* fix: handle fold configuration during glasses probe

---------

Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-10-22 10:28:14 -04:00
1 parent 7482f797c7
commit 3d9f200a7e
66 files changed
+2974 -19

No files matched your search

@@ -0,0 +1 @@
out/
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.droiddeck.viturev2check" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
<uses-feature android:name="android.hardware.usb.host" android:required="true" />
<application android:label="VITURE production driver check" android:debuggable="true" android:allowBackup="false" android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,53 @@
# Production VITURE v2 driver hardware check
This harness calls the actual production `VitureV2Link.Companion.open` and packages
the freshly compiled `VitureV2Link*.class`, `VitureV2Protocol*.class`, and
`GlassesLink*.class` files from `app/build/tmp/kotlin-classes/debug`. It contains no
USB transport or protocol implementation of its own and no vendor SDK or native
library. The Kotlin standard library version matches the root Gradle build, 2.1.0.
The default build relies on Gradle's source/dependency checks to refresh classes
and rejects unexpected application-class dependencies, including an old
orientation-helper dependency. Source and bytecode hashes are recorded together;
file timestamps are not used because Gradle can restore classes from its cache.
Build from the workspace with:
```powershell
./tools/viture/viture-v2-driver-check/build.ps1
```
This first invokes `:app:compileDebugKotlin -PvitureSdkDir=`. If the parent task just
completed that compile, pass `-SkipCompile` to package those classes without starting
another Gradle build. That option requires the caller to ensure the classes are
current. The output is
`tools/viture/viture-v2-driver-check/out/viture-v2-driver-check-debug.apk`.
SDK discovery uses `ANDROID_HOME`, `ANDROID_SDK_ROOT`, then `%LOCALAPPDATA%\Android\Sdk`.
JDK discovery uses `JAVA_HOME`, the optional `%USERPROFILE%\.jdks\jbr-17.0.9`, then
`javac.exe` on PATH. Explicit `-Sdk` and `-Java` override discovery. Kotlin cache
discovery respects `GRADLE_USER_HOME`, falling back to `%USERPROFILE%\.gradle`.
APK assets contain the upstream MIT license and a runtime manifest of the exact
production-class SHA256 hashes and Kotlin library hash. Every session logs this
manifest. The documented upstream protocol itself was derived from third-party
vendor SDK captures; this harness uses the existing SDK-free production driver.
Only an attached `35ca:1301` Pro 2 can be opened. After USB permission, the real
driver bootstraps its pose stream. `onReady` is posted to the main handler so the
link assignment is complete before control commands. The harness sends the
controller's internal IMU-off command, checks for zero new pose callbacks over
500 ms, resumes, captures for 10..15 seconds (default 12), pauses again, checks
another 500 ms, and closes the driver. A watchdog starts closure at 23.5 seconds,
reserving the driver's maximum 1.5-second join for a 25-second test limit after
permission. Android scheduling or system stalls can extend elapsed wall time.
```powershell
adb shell am start -n com.droiddeck.viturev2check/.MainActivity --ez auto true --ei seconds 12
```
JSONL logs are under
`/data/user/0/com.droiddeck.viturev2check/files/checks/driver-check-<wall-ms>.jsonl`.
They include every callback packet with actual length and base64 bytes, the exact
shared `xyzw` quaternion delivered by production code, tracking/ready events,
pause-window counts, errors, bad frames, total and capture pose counts, sample
rate, and final state. This checks the real driver's hardware/session behavior;
it does not run the full application UI or establish the user's physical axis
and recentering experience. Reopen the activity for a separate check.
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Holger Bartnick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,12 @@
The VITURE v2 protocol in the packaged production DroidDeck driver is adapted from
elasticjava/viture-v2, copyright (c) 2026 Holger Bartnick, under the MIT license.
Pinned upstream commit: ece8c30485f7d357fefa362ae74f3eabac9b3899.
See LICENSE.viture-v2 in these APK assets for the complete license.
The APK packages actual compiled DroidDeck VitureV2Link, VitureV2Protocol, and
GlassesLink classes and the Kotlin standard library 2.1.0. Kotlin is copyright
JetBrains and contributors and distributed under Apache License 2.0:
https://www.apache.org/licenses/LICENSE-2.0
See LICENSE.kotlin-Apache-2.0 in these APK assets for the complete license terms.
No vendor SDK or vendor native libraries are included.
@@ -0,0 +1,117 @@
param(
[string]$Sdk,
[string]$Java = $env:JAVA_HOME,
[switch]$SkipCompile
)
$ErrorActionPreference = 'Stop'
if (-not $Sdk) {
if ($env:ANDROID_HOME) { $Sdk = $env:ANDROID_HOME }
elseif ($env:ANDROID_SDK_ROOT) { $Sdk = $env:ANDROID_SDK_ROOT }
elseif ($env:LOCALAPPDATA) { $Sdk = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
else { throw 'Set ANDROID_HOME / ANDROID_SDK_ROOT or pass -Sdk.' }
}
if (-not $Java) {
$fallbackJdk = Join-Path $env:USERPROFILE '.jdks\jbr-17.0.9'
$javacCommand = Get-Command javac.exe -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath (Join-Path $fallbackJdk 'bin\javac.exe')) { $Java = $fallbackJdk }
elseif ($javacCommand) { $Java = Split-Path (Split-Path $javacCommand.Source -Parent) -Parent }
}
if (-not $Java -or -not (Test-Path -LiteralPath (Join-Path $Java 'bin\javac.exe'))) {
throw 'Set JAVA_HOME or pass -Java with a JDK containing bin\javac.exe.'
}
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..'))
$output = Join-Path $PSScriptRoot 'out'
$buildId = [Guid]::NewGuid().ToString('N')
$classes = Join-Path $output ('classes-' + $buildId)
$production = Join-Path $output ('production-' + $buildId)
$productionPackage = Join-Path $production 'com\droiddeck\launcher\glasses'
$assets = Join-Path $output ('assets-' + $buildId)
$dex = Join-Path $output ('dex-' + $buildId)
$buildTools = Join-Path $Sdk 'build-tools\36.0.0'
$androidJar = Join-Path $Sdk 'platforms\android-34\android.jar'
$compiled = Join-Path $repo 'app\build\tmp\kotlin-classes\debug\com\droiddeck\launcher\glasses'
$stdlibVersion = '2.1.0'
$gradleCacheRoot = if ($env:GRADLE_USER_HOME) { $env:GRADLE_USER_HOME } else { Join-Path $env:USERPROFILE '.gradle' }
$stdlibDirectory = Join-Path $gradleCacheRoot ('caches\modules-2\files-2.1\org.jetbrains.kotlin\kotlin-stdlib\' + $stdlibVersion)
$stdlibFiles = @(Get-ChildItem -LiteralPath $stdlibDirectory -Recurse -File | Where-Object Name -EQ ('kotlin-stdlib-' + $stdlibVersion + '.jar'))
if ($stdlibFiles.Count -ne 1) { throw "Expected one cached Kotlin stdlib $stdlibVersion jar." }
$stdlib = $stdlibFiles[0].FullName
$unsigned = Join-Path $output 'viture-v2-driver-check-unsigned.apk'
$aligned = Join-Path $output 'viture-v2-driver-check-aligned.apk'
$apk = Join-Path $output 'viture-v2-driver-check-debug.apk'
$classJar = Join-Path $output 'harness.jar'
$productionJar = Join-Path $output 'production-driver.jar'
$previousJavaHome = $env:JAVA_HOME
try {
$env:JAVA_HOME = $Java
if (-not $SkipCompile) {
Push-Location -LiteralPath $repo
try {
& (Join-Path $repo 'gradlew.bat') ':app:compileDebugKotlin' '-PvitureSdkDir='
if ($LASTEXITCODE -ne 0) { throw 'Production Kotlin compilation failed.' }
} finally { Pop-Location }
}
$manifestSources = @()
foreach ($pair in @(
@('VitureV2Link.class', 'VitureV2Link.kt'),
@('VitureV2Protocol.class', 'VitureV2Protocol.kt'),
@('GlassesLink.class', 'GlassesHardware.kt')
)) {
$binary = Get-Item -LiteralPath (Join-Path $compiled $pair[0])
$source = Get-Item -LiteralPath (Join-Path $repo ('app\src\main\java\com\droiddeck\launcher\glasses\' + $pair[1]))
$manifestSources += [ordered]@{ name = $source.Name; sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $source.FullName).Hash }
}
New-Item -ItemType Directory -Force -Path $output, $classes, $productionPackage, $assets, $dex | Out-Null
$classFiles = @(Get-ChildItem -LiteralPath $compiled -File | Where-Object {
$_.Name -like 'VitureV2Link*.class' -or $_.Name -like 'VitureV2Protocol*.class' -or $_.Name -like 'GlassesLink*.class'
})
if ($classFiles.Count -lt 3) { throw 'Production class selection is incomplete.' }
$manifestClasses = @()
foreach ($classFile in $classFiles) {
Copy-Item -LiteralPath $classFile.FullName -Destination $productionPackage
$manifestClasses += [ordered]@{ name = $classFile.Name; sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $classFile.FullName).Hash }
}
& (Join-Path $Java 'bin\jar.exe') cf $productionJar -C $production .
if ($LASTEXITCODE -ne 0) { throw 'Production jar creation failed.' }
$dependencies = & (Join-Path $Java 'bin\jdeps.exe') -verbose:class -filter:none $productionJar
if ($LASTEXITCODE -ne 0) { throw 'Production dependency inspection failed.' }
foreach ($line in $dependencies) {
if ($line -match '->\s+(com\.droiddeck\.launcher\.glasses\.\S+)') {
if ($Matches[1] -notmatch '^com\.droiddeck\.launcher\.glasses\.(VitureV2Link|VitureV2Protocol|GlassesLink)(\$|$)') {
throw ('Unexpected production dependency: ' + $Matches[1] + '. Recompile the current isolated driver source.')
}
}
}
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\LICENSE.viture-v2') -Destination $assets
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\NOTICE.txt') -Destination $assets
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets\LICENSE.kotlin-Apache-2.0') -Destination $assets
$runtimeManifest = [ordered]@{
source = 'Actual app/build/tmp/kotlin-classes/debug production bytecode; not reimplemented'
upstreamCommit = 'ece8c30485f7d357fefa362ae74f3eabac9b3899'
builtUtc = [DateTime]::UtcNow.ToString('o')
kotlinStdlibVersion = $stdlibVersion
kotlinStdlibSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $stdlib).Hash
productionJarSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $productionJar).Hash
sources = $manifestSources
classes = $manifestClasses
}
$runtimeManifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $assets 'runtime-manifest.json') -Encoding utf8
& (Join-Path $Java 'bin\javac.exe') --release 8 -classpath ($androidJar + ';' + $productionJar + ';' + $stdlib) -encoding UTF-8 -d $classes (Join-Path $PSScriptRoot 'src\com\droiddeck\viturev2check\MainActivity.java')
if ($LASTEXITCODE -ne 0) { throw 'Harness Java compilation failed.' }
& (Join-Path $Java 'bin\jar.exe') cf $classJar -C $classes .
if ($LASTEXITCODE -ne 0) { throw 'Harness jar creation failed.' }
& (Join-Path $buildTools 'd8.bat') --min-api 26 --lib $androidJar --output $dex $classJar $productionJar $stdlib
if ($LASTEXITCODE -ne 0) { throw 'D8 failed.' }
& (Join-Path $buildTools 'aapt2.exe') link --manifest (Join-Path $PSScriptRoot 'AndroidManifest.xml') -A $assets -I $androidJar -o $unsigned --min-sdk-version 26 --target-sdk-version 34
if ($LASTEXITCODE -ne 0) { throw 'Manifest linking failed.' }
& (Join-Path $Java 'bin\jar.exe') uf $unsigned -C $dex classes.dex
if ($LASTEXITCODE -ne 0) { throw 'Dex insertion failed.' }
& (Join-Path $buildTools 'zipalign.exe') -f 4 $unsigned $aligned
if ($LASTEXITCODE -ne 0) { throw 'APK alignment failed.' }
& (Join-Path $buildTools 'apksigner.bat') sign --ks (Join-Path $repo 'keystore\testkey.p12') --ks-key-alias testkey --ks-pass pass:android --key-pass pass:android --out $apk $aligned
if ($LASTEXITCODE -ne 0) { throw 'APK signing failed.' }
& (Join-Path $buildTools 'apksigner.bat') verify --verbose $apk
if ($LASTEXITCODE -ne 0) { throw 'APK verification failed.' }
Get-FileHash -Algorithm SHA256 -LiteralPath $apk
Write-Output $apk
} finally { $env:JAVA_HOME = $previousJavaHome }
@@ -0,0 +1,317 @@
package com.droiddeck.viturev2check;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Base64;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.droiddeck.launcher.glasses.VitureV2Link;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.json.JSONArray;
import org.json.JSONObject;
public final class MainActivity extends Activity {
private static final String PERMISSION = "com.droiddeck.viturev2check.USB_PERMISSION";
private static final int VENDOR = 0x35ca, PRODUCT = 0x1301, INTERNAL_IMU = 0x0015;
private static final long TOTAL_LIMIT_MS = 25000, CLOSE_RESERVE_MS = 1500;
private final Handler handler = new Handler(Looper.getMainLooper());
private final AtomicBoolean finishing = new AtomicBoolean();
private final AtomicLong poses = new AtomicLong(), capturePoses = new AtomicLong(), packetBytes = new AtomicLong();
private final AtomicLong readyCallbacks = new AtomicLong(), trackingOn = new AtomicLong(), trackingOff = new AtomicLong(), errors = new AtomicLong();
private final Object poseLock = new Object();
private UsbManager manager;
private UsbDevice pending;
private TextView status;
private VitureV2Link link;
private Journal journal;
private boolean busy, bootstrapHandled, firstOffAccepted, resumeAccepted, finalOffAccepted;
private int seconds;
private volatile String phase = "idle";
private long startedMs, firstOffExtra = -1, finalOffExtra = -1, captureStartedNs, captureEndedNs;
private long firstCaptureTimeNs, lastCaptureTimeNs;
private float[] lastPose;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
if (!PERMISSION.equals(intent.getAction()) || pending == null) return;
UsbDevice device = pending;
pending = null;
if (manager.hasPermission(device)) begin(device);
else { busy = false; show("USB permission denied."); }
}
};
private final VitureV2Link.Listener listener = new VitureV2Link.Listener() {
@Override public void onReady() {
readyCallbacks.incrementAndGet();
event("ready", "phase", phase);
handler.post(() -> bootstrapOff());
}
@Override public void onValue(int message, int value) { event("value", "messageId", message, "value", value); }
@Override public void onPose(byte[] raw, float[] q, long timeNs) {
long count = poses.incrementAndGet();
packetBytes.addAndGet(raw.length);
String observedPhase = phase;
synchronized (poseLock) {
lastPose = q.clone();
if ("capture".equals(observedPhase)) {
if (capturePoses.incrementAndGet() == 1) firstCaptureTimeNs = timeNs;
lastCaptureTimeNs = timeNs;
}
}
event("pose", "phase", observedPhase, "count", count, "receiptTimeNs", timeNs,
"sharedXyzw", floats(q), "packetLength", raw.length, "packetBase64", Base64.encodeToString(raw, Base64.NO_WRAP));
}
@Override public void onTracking(boolean active) {
if (active) trackingOn.incrementAndGet(); else trackingOff.incrementAndGet();
event("tracking", "active", active, "phase", phase);
}
@Override public void onLost() {
errors.incrementAndGet();
event("lost", "phase", phase);
handler.post(() -> finishCheck("driver_lost"));
}
};
@Override public void onCreate(Bundle saved) {
super.onCreate(saved);
manager = (UsbManager) getSystemService(USB_SERVICE);
seconds = Math.max(10, Math.min(15, getIntent().getIntExtra("seconds", 12)));
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(24, 24, 24, 24);
Button start = new Button(this);
start.setText("Check production driver on Pro 2");
start.setOnClickListener(view -> select());
layout.addView(start);
Button stop = new Button(this);
stop.setText("Stop and close driver");
stop.setOnClickListener(view -> finishCheck("user_stop"));
layout.addView(stop);
status = new TextView(this);
status.setTextIsSelectable(true);
ScrollView scroll = new ScrollView(this);
scroll.addView(status);
layout.addView(scroll);
setContentView(layout);
if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, new IntentFilter(PERMISSION), Context.RECEIVER_NOT_EXPORTED);
else registerReceiver(receiver, new IntentFilter(PERMISSION));
show("Actual compiled production VitureV2Link. Pro 2 only. Ready, pause 500 ms, capture " + seconds + " s, pause 500 ms, close.");
show("Logs: " + getFilesDir() + "/checks");
if (getIntent().getBooleanExtra("auto", false)) select();
}
@Override protected void onDestroy() {
finishCheck("activity_destroyed");
unregisterReceiver(receiver);
super.onDestroy();
}
private void select() {
if (busy || finishing.get()) { show("A check is already active or complete; reopen the activity for another run."); return; }
List<UsbDevice> matches = new ArrayList<>();
for (UsbDevice device : manager.getDeviceList().values()) {
if (device.getVendorId() == VENDOR && device.getProductId() == PRODUCT) matches.add(device);
}
if (matches.size() != 1) { show("Expected exactly one 35ca:1301 Pro 2; found " + matches.size()); return; }
busy = true;
UsbDevice device = matches.get(0);
if (manager.hasPermission(device)) begin(device);
else {
pending = device;
manager.requestPermission(device, PendingIntent.getBroadcast(this, PRODUCT,
new Intent(PERMISSION).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
}
}
private void begin(UsbDevice device) {
if (finishing.get()) return;
startedMs = SystemClock.elapsedRealtime();
try {
File directory = new File(getFilesDir(), "checks");
if (!directory.isDirectory() && !directory.mkdirs()) throw new IllegalStateException("Could not create log directory");
File file = new File(directory, "driver-check-" + System.currentTimeMillis() + ".jsonl");
journal = new Journal(file);
event("session", "vendorId", VENDOR, "productId", PRODUCT, "captureSeconds", seconds,
"totalLimitMillis", TOTAL_LIMIT_MS, "runtime", new JSONObject(readAsset("runtime-manifest.json")));
show("Recording " + file.getAbsolutePath());
phase = "bootstrap";
handler.postDelayed(() -> finishCheck("watchdog"), TOTAL_LIMIT_MS - CLOSE_RESERVE_MS);
link = VitureV2Link.Companion.open(manager, device, listener);
event("open_returned", "opened", link != null);
if (link == null) { errors.incrementAndGet(); finishCheck("open_failed"); }
} catch (Exception error) {
errors.incrementAndGet();
event("error", "operation", "open", "message", error.toString());
finishCheck("open_error");
}
}
private void bootstrapOff() {
if (finishing.get() || bootstrapHandled) return;
if (link == null) { handler.postDelayed(() -> bootstrapOff(), 5); return; }
bootstrapHandled = true;
try {
firstOffAccepted = link.send(INTERNAL_IMU, new byte[] {0});
long baseline = poses.get();
phase = "bootstrap_off";
event("off_requested", "stage", "bootstrap", "accepted", firstOffAccepted, "poseBaseline", baseline);
if (!firstOffAccepted) { errors.incrementAndGet(); finishCheck("bootstrap_off_rejected"); return; }
handler.postDelayed(() -> {
if (finishing.get()) return;
firstOffExtra = poses.get() - baseline;
event("off_observation", "stage", "bootstrap", "windowMillis", 500, "newPoses", firstOffExtra,
"trackingActive", link.getTrackingActive(), "ready", link.getReady());
if (firstOffExtra != 0 || link.getTrackingActive()) errors.incrementAndGet();
resume();
}, 500);
} catch (Exception error) { fail("bootstrap_off", error); }
}
private void resume() {
try {
phase = "capture";
captureStartedNs = System.nanoTime();
resumeAccepted = link.send(INTERNAL_IMU, new byte[] {1});
event("on_requested", "accepted", resumeAccepted);
if (!resumeAccepted) { errors.incrementAndGet(); finishCheck("resume_rejected"); return; }
show("Capturing production-driver poses for " + seconds + " seconds.");
handler.postDelayed(() -> finalOff(), seconds * 1000L);
} catch (Exception error) { fail("resume", error); }
}
private void finalOff() {
if (finishing.get()) return;
try {
finalOffAccepted = link.send(INTERNAL_IMU, new byte[] {0});
captureEndedNs = System.nanoTime();
long baseline = poses.get();
phase = "final_off";
event("off_requested", "stage", "final", "accepted", finalOffAccepted, "poseBaseline", baseline);
if (!finalOffAccepted) { errors.incrementAndGet(); finishCheck("final_off_rejected"); return; }
handler.postDelayed(() -> {
if (finishing.get()) return;
finalOffExtra = poses.get() - baseline;
event("off_observation", "stage", "final", "windowMillis", 500, "newPoses", finalOffExtra,
"trackingActive", link.getTrackingActive(), "ready", link.getReady());
if (finalOffExtra != 0 || link.getTrackingActive()) errors.incrementAndGet();
finishCheck("completed");
}, 500);
} catch (Exception error) { fail("final_off", error); }
}
private void fail(String operation, Exception error) {
errors.incrementAndGet();
event("error", "operation", operation, "message", error.toString());
finishCheck(operation + "_error");
}
private void finishCheck(String reason) {
if (!busy || !finishing.compareAndSet(false, true)) return;
pending = null;
handler.removeCallbacksAndMessages(null);
phase = "closing";
long badFrames = 0;
try {
if (link != null) { badFrames = link.getBadFrames(); link.close(); }
} catch (Exception error) {
errors.incrementAndGet();
event("error", "operation", "close", "message", error.toString());
} finally {
phase = "closed";
long captureCount = capturePoses.get();
long captureNs = captureEndedNs > captureStartedNs ? captureEndedNs - captureStartedNs : 0;
double rate = 0;
JSONArray finalQ;
synchronized (poseLock) {
if (captureCount > 1 && lastCaptureTimeNs > firstCaptureTimeNs)
rate = (captureCount - 1) * 1_000_000_000.0 / (lastCaptureTimeNs - firstCaptureTimeNs);
finalQ = floats(lastPose);
}
boolean pass = "completed".equals(reason) && errors.get() == 0 && readyCallbacks.get() > 0 &&
firstOffAccepted && resumeAccepted && finalOffAccepted && firstOffExtra == 0 && finalOffExtra == 0 && captureCount > 0 &&
trackingOn.get() >= 2 && trackingOff.get() >= 2 && link != null && !link.getReady() && !link.getTrackingActive();
event("summary", "reason", reason, "pass", pass, "totalMillis", SystemClock.elapsedRealtime() - startedMs,
"poseCount", poses.get(), "capturePoseCount", captureCount, "captureMillis", captureNs / 1_000_000.0,
"sampleRateHz", rate, "readyCallbacks", readyCallbacks.get(), "trackingOnCallbacks", trackingOn.get(),
"trackingOffCallbacks", trackingOff.get(), "errors", errors.get(), "badFrames", badFrames,
"bootstrapOffNewPoses", firstOffExtra, "finalOffNewPoses", finalOffExtra,
"readyAfterClose", link != null && link.getReady(), "trackingAfterClose", link != null && link.getTrackingActive(),
"lastSharedXyzw", finalQ, "packetBytes", packetBytes.get());
if (journal != null) {
try { journal.close(); } catch (Exception error) { Log.e("VitureV2Check", "Log close failed", error); }
}
busy = false;
show("Finished: " + reason + ", pass=" + pass + ", capture poses=" + captureCount + ", rate=" + String.format(java.util.Locale.ROOT, "%.1f", rate) + " Hz.");
}
}
private void event(String type, Object... fields) {
Journal output = journal;
if (output == null) return;
try { output.event(type, fields); }
catch (Exception error) { errors.incrementAndGet(); Log.e("VitureV2Check", "Could not log " + type, error); }
}
private String readAsset(String name) throws Exception {
try (InputStream input = getAssets().open(name); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
for (int count; (count = input.read(buffer)) != -1;) output.write(buffer, 0, count);
return new String(output.toByteArray(), StandardCharsets.UTF_8);
}
}
private static JSONArray floats(float[] values) {
JSONArray result = new JSONArray();
if (values != null) for (float value : values) {
try { result.put((double) value); } catch (Exception ignored) { result.put(JSONObject.NULL); }
}
return result;
}
private void show(String message) {
Log.i("VitureV2Check", message);
runOnUiThread(() -> status.append(message + "\n"));
}
private static final class Journal implements AutoCloseable {
private final BufferedWriter writer;
Journal(File file) throws Exception { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); }
synchronized void event(String type, Object... fields) throws Exception {
JSONObject json = new JSONObject();
json.put("event", type);
json.put("elapsedRealtimeNanos", SystemClock.elapsedRealtimeNanos());
for (int i = 0; i < fields.length; i += 2) json.put((String) fields[i], fields[i + 1]);
writer.write(json.toString());
writer.newLine();
writer.flush();
}
@Override public synchronized void close() throws Exception { writer.close(); }
}
}
+1
View File
@@ -0,0 +1 @@
out/
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.droiddeck.viturev2probe" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="34" />
<uses-feature android:name="android.hardware.usb.host" android:required="true" />
<application android:label="VITURE Pro 2 probe" android:debuggable="true" android:allowBackup="false" android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Holger Bartnick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,77 @@
# SDK-free Android VITURE Pro 2 probe
Protocol and the pose test vector are adapted from Holger Bartnick's MIT-licensed
[elasticjava/viture-v2](https://github.com/elasticjava/viture-v2), pinned to commit
`ece8c30485f7d357fefa362ae74f3eabac9b3899`. Consult `LICENSE.upstream` for its license;
the APK also includes this notice at `assets/LICENSE.upstream`.
Sources consulted: upstream `PROTOCOL.md`, runtime `src/lib.rs` and `src/usbfs.rs`.
The upstream document says its protocol was derived from official SDK USB captures
and then verified using an independent implementation. This is third-party
SDK-derived protocol documentation, not a claim of clean-room discovery.
This standalone Java application uses Android's USB host APIs. It includes no
vendor SDK, vendor native library, project Kotlin source, or project SDK trace.
The prior local SDK capture directories and downloaded vendor SDK were excluded
from this work. Its build uses the Java sources and manifest in this directory.
Only VITURE Pro 2 `35ca:1301` (decimal PID 4865), interface 0, is accepted. The
active interface must be HID alternate 0 with exactly two endpoints: one 64-byte
interrupt IN and one 64-byte interrupt OUT. Endpoint addresses come from the
device descriptors. Standard GET_CONFIGURATION and GET_INTERFACE reads identify
the current transport; the probe changes neither setting. The input request is
queued before any protocol command.
The probe queries firmware with `0x3003`, enables either pose at 120 Hz
(`0x0301 [1,2]`) or raw at 120 Hz (`0x0301 [2,2]`), and sends stream off
(`0x0301 [0,0]`) in `finally`. It does not query serial numbers or change display,
brightness, volume, film, or calibration settings. Pose and raw are separate modes.
Every input completion retains its actual byte count and base64 bytes. Decoding
requires the v2 preamble, bounded declared length, byte-sum checksum, and exact
known event payload size. Pose requires finite quaternion components and norm
within 0.05 of 1. Raw samples require finite gyro/acceleration components;
acceleration norm is logged without assuming that moving hardware has a 1 g
reading. Valid frame, pose, raw, malformed frame, and malformed sample counters
remain separate. Device tick units are unknown. Transport completion is not a
firmware ACK; control ACKs are logged independently.
Stream off is attempted on orderly completion, stop, activity destruction, and
caught errors after a stream-enable attempt. Input reads remain active for a
bounded off-response grace period before cancellation. Resource closing does not
depend on successful logging. Process termination, unplugging, or power loss can
prevent cleanup.
Build with `./tools/viture/viture-v2-probe/build.ps1`. SDK discovery uses
`ANDROID_HOME`, `ANDROID_SDK_ROOT`, then `%LOCALAPPDATA%\Android\Sdk`. JDK discovery
uses `JAVA_HOME`, the optional `%USERPROFILE%\.jdks\jbr-17.0.9`, then `javac.exe` on
PATH. Explicit `-Sdk` and `-Java` override discovery. Thirteen protocol checks run
before APK compilation and signing. The APK is written to
`tools/viture/viture-v2-probe/out/viture-v2-probe-debug.apk` and uses the repository
test key. No Gradle dependency or vendor library is required.
After installation, launch the default pose capture:
```powershell
adb shell am start -n com.droiddeck.viturev2probe/.MainActivity --ez auto true --ei seconds 15
```
For raw gyro and accelerometer data, pass `--es mode raw`:
```powershell
adb shell am start -n com.droiddeck.viturev2probe/.MainActivity --ez auto true --es mode raw --ei seconds 15
```
`mode` accepts `pose` or `raw` and defaults to `pose`. Automatic launch defaults to
PID 4865 and interface 0; if supplied, `--ei pid` and `--ei interface` must match
those exact values. `seconds` defaults to 15 and is clamped to 1..30. Descriptor
reads and bounded cleanup add a few seconds around that capture window. Allow
the USB permission dialog once. The UI provides a Pro 2 capture button using the
selected mode and a stop button.
Logs are app-private JSONL files under
`/data/user/0/com.droiddeck.viturev2probe/files/captures/` named
`probe-<wall-time-ms>-pid-4865-if-0.jsonl`.
Use `adb shell run-as com.droiddeck.viturev2probe ls files/captures` to enumerate them
and `adb exec-out run-as com.droiddeck.viturev2probe cat files/captures/<name>` to read.
For another launch with new extras, finish the existing activity or force-stop only
after `session_end` is present so the stream-off cleanup can complete.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Holger Bartnick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+61
View File
@@ -0,0 +1,61 @@
param(
[string]$Sdk,
[string]$Java = $env:JAVA_HOME
)
$ErrorActionPreference = 'Stop'
if (-not $Sdk) {
if ($env:ANDROID_HOME) { $Sdk = $env:ANDROID_HOME }
elseif ($env:ANDROID_SDK_ROOT) { $Sdk = $env:ANDROID_SDK_ROOT }
elseif ($env:LOCALAPPDATA) { $Sdk = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
else { throw 'Set ANDROID_HOME / ANDROID_SDK_ROOT or pass -Sdk.' }
}
if (-not $Java) {
$fallbackJdk = Join-Path $env:USERPROFILE '.jdks\jbr-17.0.9'
$javacCommand = Get-Command javac.exe -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath (Join-Path $fallbackJdk 'bin\javac.exe')) { $Java = $fallbackJdk }
elseif ($javacCommand) { $Java = Split-Path (Split-Path $javacCommand.Source -Parent) -Parent }
}
if (-not $Java -or -not (Test-Path -LiteralPath (Join-Path $Java 'bin\javac.exe'))) {
throw 'Set JAVA_HOME or pass -Java with a JDK containing bin\javac.exe.'
}
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..'))
$output = Join-Path $PSScriptRoot 'out'
$classes = Join-Path $output ('classes-' + [Guid]::NewGuid().ToString('N'))
$testClasses = Join-Path $output ('tests-' + [Guid]::NewGuid().ToString('N'))
$dex = Join-Path $output ('dex-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Force -Path $output, $classes, $testClasses, $dex | Out-Null
$buildTools = Join-Path $Sdk 'build-tools\36.0.0'
$androidJar = Join-Path $Sdk 'platforms\android-34\android.jar'
$unsigned = Join-Path $output 'viture-v2-probe-unsigned.apk'
$aligned = Join-Path $output 'viture-v2-probe-aligned.apk'
$apk = Join-Path $output 'viture-v2-probe-debug.apk'
$classJar = Join-Path $output 'classes.jar'
$source = Join-Path $PSScriptRoot 'src\com\droiddeck\viturev2probe'
$previousJavaHome = $env:JAVA_HOME
try {
$env:JAVA_HOME = $Java
& (Join-Path $Java 'bin\javac.exe') --release 8 -encoding UTF-8 -d $testClasses (Join-Path $source 'Protocol.java') (Join-Path $PSScriptRoot 'tests\com\droiddeck\viturev2probe\ProtocolTest.java')
if ($LASTEXITCODE -ne 0) { throw 'test compilation failed' }
& (Join-Path $Java 'bin\java.exe') -cp $testClasses com.droiddeck.viturev2probe.ProtocolTest
if ($LASTEXITCODE -ne 0) { throw 'protocol tests failed' }
& (Join-Path $Java 'bin\javac.exe') --release 8 -classpath $androidJar -encoding UTF-8 -d $classes (Join-Path $source 'Protocol.java') (Join-Path $source 'MainActivity.java')
if ($LASTEXITCODE -ne 0) { throw 'javac failed' }
& (Join-Path $Java 'bin\jar.exe') cf $classJar -C $classes .
if ($LASTEXITCODE -ne 0) { throw 'jar failed' }
& (Join-Path $buildTools 'd8.bat') --min-api 26 --lib $androidJar --output $dex $classJar
if ($LASTEXITCODE -ne 0) { throw 'd8 failed' }
& (Join-Path $buildTools 'aapt2.exe') link --manifest (Join-Path $PSScriptRoot 'AndroidManifest.xml') -A (Join-Path $PSScriptRoot 'assets') -I $androidJar -o $unsigned --min-sdk-version 26 --target-sdk-version 34
if ($LASTEXITCODE -ne 0) { throw 'aapt2 failed' }
& (Join-Path $Java 'bin\jar.exe') uf $unsigned -C $dex classes.dex
if ($LASTEXITCODE -ne 0) { throw 'APK dex insertion failed' }
& (Join-Path $buildTools 'zipalign.exe') -f 4 $unsigned $aligned
if ($LASTEXITCODE -ne 0) { throw 'zipalign failed' }
& (Join-Path $buildTools 'apksigner.bat') sign --ks (Join-Path $repo 'keystore\testkey.p12') --ks-key-alias testkey --ks-pass pass:android --key-pass pass:android --out $apk $aligned
if ($LASTEXITCODE -ne 0) { throw 'APK signing failed' }
& (Join-Path $buildTools 'apksigner.bat') verify --verbose $apk
if ($LASTEXITCODE -ne 0) { throw 'APK verification failed' }
Get-FileHash -Algorithm SHA256 -LiteralPath $apk
Write-Output $apk
} finally {
$env:JAVA_HOME = $previousJavaHome
}
@@ -0,0 +1,451 @@
package com.droiddeck.viturev2probe;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConfiguration;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Base64;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
public final class MainActivity extends Activity {
private static final String PERMISSION = "com.droiddeck.viturev2probe.USB_PERMISSION";
private static final int VENDOR = 0x35ca;
private static final int PRODUCT = 0x1301;
private static final int INTERFACE = 0;
private static final int BYTE_LIMIT = 4 * 1024 * 1024;
private UsbManager manager;
private TextView status;
private volatile boolean stop;
private boolean busy;
private UsbDevice pending;
private int durationSeconds = 15;
private boolean rawMode;
private boolean invalidMode;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
if (!PERMISSION.equals(intent.getAction()) || pending == null) return;
UsbDevice device = pending;
pending = null;
if (manager.hasPermission(device)) start(device);
else { busy = false; show("USB permission denied."); }
}
};
@Override public void onCreate(Bundle saved) {
super.onCreate(saved);
manager = (UsbManager) getSystemService(USB_SERVICE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(24, 24, 24, 24);
status = new TextView(this);
status.setTextIsSelectable(true);
addButton(layout, "Probe VITURE Pro 2", () -> select(PRODUCT, INTERFACE));
addButton(layout, "Stop and disable stream", () -> stop = true);
ScrollView scroll = new ScrollView(this);
scroll.addView(status);
layout.addView(scroll);
setContentView(layout);
if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, new IntentFilter(PERMISSION), Context.RECEIVER_NOT_EXPORTED);
else registerReceiver(receiver, new IntentFilter(PERMISSION));
String mode = getIntent().getStringExtra("mode");
rawMode = "raw".equals(mode);
invalidMode = mode != null && !rawMode && !"pose".equals(mode);
durationSeconds = Math.max(1, Math.min(30, getIntent().getIntExtra("seconds", 15)));
show("Pro 2 firmware query, " + (rawMode ? "raw" : "pose") + " at 120 Hz, then stream off. Capture window: " + durationSeconds + " s.");
if (invalidMode) show("Invalid mode: use pose or raw.");
show("Logs: " + getFilesDir() + "/captures");
for (UsbDevice device : manager.getDeviceList().values()) {
if (device.getVendorId() == VENDOR && device.getProductId() == PRODUCT)
show(String.format("Attached Pro 2 %04x:%04x, %d interfaces", VENDOR, PRODUCT, device.getInterfaceCount()));
}
if (getIntent().getBooleanExtra("auto", false)) {
select(getIntent().getIntExtra("pid", PRODUCT), getIntent().getIntExtra("interface", INTERFACE));
}
}
private void addButton(LinearLayout layout, String label, Runnable action) {
Button button = new Button(this);
button.setText(label);
button.setOnClickListener(view -> action.run());
layout.addView(button);
}
@Override protected void onDestroy() {
stop = true;
unregisterReceiver(receiver);
super.onDestroy();
}
private void show(String message) {
Log.i("VitureV2Probe", message);
runOnUiThread(() -> status.append(message + "\n"));
}
private void select(int product, int intf) {
if (busy) { show("A probe or permission request is already active."); return; }
if (invalidMode) { show("Probe disabled: use mode pose or raw."); return; }
if (product != PRODUCT || intf != INTERFACE) {
show("This probe requires Pro 2 pid 4865 (0x1301), interface 0."); return;
}
List<UsbDevice> matches = new ArrayList<>();
for (UsbDevice device : manager.getDeviceList().values()) {
if (device.getVendorId() == VENDOR && device.getProductId() == product) matches.add(device);
}
if (matches.size() != 1) { show("Expected one matching device; found " + matches.size()); return; }
busy = true;
stop = false;
UsbDevice device = matches.get(0);
if (manager.hasPermission(device)) start(device);
else {
pending = device;
PendingIntent permission = PendingIntent.getBroadcast(this, product,
new Intent(PERMISSION).setPackage(getPackageName()), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
manager.requestPermission(device, permission);
}
}
private void start(UsbDevice device) {
new Thread(() -> {
File directory = new File(getFilesDir(), "captures");
directory.mkdirs();
File file = new File(directory, "probe-" + System.currentTimeMillis() + "-pid-" + device.getProductId() + "-if-" + INTERFACE + ".jsonl");
try (Journal journal = new Journal(file)) {
show("Recording " + file.getName());
journal.event("session", "vendorId", device.getVendorId(), "productId", device.getProductId(),
"interface", INTERFACE, "seconds", durationSeconds, "wallTimeMillis", System.currentTimeMillis(),
"mode", rawMode ? "raw" : "pose",
"modeSource", getIntent().hasExtra("mode") ? "explicit intent extra" : "default pose",
"requestedStream", rawMode ? "raw_120hz" : "pose_120hz",
"upstreamCommit", "ece8c30485f7d357fefa362ae74f3eabac9b3899", "byteLimitPerInput", BYTE_LIMIT,
"quaternionNormTolerance", 0.05, "timestampMeaning", "host elapsedRealtimeNanos; decoded tick is an uncalibrated device field");
describe(device, journal);
probe(device, journal);
journal.event("session_end", "stoppedByUserOrActivity", stop);
show("Saved " + file.getAbsolutePath());
} catch (Exception error) { show("Probe error: " + error); }
finally { runOnUiThread(() -> busy = false); }
}, "viture-v2-probe").start();
}
private void describe(UsbDevice device, Journal journal) throws Exception {
journal.event("device", "vendorId", device.getVendorId(), "productId", device.getProductId(), "configurationCount", device.getConfigurationCount());
for (int c = 0; c < device.getConfigurationCount(); c++) {
UsbConfiguration configuration = device.getConfiguration(c);
journal.event("configuration", "productId", device.getProductId(), "id", configuration.getId(), "interfaceCount", configuration.getInterfaceCount());
for (int i = 0; i < configuration.getInterfaceCount(); i++) {
UsbInterface intf = configuration.getInterface(i);
journal.event("interface", "productId", device.getProductId(), "configurationId", configuration.getId(),
"interface", intf.getId(), "alternate", intf.getAlternateSetting(), "class", intf.getInterfaceClass(),
"subclass", intf.getInterfaceSubclass(), "protocol", intf.getInterfaceProtocol());
for (int e = 0; e < intf.getEndpointCount(); e++) {
UsbEndpoint endpoint = intf.getEndpoint(e);
journal.event("endpoint", "productId", device.getProductId(), "configurationId", configuration.getId(),
"interface", intf.getId(), "alternate", intf.getAlternateSetting(), "address", endpoint.getAddress(),
"type", endpoint.getType(), "direction", endpoint.getDirection(), "maxPacketSize", endpoint.getMaxPacketSize(), "interval", endpoint.getInterval());
}
}
}
}
private void probe(UsbDevice device, Journal journal) throws Exception {
if (device.getVendorId() != VENDOR || device.getProductId() != PRODUCT) {
journal.event("outcome", "result", "unsupported_product"); return;
}
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) { journal.event("outcome", "result", "open_failed"); return; }
UsbInterface claimed = null;
Pump pump = new Pump(connection, journal);
UsbEndpoint output = null;
boolean readsReady = false;
boolean enableAttempted = false;
String result = "unsupported_transport";
try {
byte[] descriptors = connection.getRawDescriptors();
journal.event("raw_descriptors", "length", descriptors == null ? -1 : descriptors.length, "bytesBase64", encode(descriptors));
byte[] active = new byte[1];
int configRead = connection.controlTransfer(0x80, 8, 0, 0, active, 1, 500);
journal.event("get_configuration", "result", configRead, "configuration", configRead == 1 ? active[0] & 255 : -1);
if (configRead != 1) return;
UsbConfiguration configuration = null;
for (int c = 0; c < device.getConfigurationCount(); c++) {
if (device.getConfiguration(c).getId() == (active[0] & 255)) configuration = device.getConfiguration(c);
}
if (configuration == null) return;
List<UsbInterface> alternatives = new ArrayList<>();
for (int i = 0; i < configuration.getInterfaceCount(); i++) {
if (configuration.getInterface(i).getId() == INTERFACE) alternatives.add(configuration.getInterface(i));
}
byte[] alt = new byte[1];
int altRead = connection.controlTransfer(0x81, 10, 0, INTERFACE, alt, 1, 500);
int activeAlt = altRead == 1 ? alt[0] & 255 : alternatives.size() == 1 && alternatives.get(0).getAlternateSetting() == 0 ? 0 : -1;
journal.event("get_interface", "result", altRead, "alternate", activeAlt,
"evidence", altRead == 1 ? "GET_INTERFACE" : "only advertised alternate zero or unknown");
UsbInterface selected = null;
for (UsbInterface intf : alternatives) if (intf.getAlternateSetting() == activeAlt) selected = intf;
if (selected == null) { journal.event("unsupported", "reason", "selected active interface unavailable"); return; }
if (activeAlt != 0 || selected.getInterfaceClass() != UsbConstants.USB_CLASS_HID || selected.getEndpointCount() != 2) {
journal.event("unsupported", "reason", "Pro 2 requires active HID interface 0 alternate 0 with two endpoints"); return;
}
List<UsbEndpoint> ins = new ArrayList<>();
int outputs = 0;
for (int e = 0; e < selected.getEndpointCount(); e++) {
UsbEndpoint endpoint = selected.getEndpoint(e);
if (endpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT || endpoint.getMaxPacketSize() != 64) continue;
if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) ins.add(endpoint);
else { output = endpoint; outputs++; }
}
if (outputs != 1 || ins.size() != 1) {
output = null;
journal.event("unsupported", "reason", "requires exactly one 64-byte interrupt IN and one 64-byte interrupt OUT",
"eligibleInputs", ins.size(), "eligibleOutputs", outputs);
return;
}
boolean success = connection.claimInterface(selected, false);
journal.event("claim_interface", "force", false, "success", success);
if (!success) {
success = connection.claimInterface(selected, true);
journal.event("claim_interface", "force", true, "success", success);
}
if (!success) { output = null; result = "claim_failed"; return; }
claimed = selected;
for (UsbEndpoint endpoint : ins) {
Input input = new Input(endpoint);
if (!input.request.initialize(connection, endpoint)) { input.request.close(); result = "input_initialize_failed"; return; }
input.request.setClientData(input);
pump.inputs.add(input);
}
readsReady = true;
for (Input input : pump.inputs) readsReady &= pump.queue(input);
journal.event("inputs_started", "allQueued", readsReady, "inputCount", pump.inputs.size(), "outputEndpoint", output.getAddress());
if (!readsReady || stop) { result = "input_queue_failed_or_stopped"; return; }
long deadline = SystemClock.elapsedRealtime() + durationSeconds * 1000L;
pump.send(output, "firmware_query", Protocol.firmware());
pump.until(Math.min(deadline, SystemClock.elapsedRealtime() + 400), true, true);
if (!stop && SystemClock.elapsedRealtime() < deadline) {
enableAttempted = true;
pump.send(output, rawMode ? "raw_120hz_enable" : "pose_120hz_enable", rawMode ? Protocol.raw120() : Protocol.pose120());
pump.until(deadline, true, true);
}
result = pump.validPose > 0 ? "validated_v2_pose" : pump.validRaw > 0 ? "validated_v2_raw" : pump.validFrames > 0 ? "v2_frames_without_validated_imu" : "no_validated_v2_frames";
} catch (Exception error) {
result = "error";
journal.event("error", "message", error.toString());
} finally {
if (enableAttempted && claimed != null && output != null && readsReady) {
try {
for (Input input : pump.inputs) if (!input.pending && input.bytes < BYTE_LIMIT) pump.queue(input);
pump.send(output, "stream_off_finally", Protocol.off());
pump.until(SystemClock.elapsedRealtime() + 200, false, true);
} catch (Exception error) { journal.safeEvent("stream_off_error", "message", error.toString()); }
}
try {
for (Input input : pump.inputs) if (input.pending) {
input.cancelRequested = true;
try { journal.safeEvent("input_cancel", "endpoint", input.endpoint.getAddress(), "success", input.request.cancel()); }
catch (Exception error) { journal.safeEvent("input_cancel_error", "message", error.toString()); }
}
for (Command command : pump.commands) if (command.pending) {
command.cancelRequested = true;
try { journal.safeEvent("command_cancel", "name", command.name, "success", command.request.cancel()); }
catch (Exception error) { journal.safeEvent("command_cancel_error", "message", error.toString()); }
}
try { pump.until(SystemClock.elapsedRealtime() + 100, false, false); } catch (Exception ignored) {}
for (Input input : pump.inputs) {
journal.safeEvent("input_end", "endpoint", input.endpoint.getAddress(), "bytes", input.bytes, "packets", input.packets,
"zeroLengthCompletions", input.zeros, "pendingAtClose", input.pending);
}
if (claimed != null) {
try { journal.safeEvent("release_interface", "success", connection.releaseInterface(claimed)); }
catch (Exception error) { journal.safeEvent("release_interface_error", "message", error.toString()); }
}
} finally {
try { connection.close(); }
finally {
for (Input input : pump.inputs) {
try { input.request.close(); } catch (Exception error) { journal.safeEvent("input_close_error", "message", error.toString()); }
}
for (Command command : pump.commands) {
try { command.request.close(); } catch (Exception error) { journal.safeEvent("command_close_error", "message", error.toString()); }
}
}
}
journal.safeEvent("outcome", "result", result, "validFrames", pump.validFrames, "invalidFrames", pump.invalidFrames,
"validPose", pump.validPose, "validRaw", pump.validRaw, "invalidSamples", pump.invalidSamples,
"firmwareReplies", pump.firmwareReplies, "successfulFirmwareReplies", pump.successfulFirmwareReplies, "controlAcks", pump.controlAcks,
"nonzeroControlStatuses", pump.nonzeroControlStatuses, "streamEnableAttempted", enableAttempted,
"poseEnableAttempted", !rawMode && enableAttempted, "rawEnableAttempted", rawMode && enableAttempted,
"streamOffWriteCompleted", pump.offCompleted);
show("Outcome: " + result + "; valid pose " + pump.validPose + ", raw " + pump.validRaw + ", v2 frames " + pump.validFrames);
}
}
private final class Pump {
final UsbDeviceConnection connection;
final Journal journal;
final List<Input> inputs = new ArrayList<>();
final List<Command> commands = new ArrayList<>();
int validFrames, invalidFrames, validPose, validRaw, invalidSamples, firmwareReplies, successfulFirmwareReplies, controlAcks, nonzeroControlStatuses;
boolean offCompleted;
Pump(UsbDeviceConnection connection, Journal journal) { this.connection = connection; this.journal = journal; }
boolean queue(Input input) throws Exception {
if (input.bytes >= BYTE_LIMIT) return false;
input.buffer.clear();
input.buffer.limit(Math.min(input.buffer.capacity(), BYTE_LIMIT - input.bytes));
input.cancelRequested = false;
input.queued = SystemClock.elapsedRealtimeNanos();
input.pending = input.request.queue(input.buffer);
if (!input.pending) journal.event("input_queue_failed", "endpoint", input.endpoint.getAddress());
return input.pending;
}
void send(UsbEndpoint endpoint, String name, byte[] bytes) throws Exception {
Command command = new Command(name, bytes);
if (!command.request.initialize(connection, endpoint)) { command.request.close(); journal.event("command_initialize_failed", "name", name); return; }
command.request.setClientData(command);
commands.add(command);
command.pending = command.request.queue(command.buffer);
journal.event("command_queued", "name", name, "endpoint", endpoint.getAddress(), "length", bytes.length,
"bytesBase64", encode(bytes), "queued", command.pending);
long deadline = SystemClock.elapsedRealtime() + 400;
while (command.pending && SystemClock.elapsedRealtime() < deadline) step(50, true);
if (command.pending) {
command.cancelRequested = true;
journal.event("command_timeout", "name", name, "cancelled", command.request.cancel());
}
}
void until(long deadline, boolean respectStop, boolean requeueInputs) throws Exception {
while ((!respectStop || !stop) && SystemClock.elapsedRealtime() < deadline) {
step(Math.min(50, Math.max(1, deadline - SystemClock.elapsedRealtime())), requeueInputs);
}
}
void step(long timeout, boolean requeue) throws Exception {
try {
UsbRequest completed = connection.requestWait(timeout);
if (completed == null) throw new IllegalStateException("requestWait returned null");
Object data = completed.getClientData();
if (data instanceof Command) {
Command command = (Command) data;
command.pending = false;
int length = command.buffer.position();
if (command.name.equals("stream_off_finally") && length == command.length) offCompleted = true;
journal.event("command_completion", "name", command.name, "actualLength", length, "expectedLength", command.length,
"afterCancel", command.cancelRequested);
return;
}
Input input = (Input) data;
input.pending = false;
int count = input.buffer.position();
byte[] bytes = new byte[count];
input.buffer.flip();
input.buffer.get(bytes);
input.bytes += count;
if (count > 0) input.packets++; else input.zeros++;
journal.event("input_transfer", "endpoint", input.endpoint.getAddress(), "queueElapsedRealtimeNanos", input.queued,
"length", count, "bytesBase64", encode(bytes), "afterCancel", input.cancelRequested);
if (count > 0) decode(bytes, input.endpoint.getAddress());
if (requeue && input.bytes < BYTE_LIMIT) queue(input);
} catch (TimeoutException ignored) {}
}
void decode(byte[] bytes, int endpoint) throws Exception {
Protocol.Frame frame;
try { frame = Protocol.parse(bytes); }
catch (IllegalArgumentException error) { invalidFrames++; journal.event("invalid_v2_frame", "endpoint", endpoint, "reason", error.getMessage()); return; }
validFrames++;
journal.event("v2_frame", "endpoint", endpoint, "messageId", frame.message, "payloadLength", frame.payload.length);
if (frame.message == Protocol.POSE || frame.message == Protocol.RAW) {
try {
Protocol.Sample sample = frame.message == Protocol.POSE ? Protocol.pose(frame) : Protocol.raw(frame);
if (frame.message == Protocol.POSE) validPose++; else validRaw++;
JSONArray values = new JSONArray();
for (float value : sample.values) values.put((double) value);
journal.event(frame.message == Protocol.POSE ? "valid_pose" : "valid_raw", "endpoint", endpoint,
"tick", sample.tick, "values", values, "norm", sample.norm,
"fields", frame.message == Protocol.POSE ? "qw,qx,qy,qz" : "gyroX,gyroY,gyroZ,accelX,accelY,accelZ");
} catch (IllegalArgumentException error) { invalidSamples++; journal.event("invalid_sample", "endpoint", endpoint, "messageId", frame.message, "reason", error.getMessage()); }
} else if (frame.message == Protocol.FIRMWARE + 0x2000 && frame.payload.length >= 1) {
firmwareReplies++;
String firmware = new String(frame.payload, 1, frame.payload.length - 1, StandardCharsets.US_ASCII).replace("\u0000", "");
if (frame.payload[0] == 0 && !firmware.isEmpty() && firmware.matches("[ -~]+")) successfulFirmwareReplies++;
journal.event("firmware_reply", "endpoint", endpoint, "status", frame.payload[0] & 255, "firmware", firmware);
} else if (frame.message == Protocol.CONTROL + 0x2000 && frame.payload.length == 1) {
controlAcks++;
if (frame.payload[0] != 0) nonzeroControlStatuses++;
journal.event("control_ack", "endpoint", endpoint, "status", frame.payload[0] & 255);
}
}
}
private static final class Input {
final UsbEndpoint endpoint;
final UsbRequest request = new UsbRequest();
final ByteBuffer buffer;
boolean pending, cancelRequested;
int bytes, packets, zeros;
long queued;
Input(UsbEndpoint endpoint) { this.endpoint = endpoint; buffer = ByteBuffer.allocateDirect(Math.max(1, endpoint.getMaxPacketSize())); }
}
private static final class Command {
final String name;
final int length;
final UsbRequest request = new UsbRequest();
final ByteBuffer buffer;
boolean pending, cancelRequested;
Command(String name, byte[] bytes) { this.name = name; length = bytes.length; buffer = ByteBuffer.allocateDirect(length); buffer.put(bytes).flip(); }
}
private static String encode(byte[] bytes) { return bytes == null ? "" : Base64.encodeToString(bytes, Base64.NO_WRAP); }
private static final class Journal implements AutoCloseable {
final BufferedWriter writer;
Journal(File file) throws Exception { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); }
void event(String event, Object... fields) throws Exception {
JSONObject json = new JSONObject();
json.put("event", event);
json.put("elapsedRealtimeNanos", SystemClock.elapsedRealtimeNanos());
for (int i = 0; i < fields.length; i += 2) json.put((String) fields[i], fields[i + 1]);
writer.write(json.toString());
writer.newLine();
writer.flush();
}
void safeEvent(String event, Object... fields) {
try { event(event, fields); } catch (Exception error) { Log.e("VitureV2Probe", "Could not log " + event, error); }
}
@Override public void close() throws Exception { writer.close(); }
}
}
@@ -0,0 +1,85 @@
package com.droiddeck.viturev2probe;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
public final class Protocol {
public static final int FIRMWARE = 0x3003;
public static final int CONTROL = 0x0301;
public static final int POSE = 0x7308;
public static final int RAW = 0x7309;
private Protocol() {}
public static byte[] firmware() { return frame(FIRMWARE, new byte[0]); }
public static byte[] pose120() { return frame(CONTROL, new byte[] {1, 2}); }
public static byte[] raw120() { return frame(CONTROL, new byte[] {2, 2}); }
public static byte[] off() { return frame(CONTROL, new byte[] {0, 0}); }
static byte[] frame(int message, byte[] payload) {
if (payload.length > 56) throw new IllegalArgumentException("payload exceeds upstream 64-byte frame");
ByteBuffer buffer = ByteBuffer.allocate(8 + payload.length).order(ByteOrder.LITTLE_ENDIAN);
int sum = 0;
for (byte value : payload) sum = (sum + (value & 255)) & 65535;
buffer.putShort((short) 0x10).putShort((short) message).putShort((short) payload.length).putShort((short) sum).put(payload);
return buffer.array();
}
public static Frame parse(byte[] data) {
if (data.length < 8) throw new IllegalArgumentException("short_header");
if (u16(data, 0) != 0x10) throw new IllegalArgumentException("preamble");
int length = u16(data, 4);
if (length > 56 || length + 8 > data.length) throw new IllegalArgumentException("payload_length");
int sum = 0;
for (int i = 8; i < 8 + length; i++) sum = (sum + (data[i] & 255)) & 65535;
if (sum != u16(data, 6)) throw new IllegalArgumentException("checksum");
return new Frame(u16(data, 2), Arrays.copyOfRange(data, 8, 8 + length));
}
public static Sample pose(Frame frame) {
if (frame.message != POSE || frame.payload.length != 24) throw new IllegalArgumentException("pose_length_or_id");
float[] values = floats(frame.payload, 8, 4);
double squared = 0;
for (float value : values) squared += (double) value * value;
double norm = Math.sqrt(squared);
if (Math.abs(norm - 1.0) > 0.05) throw new IllegalArgumentException("quaternion_norm");
return new Sample(tick(frame.payload), values, norm);
}
public static Sample raw(Frame frame) {
if (frame.message != RAW || frame.payload.length != 56) throw new IllegalArgumentException("raw_length_or_id");
float[] values = floats(frame.payload, 10, 6);
double accelNorm = Math.sqrt((double) values[3] * values[3] + (double) values[4] * values[4] + (double) values[5] * values[5]);
return new Sample(tick(frame.payload), values, accelNorm);
}
private static float[] floats(byte[] data, int offset, int count) {
ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
float[] values = new float[count];
for (int i = 0; i < count; i++) {
values[i] = buffer.getFloat(offset + i * 4);
if (Float.isNaN(values[i]) || Float.isInfinite(values[i])) throw new IllegalArgumentException("non_finite");
}
return values;
}
private static long tick(byte[] payload) {
return ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).getInt(4) & 0xffffffffL;
}
static int u16(byte[] data, int offset) { return (data[offset] & 255) | ((data[offset + 1] & 255) << 8); }
public static final class Frame {
public final int message;
public final byte[] payload;
Frame(int message, byte[] payload) { this.message = message; this.payload = payload; }
}
public static final class Sample {
public final long tick;
public final float[] values;
public final double norm;
Sample(long tick, float[] values, double norm) { this.tick = tick; this.values = values; this.norm = norm; }
}
}
@@ -0,0 +1,48 @@
package com.droiddeck.viturev2probe;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
public final class ProtocolTest {
private static int checks;
public static void main(String[] args) {
equal(Protocol.firmware(), hex("10 00 03 30 00 00 00 00"));
equal(Protocol.pose120(), hex("10 00 01 03 02 00 03 00 01 02"));
equal(Protocol.raw120(), hex("10 00 01 03 02 00 04 00 02 02"));
equal(Protocol.off(), hex("10 00 01 03 02 00 00 00 00 00"));
byte[] payload = hex("26 01 00 00 59 d6 21 00 dd e3 2b 3e 52 5d 7c 3f dd 45 9a 3b e8 27 52 3a");
byte[] poseFrame = Protocol.frame(Protocol.POSE, payload);
Protocol.Sample sample = Protocol.pose(Protocol.parse(poseFrame));
check(sample.tick == 0x0021d659L && Math.abs(sample.norm - 1) < 0.001);
check(Protocol.pose(Protocol.parse(Arrays.copyOf(poseFrame, 64))).tick == sample.tick);
reject(() -> Protocol.parse(Arrays.copyOf(poseFrame, 31)));
byte[] corrupt = poseFrame.clone();
corrupt[8] ^= 1;
reject(() -> Protocol.parse(corrupt));
reject(() -> Protocol.parse(hex("ff fe 00 00 00 00 00 00")));
reject(() -> Protocol.pose(Protocol.parse(Protocol.frame(Protocol.POSE, new byte[24]))));
ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(8, Float.NaN);
reject(() -> Protocol.pose(Protocol.parse(Protocol.frame(Protocol.POSE, payload))));
byte[] raw = new byte[56];
ByteBuffer buffer = ByteBuffer.wrap(raw).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(4, -1).putFloat(10, 0.1f).putFloat(14, 0.2f).putFloat(18, 0.3f).putFloat(30, 1f);
Protocol.Sample rawSample = Protocol.raw(Protocol.parse(Protocol.frame(Protocol.RAW, raw)));
check(rawSample.tick == 0xffffffffL && rawSample.values[0] == 0.1f && rawSample.norm == 1);
buffer.putFloat(30, Float.POSITIVE_INFINITY);
reject(() -> Protocol.raw(Protocol.parse(Protocol.frame(Protocol.RAW, raw))));
System.out.println("Protocol tests passed: " + checks);
}
private static void check(boolean condition) { if (!condition) throw new AssertionError(); checks++; }
private static void equal(byte[] actual, byte[] expected) { check(Arrays.equals(actual, expected)); }
private static void reject(Runnable operation) {
try { operation.run(); } catch (IllegalArgumentException expected) { checks++; return; }
throw new AssertionError("Expected rejection");
}
private static byte[] hex(String text) {
String[] parts = text.split(" ");
byte[] result = new byte[parts.length];
for (int i = 0; i < parts.length; i++) result[i] = (byte) Integer.parseInt(parts[i], 16);
return result;
}
}