diff --git a/app/src/main/assets/licenses/viture-v2/LICENSE b/app/src/main/assets/licenses/viture-v2/LICENSE new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/app/src/main/assets/licenses/viture-v2/LICENSE @@ -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. diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt b/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt index 947ed5fd27..fe09a7809e 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/Glasses.kt @@ -43,6 +43,7 @@ data class GlassesState( val volumeMax: Int = 8, val sunblock: Boolean = false, val hardwareControls: Boolean = true, + val supportsDisplayModeControl: Boolean = true, val hasSunblock: Boolean = true, val controlError: String? = null, val tracking: Boolean = false, @@ -64,7 +65,7 @@ data class GlassesState( val spatialConnected: Boolean get() = canControl && supportsSpatial fun usesSpatialControllers(settings: GlassesSettings) = spatialConnected && settings.positionalTracking && (settings.handControllers || settings.joyConTracking) - val can3d: Boolean get() = canControl && !noSignal && sbsSupport != SBS_FAILS + val can3d: Boolean get() = canControl && supportsDisplayModeControl && !noSignal && sbsSupport != SBS_FAILS val verticalFovDeg: Float get() { val half = Math.toRadians(diagonalFovDeg / 2.0) val aspect = if (width > 0 && height > 0) @@ -213,7 +214,7 @@ object Glasses { } fun sendMode(mode: Int) = post { - if (!_state.value.canControl) return@post + if (!_state.value.canControl || !_state.value.supportsDisplayModeControl) return@post if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) lastModeSentAt = SystemClock.uptimeMillis() } @@ -470,6 +471,7 @@ object Glasses { .put("controlError", s.controlError ?: JSONObject.NULL) .put("experimental", s.experimental) .put("supportsScreen3dof", s.supportsScreen3dof) + .put("supportsDisplayModeControl", s.supportsDisplayModeControl) .put("supportsSpatial", s.supportsSpatial) .put("firmware", (link as? VitureSdkLink)?.firmware ?: JSONObject.NULL) .put("spatialSdk", (link as? VitureSdkLink)?.spatialDiagnostics()?.let { @@ -614,14 +616,16 @@ object Glasses { switching3d = modeState.pendingStereo, brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8, sunblock = if (m === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock, - hardwareControls = device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel, + hardwareControls = m?.hardwareControls == true && + (device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel), + supportsDisplayModeControl = m?.supportsDisplayModeControl == true, hasSunblock = m?.hasSunblock == true, diagonalFovDeg = m?.diagonalFovDeg ?: 46f, tracking = it.tracking && link != null, noSignal = noSignal, sbs90 = m?.sbs90 == true, rates2d = m?.rates2d ?: listOf(60, 90, 120), - experimental = m === XrealModel, + experimental = m === XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk), supportsScreen3dof = link?.hasImu == true, supports30Hz = display?.let(::supports30Hz) == true, supportsSpatial = (link as? VitureSdkLink)?.isCarina == true, @@ -653,7 +657,8 @@ object Glasses { internal fun deviceModel(device: UsbDevice): GlassesModel? { val name = runCatching { device.productName }.getOrNull() return if (device.vendorId == VitureProtocol.VENDOR_ID) { - VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel) + if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) VitureProtocol.model(device.productId, name) + else VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel) ?: VitureProtocol.model(device.productId, name) } else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel @@ -720,7 +725,9 @@ object Glasses { calibrationKey = calibrationStore.key(device.vendorId, device.productId, runCatching { device.serialNumber }.getOrNull(), model?.name.orEmpty()) val l = if (device.vendorId == VitureProtocol.VENDOR_ID) { - if ((model as? VitureProtocol.Model)?.needsSdk == true) { + if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) { + VitureV2Link.open(usb, device, v2Listener(generation)) + } else if ((model as? VitureProtocol.Model)?.needsSdk == true) { // Android can evict cacheDir while the SDK is running. Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial)) VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation), @@ -851,6 +858,40 @@ object Glasses { } } + private fun v2Listener(generation: Long) = object : VitureV2Link.Listener { + override fun onReady() = post { + if (generation != linkGeneration) return@post + val current = link as? VitureV2Link ?: return@post + publish { it.copy(connected = current.ready, supportsScreen3dof = current.hasImu, + tracking = current.trackingActive, controlError = null) } + updateImu() + } + override fun onValue(msgId: Int, value: Int) = post { + if (generation != linkGeneration) return@post + when (msgId) { + VitureProtocol.MSG_GET_DISPLAY -> glassesMode = value + VitureProtocol.MSG_GET_BRIGHTNESS -> publish { it.copy(brightness = value) } + VitureProtocol.MSG_GET_VOLUME -> publish { it.copy(volume = value) } + } + } + override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) { + if (generation != linkGeneration) return + imuPackets++ + probe?.invoke(raw, q) + if (simulating.get() == null) deliver(q, timeNs) + } + override fun onTracking(active: Boolean) = post { + if (generation != linkGeneration) return@post + val current = link as? VitureV2Link ?: return@post + publish { it.copy(tracking = active && current.trackingActive) } + } + override fun onLost() = post { + if (generation != linkGeneration) return@post + closeLink() + publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) } + } + } + private fun rayNeoListener(generation: Long) = object : RayNeoLink.Listener { override fun onDeviceInfo(boardId: Int, calibrationSaved: Boolean) = post { if (generation != linkGeneration) return@post @@ -926,7 +967,7 @@ object Glasses { private fun applyMode(force: Boolean) { val s = _state.value val m = model ?: return - if (!s.canControl) return + if (!s.canControl || !s.supportsDisplayModeControl) return if (modeState.restorePending) { sendMode(false) return @@ -948,6 +989,7 @@ object Glasses { private fun sendMode(sbs: Boolean): Boolean { val m = model ?: return false + if (!m.supportsDisplayModeControl) return false if (sbs && !_settings.value.gameOnGlasses) update { it.copy(gameOnGlasses = true) } val g = _settings.value val resolution = GlassesDisplayModes.selected(g, _state.value, sbs) @@ -980,11 +1022,11 @@ object Glasses { val l = link ?: return if (!l.ready) return val want = (sink != null || poseObservers.isNotEmpty() || probe != null || _calibration.value.running || SpatialTracking.enabled) && l.hasImu - if (want == _state.value.tracking) return + if (l !is VitureV2Link && want == _state.value.tracking) return val accepted = l.send(VitureProtocol.MSG_IMU, byteArrayOf(if (want) 1 else 0)) if (want && !accepted) return if (want) l.send(VitureProtocol.MSG_IMU_RATE, byteArrayOf(VitureProtocol.IMU_RATE_240.toByte())) - publish { it.copy(tracking = want) } + publish { it.copy(tracking = if (l is VitureV2Link) l.trackingActive else want) } } private fun linkListener(generation: Long) = object : VitureLink.Listener { diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt b/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt index 7362ebf44a..5de0f03f52 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/GlassesHardware.kt @@ -4,6 +4,8 @@ package com.droiddeck.launcher.glasses interface GlassesModel { val name: String val controllable: Boolean + val hardwareControls: Boolean get() = true + val supportsDisplayModeControl: Boolean get() = true val brightnessMax: Int val volumeMax: Int val diagonalFovDeg: Float diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt b/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt index 4d3147d65d..573f0f8dcf 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/VitureProtocol.kt @@ -6,6 +6,7 @@ import kotlin.math.sqrt object VitureProtocol { const val VENDOR_ID = 0x35CA + const val PRO2_PRODUCT_ID = 0x1301 const val PACKET_SIZE = 64 private const val HEADER = 0x12 @@ -33,13 +34,19 @@ object VitureProtocol { enum class Family { ONE, PRO, LUMA, ULTRA, BEAST, PRO2 } - class Model(override val name: String, val family: Family) : GlassesModel { + class Model( + override val name: String, + val family: Family, + val needsSdk: Boolean = family == Family.ULTRA || family == Family.BEAST || family == Family.PRO2, + ) : GlassesModel { override val controllable: Boolean get() = true - val needsSdk: Boolean get() = family == Family.ULTRA || family == Family.BEAST || family == Family.PRO2 + private val directPro2: Boolean get() = family == Family.PRO2 && !needsSdk + override val hardwareControls: Boolean get() = !directPro2 + override val supportsDisplayModeControl: Boolean get() = !directPro2 val tall: Boolean get() = family == Family.LUMA || family == Family.ULTRA || family == Family.BEAST override val sbs90: Boolean get() = family == Family.ULTRA - override val brightnessMax: Int get() = 8 - override val volumeMax: Int get() = if (family == Family.BEAST) 15 else 8 + override val brightnessMax: Int get() = if (directPro2) 0 else 8 + override val volumeMax: Int get() = if (directPro2) 0 else if (family == Family.BEAST) 15 else 8 override val hasSunblock: Boolean get() = family != Family.PRO2 override val diagonalFovDeg: Float get() = when (family) { Family.ONE -> 43f @@ -89,6 +96,7 @@ object VitureProtocol { } fun model(productId: Int, productName: String?): Model? { + if (productId == PRO2_PRODUCT_ID) return Model("VITURE Pro 2", Family.PRO2, needsSdk = false) val family = when (productId) { 0x1011, 0x1013, 0x1015, 0x1017, 0x101b -> Family.ONE 0x1019, 0x101d -> Family.PRO diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Link.kt b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Link.kt new file mode 100644 index 0000000000..d46c246b7c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Link.kt @@ -0,0 +1,288 @@ +package com.droiddeck.launcher.glasses + +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.util.Log +import java.io.IOException +import java.nio.ByteBuffer +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.TimeoutException +import java.util.concurrent.atomic.AtomicLong + +internal class VitureV2Link internal constructor( + private val transport: Transport, + private val listener: Listener, +) : GlassesLink { + interface Listener { + fun onReady() + fun onValue(msgId: Int, value: Int) + fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) + fun onTracking(active: Boolean) + fun onLost() + } + + internal data class Received(val bytes: ByteArray, val timeNs: Long) + internal interface Transport { + fun write(packet: ByteArray): Boolean + fun read(timeoutMs: Long): Received? + fun close() + } + + private data class Command(val packet: ByteArray, val stream: Boolean? = null) + private val commands = ArrayBlockingQueue(16) + private val stateLock = Any() + private val bad = AtomicLong() + @Volatile private var running = true + @Volatile private var wanted = true + @Volatile override var ready = false + private set + @Volatile var trackingActive = false + private set + override val hasImu: Boolean get() = ready + override val badFrames: Long get() = bad.get() + @Volatile private var streamOn = false + private var lastPoseAt = 0L + private var lastTick: Long? = null + private var poseNotBefore = 0L + private val worker = Thread(::run, "viture-v2").apply { isDaemon = true; start() } + + override fun send(msgId: Int, payload: ByteArray): Boolean { + synchronized(stateLock) { + if (!running || !ready) return false + if (msgId == VitureProtocol.MSG_IMU) { + if (payload.size != 1 || payload[0].toInt() !in 0..1) return false + val enabled = payload[0].toInt() == 1 + if (wanted == enabled) return true + val command = Command(VitureV2Protocol.imuControl( + if (enabled) VitureV2Protocol.STREAM_POSE else VitureV2Protocol.STREAM_OFF), enabled) + if (!commands.offer(command)) return false + wanted = enabled + if (!enabled) { + streamOn = false + tracking(false) + } + return true + } + if (msgId == VitureProtocol.MSG_GET_IMU) return true + // Keep the measured 120 Hz mode; the generic controller requests 240 Hz. + if (msgId == VitureProtocol.MSG_IMU_RATE) return false + val query = when (msgId) { + VitureProtocol.MSG_GET_BRIGHTNESS -> VitureV2Protocol.MSG_GET_BRIGHTNESS + VitureProtocol.MSG_GET_VOLUME -> VitureV2Protocol.MSG_GET_VOLUME + VitureProtocol.MSG_GET_DISPLAY -> VitureV2Protocol.MSG_GET_DISPLAY + else -> return false + } + return payload.isEmpty() && commands.offer(Command(VitureV2Protocol.packet(query))) + } + } + + private fun tracking(active: Boolean) { + if (trackingActive != active) { + trackingActive = active + listener.onTracking(active) + } + } + + private fun run() { + try { + if (!transport.write(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE))) + throw IOException("Could not start pose stream") + poseNotBefore = System.nanoTime() + streamOn = true + lastPoseAt = System.nanoTime() + while (running) { + commands.poll()?.let { command -> + if (!transport.write(command.packet)) throw IOException("USB command failed") + val completedAt = System.nanoTime() + synchronized(stateLock) { + command.stream?.let { + streamOn = it + lastTick = null + poseNotBefore = completedAt + lastPoseAt = System.nanoTime() + } + } + } + transport.read(100)?.let(::receive) + if (streamOn && System.nanoTime() - lastPoseAt > POSE_TIMEOUT_NS) + throw IOException("No fresh valid pose samples") + } + } catch (e: Exception) { + if (running) { + ready = false + tracking(false) + Log.w(TAG, "V2 connection lost: ${e.message}") + listener.onLost() + } + } finally { + running = false + ready = false + tracking(false) + runCatching { transport.write(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) } + transport.close() + } + } + + private fun receive(received: Received) = synchronized(stateLock) { + if (!running) return + val frame = VitureV2Protocol.parse(received.bytes) ?: run { bad.incrementAndGet(); return } + if (frame.msgId == VitureV2Protocol.EVENT_POSE) { + val pose = VitureV2Protocol.pose(frame) ?: run { bad.incrementAndGet(); return } + if (!streamOn || !wanted || received.timeNs < poseNotBefore) return + val previous = lastTick + if (previous != null) { + val delta = (pose.deviceTick - previous) and 0xffffffffL + if (delta == 0L || delta >= 0x80000000L) return + } + lastTick = pose.deviceTick + lastPoseAt = System.nanoTime() + val becameReady = !ready + ready = true + tracking(true) + if (becameReady) listener.onReady() + val q = pose.quaternion + // Upstream right/up/back pose converted to the shared VITURE legacy basis. + val shared = floatArrayOf(-q[2], -q[0], q[1], q[3]) + // Upstream does not establish device tick units; use host monotonic receipt time. + if (running && wanted && streamOn) listener.onPose(received.bytes, shared, received.timeNs) + return + } + VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_IMU_CONTROL)?.let { + if (!it.success) throw IOException("Pose stream rejected with status ${it.status}") + } + val queries = arrayOf( + VitureV2Protocol.MSG_GET_BRIGHTNESS to VitureProtocol.MSG_GET_BRIGHTNESS, + VitureV2Protocol.MSG_GET_VOLUME to VitureProtocol.MSG_GET_VOLUME, + VitureV2Protocol.MSG_GET_DISPLAY to VitureProtocol.MSG_GET_DISPLAY, + ) + for ((query, internalId) in queries) { + val reply = VitureV2Protocol.reply(frame, query) ?: continue + if (reply.success && reply.body.size == 1) listener.onValue(internalId, reply.body[0].toInt() and 255) + } + } + + override fun close() { + synchronized(stateLock) { + running = false + ready = false + wanted = false + commands.clear() + } + if (Thread.currentThread() !== worker) worker.join(1500) + } + + companion object { + private const val TAG = "VitureV2Link" + private const val POSE_TIMEOUT_NS = 3_000_000_000L + const val PRODUCT_ID = 0x1301 + + fun open(usb: UsbManager, device: UsbDevice, listener: Listener): VitureV2Link? { + if (device.vendorId != VitureProtocol.VENDOR_ID || device.productId != PRODUCT_ID) return null + val candidates = (0 until device.interfaceCount).map(device::getInterface).filter { + it.interfaceClass == UsbConstants.USB_CLASS_HID && it.alternateSetting == 0 && it.endpointCount == 2 + }.mapNotNull { intf -> + val endpoints = (0 until intf.endpointCount).map(intf::getEndpoint) + val input = endpoints.singleOrNull { it.direction == UsbConstants.USB_DIR_IN && + it.type == UsbConstants.USB_ENDPOINT_XFER_INT && it.maxPacketSize == 64 } + val output = endpoints.singleOrNull { it.direction == UsbConstants.USB_DIR_OUT && + it.type == UsbConstants.USB_ENDPOINT_XFER_INT && it.maxPacketSize == 64 } + if (input != null && output != null) Triple(intf, input, output) else null + } + val (intf, input, output) = candidates.singleOrNull() ?: return null + val connection = usb.openDevice(device) ?: return null + if (!connection.claimInterface(intf, true)) { connection.close(); return null } + return try { + VitureV2Link(AndroidTransport(connection, intf, input, output), listener) + } catch (e: Exception) { + connection.releaseInterface(intf) + connection.close() + Log.w(TAG, "Could not initialize USB requests", e) + null + } + } + } + + private class AndroidTransport( + private val connection: UsbDeviceConnection, + private val intf: UsbInterface, + input: UsbEndpoint, + output: UsbEndpoint, + ) : Transport { + private val inputRequest = UsbRequest() + private val outputRequest = UsbRequest() + private val inputBuffer = ByteBuffer.allocateDirect(64) + private var outputBuffer: ByteBuffer? = null + private var outputPending = false + private val received = ArrayDeque() + + init { + try { + if (!inputRequest.initialize(connection, input) || !outputRequest.initialize(connection, output)) + throw IOException("USB request initialization failed") + queueInput() + } catch (e: Exception) { + inputRequest.close() + outputRequest.close() + throw e + } + } + + private fun queueInput() { + inputBuffer.clear() + if (!inputRequest.queue(inputBuffer)) throw IOException("USB input queue failed") + } + + private fun await(timeoutMs: Long) { + val completed = try { connection.requestWait(timeoutMs) } catch (_: TimeoutException) { return } + ?: throw IOException("USB device disconnected") + if (completed === outputRequest) { + outputPending = false + } else if (completed === inputRequest) { + val count = inputBuffer.position() + if (count > 0) { + val bytes = ByteArray(count) + inputBuffer.flip() + inputBuffer.get(bytes) + if (received.size >= 512) throw IOException("USB input backlog overflow") + received.addLast(Received(bytes, System.nanoTime())) + } + queueInput() + } + } + + override fun write(packet: ByteArray): Boolean { + if (outputPending) throw IOException("Previous USB output has not completed") + val buffer = ByteBuffer.allocateDirect(packet.size).apply { put(packet); flip() } + outputBuffer = buffer + outputPending = outputRequest.queue(buffer) + if (!outputPending) return false + val deadline = System.nanoTime() + 250_000_000L + while (outputPending && System.nanoTime() < deadline) await(25) + if (outputPending) { + outputRequest.cancel() + throw IOException("USB output timed out") + } + return buffer.position() == packet.size + } + + override fun read(timeoutMs: Long): Received? { + if (received.isEmpty()) await(timeoutMs) + return received.removeFirstOrNull() + } + + override fun close() { + inputRequest.cancel() + if (outputPending) outputRequest.cancel() + connection.releaseInterface(intf) + connection.close() + inputRequest.close() + outputRequest.close() + outputBuffer = null + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Protocol.kt b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Protocol.kt new file mode 100644 index 0000000000..548ad6b918 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/glasses/VitureV2Protocol.kt @@ -0,0 +1,132 @@ +// Adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick. +// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/. +package com.droiddeck.launcher.glasses + +import kotlin.math.sqrt + +object VitureV2Protocol { + const val PACKET_SIZE = 64 + const val HEADER_SIZE = 8 + const val RESPONSE_OFFSET = 0x2000 + private const val PREAMBLE = 0x0010 + private const val MAX_PAYLOAD_SIZE = PACKET_SIZE - HEADER_SIZE + + const val MSG_IMU_CONTROL = 0x0301 + const val MSG_GET_SERIAL = 0x3002 + const val MSG_GET_VERSION = 0x3003 + const val MSG_GET_BRIGHTNESS = 0x3122 + const val MSG_GET_DUTY_CYCLE = 0x3125 + const val MSG_GET_DISPLAY = 0x3141 + const val MSG_GET_VOLUME = 0x3201 + const val MSG_GET_WEAR = 0x3321 + const val EVENT_POSE = 0x7308 + const val EVENT_RAW = 0x7309 + + const val STREAM_OFF = 0 + const val STREAM_POSE = 1 + const val STREAM_RAW = 2 + + enum class Rate(val wireValue: Int, val hz: Int) { + HZ_60(0, 60), HZ_90(1, 90), HZ_120(2, 120), + HZ_240(3, 240), HZ_500(4, 500), HZ_1000(5, 1000), + } + + class Frame internal constructor(val msgId: Int, val payload: ByteArray) + + class Reply internal constructor(val status: Int, val body: ByteArray) { + val success: Boolean get() = status == 0 + } + + // Device ticks have no established time unit; quaternion is xyzw with no axis remapping. + class Pose internal constructor( + val deviceTick: Long, + val quaternion: FloatArray, + val unknown: Long, + ) + + class RawSample internal constructor( + val deviceTick: Long, + val gyroRadPerSec: FloatArray, + val accelG: FloatArray, + val payload: ByteArray, + ) + + fun packet(msgId: Int, payload: ByteArray = ByteArray(0)): ByteArray { + require(msgId in 0..0xFFFF) + require(payload.size <= MAX_PAYLOAD_SIZE) + return ByteArray(HEADER_SIZE + payload.size).also { buffer -> + putU16(buffer, 0, PREAMBLE) + putU16(buffer, 2, msgId) + putU16(buffer, 4, payload.size) + putU16(buffer, 6, checksum(payload, 0, payload.size)) + payload.copyInto(buffer, HEADER_SIZE) + } + } + + fun imuControl(streams: Int, rate: Rate = Rate.HZ_120): ByteArray { + // Upstream measured that stream mask 3 ACKs but produces no events on Pro 2. + require(streams == STREAM_OFF || streams == STREAM_POSE || streams == STREAM_RAW) + require(streams != STREAM_POSE || rate.hz <= 240) + val wireRate = if (streams == STREAM_OFF) 0 else rate.wireValue + return packet(MSG_IMU_CONTROL, byteArrayOf(streams.toByte(), wireRate.toByte())) + } + + fun parse(buffer: ByteArray, size: Int = buffer.size): Frame? { + if (size < HEADER_SIZE || size > PACKET_SIZE || size > buffer.size) return null + if (u16(buffer, 0) != PREAMBLE) return null + val payloadSize = u16(buffer, 4) + if (payloadSize > MAX_PAYLOAD_SIZE || HEADER_SIZE + payloadSize > size) return null + if (checksum(buffer, HEADER_SIZE, payloadSize) != u16(buffer, 6)) return null + return Frame(u16(buffer, 2), buffer.copyOfRange(HEADER_SIZE, HEADER_SIZE + payloadSize)) + } + + fun reply(frame: Frame, requestMsgId: Int): Reply? { + if (requestMsgId !in 0..0xFFFF || frame.msgId != ((requestMsgId + RESPONSE_OFFSET) and 0xFFFF)) return null + if (frame.payload.isEmpty()) return null + return Reply(u8(frame.payload[0]), frame.payload.copyOfRange(1, frame.payload.size)) + } + + fun pose(frame: Frame): Pose? { + if (frame.msgId != EVENT_POSE || frame.payload.size != 24) return null + val payload = frame.payload + val w = float(payload, 8) + val x = float(payload, 12) + val y = float(payload, 16) + val z = float(payload, 20) + if (!w.isFinite() || !x.isFinite() || !y.isFinite() || !z.isFinite()) return null + val norm = sqrt(w.toDouble() * w + x.toDouble() * x + y.toDouble() * y + z.toDouble() * z) + if (norm !in 0.9..1.1) return null + val n = norm.toFloat() + return Pose(u32(payload, 4), floatArrayOf(x / n, y / n, z / n, w / n), u32(payload, 0)) + } + + fun raw(frame: Frame): RawSample? { + if (frame.msgId != EVENT_RAW || frame.payload.size != 56) return null + val payload = frame.payload + val gyro = floatArrayOf(float(payload, 10), float(payload, 14), float(payload, 18)) + val accel = floatArrayOf(float(payload, 22), float(payload, 26), float(payload, 30)) + if (gyro.any { !it.isFinite() } || accel.any { !it.isFinite() }) return null + return RawSample(u32(payload, 4), gyro, accel, payload.copyOf()) + } + + private fun checksum(buffer: ByteArray, offset: Int, size: Int): Int { + var sum = 0 + for (i in offset until offset + size) sum += u8(buffer[i]) + return sum and 0xFFFF + } + + private fun u8(value: Byte) = value.toInt() and 0xFF + + private fun u16(buffer: ByteArray, offset: Int) = + u8(buffer[offset]) or (u8(buffer[offset + 1]) shl 8) + + private fun u32(buffer: ByteArray, offset: Int): Long = + u16(buffer, offset).toLong() or (u16(buffer, offset + 2).toLong() shl 16) + + private fun float(buffer: ByteArray, offset: Int): Float = Float.fromBits(u32(buffer, offset).toInt()) + + private fun putU16(buffer: ByteArray, offset: Int, value: Int) { + buffer[offset] = value.toByte() + buffer[offset + 1] = (value ushr 8).toByte() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt index 50ce39b29a..92e0aef3bc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt @@ -149,7 +149,8 @@ internal fun GlassesGroups( } } if (display) SettingsGroup(g.model) { - if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(R.string.glasses_xreal_experimental)) {} + if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource( + if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {} val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(), stringResource(if (g.sbs) R.string.glasses_mode_3d else R.string.glasses_mode_2d)) else null when { @@ -168,7 +169,7 @@ internal fun GlassesGroups( ToggleRow(host, "glasses-game", stringResource(R.string.glasses_game_on), stringResource(R.string.glasses_game_on_hint), s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) } } - if (display && g.canControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) { + if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) { SettingsGroup(stringResource(R.string.glasses_display_mode)) { if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) { ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed), @@ -177,7 +178,7 @@ internal fun GlassesGroups( g.sbs, chipModifier = track("glasses-3d")) { Glasses.set3d(it) } } } - if (display && g.canControl) { + if (display && g.canControl && g.supportsDisplayModeControl) { val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false)) else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D) for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D) @@ -214,9 +215,9 @@ internal fun GlassesGroups( } if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) { steamVr() - ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d), stringResource(R.string.glasses_auto3d_hint), - s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) } - if (g.canControl) { + if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d), + stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) } + if (g.canControl && g.supportsDisplayModeControl) { GlassesResolutionRow(host, g, s, GlassesDisplayProfile.VR, track) if (steamVrRunning && tab != null) GlassesRefreshRow(host, g, s, track) } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index b54ebd9aa3..d60a59fb94 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2607,6 +2607,7 @@ في انتظار اتصال USB Ethernet الخاص بالنظارة. قد لا يتيحه هذا الهاتف للتطبيقات. انقطع اتصال XREAL أو أعاد استجابة غير مدعومة. جارٍ إعادة المحاولة… دعم تجريبي لـ 1S. استخدم وضع Follow وعطّل تثبيت الصورة من قائمة النظارة. لا تزال اتجاهات التتبّع وأوضاع العرض بحاجة إلى اختبار على الجهاز. + تتبّع تجريبي لحركة الرأس لنظارة Pro 2. لا يُدعم بعد ضبط السطوع ومستوى الصوت أو تبديل وضع العرض. Cardboard VR وضع Cardboard عرض للعين اليسرى وآخر لليمنى لنظارة واقع افتراضي للهاتف. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index a7908694ce..b924266f43 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1029,6 +1029,7 @@ Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps. La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando… Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla. + Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles. En lugar de View/Select. Animaciones Los sticks aparecen donde tocas y se ocultan al soltar diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index ecd90da46a..f6d820e9e4 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -2507,6 +2507,7 @@ Изчаква се USB Ethernet връзката на очилата. Този телефон може да не я предоставя на приложенията. Връзката с XREAL беше прекъсната или върна неподдържан отговор. Нов опит… Експериментална поддръжка на 1S. Използвайте режим Follow и изключете стабилизацията в менюто на очилата. Посоките на проследяване и режимите на показване все още трябва да се тестват на устройство. + Експериментално проследяване на движенията на главата за Pro 2. Регулирането на яркостта и силата на звука и превключването на режима на показване все още не се поддържат. Cardboard VR Режим Cardboard Изображения за лявото и дясното око за VR очила за телефон. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 2929884765..74c7e327f9 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -2557,6 +2557,7 @@ Čeká se na připojení USB Ethernet brýlí. Tento telefon ho možná aplikacím nezpřístupňuje. Připojení XREAL bylo přerušeno nebo vrátilo nepodporovanou odpověď. Zkouší se to znovu… Experimentální podpora 1S. V nabídce brýlí použijte režim Follow a vypněte stabilizaci. Směry sledování a režimy zobrazení je ještě třeba otestovat na zařízení. + Experimentální sledování pohybu hlavy pro Pro 2. Nastavení jasu, hlasitosti a přepínání režimů zobrazení zatím nejsou podporovány. Cardboard VR Režim Cardboard Obraz pro levé a pravé oko pro VR brýle pro telefon. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index a7d2f5575a..062bcb4b54 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -2507,6 +2507,7 @@ Venter på brillens USB-Ethernet-forbindelse. Denne telefon gør den muligvis ikke tilgængelig for apps. XREAL-forbindelsen blev afbrudt eller returnerede et svar, der ikke understøttes. Prøver igen… Eksperimentel understøttelse af 1S. Brug Follow-tilstand, og slå stabilisering fra i brillens menu. Sporingsretninger og visningstilstande mangler stadig test på enheden. + Eksperimentel hovedsporing til Pro 2. Justering af lysstyrke og lydstyrke samt skift af visningstilstand understøttes endnu ikke. Cardboard VR Cardboard-tilstand Billeder til venstre og højre øje til en VR-brille til telefonen. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 8376b925a8..d46e0c5758 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2493,6 +2493,7 @@ Warte auf die USB-Ethernet-Verbindung der Brille. Dieses Smartphone stellt sie Apps möglicherweise nicht bereit. Die XREAL-Verbindung wurde unterbrochen oder hat eine nicht unterstützte Antwort geliefert. Neuer Versuch … Experimentelle Unterstützung für die 1S. Nutze den Follow-Modus und deaktiviere die Stabilisierung im Menü der Brille. Tracking-Richtungen und Anzeigemodi müssen noch auf Geräten getestet werden. + Experimentelles Kopftracking für Pro 2. Das Einstellen von Helligkeit und Lautstärke sowie das Umschalten des Anzeigemodus werden noch nicht unterstützt. Cardboard VR Cardboard-Modus Bilder für linkes und rechtes Auge für eine Smartphone-VR-Brille. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 3e75ec7cf3..dd6458776e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -2507,6 +2507,7 @@ Αναμονή για τη σύνδεση USB Ethernet των γυαλιών. Αυτό το τηλέφωνο ίσως δεν τη διαθέτει στις εφαρμογές. Η σύνδεση XREAL διακόπηκε ή επέστρεψε μη υποστηριζόμενη απόκριση. Νέα προσπάθεια… Πειραματική υποστήριξη για 1S. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών. Οι κατευθύνσεις παρακολούθησης και οι λειτουργίες οθόνης χρειάζονται ακόμα δοκιμή σε συσκευή. + Πειραματική παρακολούθηση κεφαλής για Pro 2. Η ρύθμιση της φωτεινότητας και της έντασης ήχου και η αλλαγή λειτουργίας οθόνης δεν υποστηρίζονται ακόμη. Cardboard VR Λειτουργία Cardboard Εικόνες για το αριστερό και το δεξί μάτι, για γυαλιά VR κινητού. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 1e44f94029..9060bac1e7 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2517,6 +2517,7 @@ Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps. La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando… Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla. + Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles. Desarrollador Distribuidor Lanzamiento diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 3f8ada5c87..a6e7493725 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -2507,6 +2507,7 @@ Odotetaan lasien USB-Ethernet-yhteyttä. Tämä puhelin ei ehkä tarjoa sitä sovelluksille. XREAL-yhteys katkesi tai palautti vastauksen, jota ei tueta. Yritetään uudelleen… Kokeellinen 1S-tuki. Käytä Follow-tilaa ja poista vakautus käytöstä lasien valikosta. Seurannan suunnat ja näyttötilat vaativat vielä testausta laitteella. + Kokeellinen päänliikkeiden seuranta Pro 2:lle. Kirkkauden ja äänenvoimakkuuden säätöä sekä näyttötilan vaihtamista ei vielä tueta. Cardboard VR Cardboard-tila Vasemman ja oikean silmän kuvat puhelimen VR-laseille. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f1b72a75a6..9e7d00dcc7 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -2528,6 +2528,7 @@ En attente de la connexion Ethernet USB des lunettes. Ce téléphone ne la rend peut-être pas accessible aux applications. La connexion XREAL a été interrompue ou a renvoyé une réponse non prise en charge. Nouvelle tentative… Prise en charge expérimentale des 1S. Utilisez le mode Follow et désactivez la stabilisation dans le menu des lunettes. Le sens du suivi et les modes d\'affichage restent à tester sur l\'appareil. + Suivi expérimental des mouvements de la tête pour Pro 2. Le réglage de la luminosité et du volume ainsi que le changement de mode d\'affichage ne sont pas encore pris en charge. Développeur Éditeur Sortie diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 3087a4f5d4..c7d0f6005e 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -2507,6 +2507,7 @@ चश्मे के USB Ethernet कनेक्शन का इंतज़ार है। हो सकता है यह फ़ोन इसे ऐप्स को उपलब्ध न कराए। XREAL कनेक्शन टूट गया या उसने ऐसा जवाब दिया जो समर्थित नहीं है। फिर से कोशिश हो रही है… 1S के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें। ट्रैकिंग की दिशाएं और डिस्प्ले मोड अभी डिवाइस पर टेस्ट होने बाकी हैं। + Pro 2 के लिए प्रायोगिक हेड ट्रैकिंग। चमक और वॉल्यूम बदलना और डिस्प्ले मोड स्विच करना अभी समर्थित नहीं है। Cardboard VR Cardboard मोड फ़ोन VR व्यूअर के लिए बाईं और दाईं आंख के व्यू। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index b2f654b134..c146857a5e 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -2507,6 +2507,7 @@ Várakozás a szemüveg USB-s Ethernet-kapcsolatára. Lehet, hogy ez a telefon nem teszi elérhetővé az alkalmazások számára. Az XREAL-kapcsolat megszakadt, vagy nem támogatott választ adott. Újrapróbálkozás… Kísérleti 1S-támogatás. Használja a Follow módot, és kapcsolja ki a stabilizálást a szemüveg menüjében. A követési irányokat és a megjelenítési módokat még tesztelni kell az eszközön. + Kísérleti fejkövetés a Pro 2-höz. A fényerő és a hangerő beállítása, valamint a megjelenítési mód váltása még nem támogatott. Cardboard VR Cardboard mód Bal és jobb szem képe telefonos VR-szemüveghez. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index da22c11fe2..8208d2fa3c 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -2482,6 +2482,7 @@ Menunggu koneksi Ethernet USB dari kacamata. Ponsel ini mungkin tidak menyediakannya untuk aplikasi. Koneksi XREAL terputus atau memberikan respons yang tidak didukung. Mencoba lagi… Dukungan 1S eksperimental. Gunakan mode Follow dan nonaktifkan stabilisasi di menu kacamata. Arah pelacakan dan mode tampilan masih perlu diuji di perangkat. + Pelacakan kepala Pro 2 eksperimental. Pengaturan kecerahan, volume, dan pergantian mode tampilan belum didukung. Cardboard VR Mode Cardboard Tampilan mata kiri dan kanan untuk kacamata VR ponsel. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 1588bfe3f0..75e4645136 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2518,6 +2518,7 @@ In attesa della connessione USB Ethernet degli occhiali. Questo telefono potrebbe non renderla disponibile alle app. La connessione XREAL si è interrotta o ha restituito una risposta non supportata. Nuovo tentativo… Supporto sperimentale per 1S. Usa la modalità Follow e disattiva la stabilizzazione nel menu degli occhiali. Direzioni del tracciamento e modalità di visualizzazione devono ancora essere testate sul dispositivo. + Tracciamento sperimentale della testa per Pro 2. La regolazione di luminosità e volume e il cambio della modalità di visualizzazione non sono ancora supportati. Cardboard VR Modalità Cardboard Immagini per l\'occhio sinistro e destro, per un visore VR per telefono. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index f3ce1c5f79..f1e78ddb83 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2484,6 +2484,7 @@ グラスの USB Ethernet 接続を待っています。このスマートフォンでは、アプリがこの接続を利用できない場合があります。 XREAL との接続が中断されたか、サポートされていない応答が返されました。再試行しています… 1S のサポートは試験運用中です。グラスのメニューで Follow モードを使い、安定化をオフにしてください。トラッキングの方向と表示モードは、まだ実機でのテストが必要です。 + Pro 2 のヘッドトラッキングは試験運用中です。明るさと音量の調整、および表示モードの切り替えにはまだ対応していません。 開発元 パブリッシャー 発売日 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 45966e7886..6b7efb33ad 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -2484,6 +2484,7 @@ 안경의 USB Ethernet 연결을 기다리는 중입니다. 이 휴대폰은 앱에 이 연결을 제공하지 않을 수 있습니다. XREAL 연결이 중단되었거나 지원되지 않는 응답을 받았습니다. 다시 시도하는 중… 1S 지원은 실험 단계입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. 트래킹 방향과 디스플레이 모드는 아직 기기에서 테스트가 필요합니다. + Pro 2 헤드 트래킹은 실험 단계입니다. 밝기와 음량 조절 및 디스플레이 모드 전환은 아직 지원되지 않습니다. 개발사 배급사 출시일 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 49cf1e98ac..ef8c7d5f22 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -2482,6 +2482,7 @@ Menunggu sambungan USB Ethernet cermin mata. Telefon ini mungkin tidak mendedahkannya kepada apl. Sambungan XREAL terganggu atau memberikan respons yang tidak disokong. Mencuba semula… Sokongan eksperimen untuk 1S. Gunakan mod Follow dan matikan penstabilan dalam menu cermin mata. Arah penjejakan dan mod paparan masih perlu diuji pada peranti. + Penjejakan kepala Pro 2 secara eksperimen. Pelarasan kecerahan, kelantangan dan pertukaran mod paparan belum disokong. Cardboard VR Mod Cardboard Paparan mata kiri dan kanan untuk kaca mata VR telefon. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index d391715a74..5dc36a00c5 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -2507,6 +2507,7 @@ Venter på USB Ethernet-tilkoblingen til brillene. Denne telefonen gjør den kanskje ikke tilgjengelig for apper. XREAL-tilkoblingen ble avbrutt eller ga et svar som ikke støttes. Prøver igjen… Eksperimentell støtte for 1S. Bruk Follow-modus og slå av stabilisering i brillemenyen. Sporingsretninger og visningsmoduser må fortsatt testes på enheten. + Eksperimentell hodesporing for Pro 2. Justering av lysstyrke og volum samt bytte av visningsmodus støttes ikke ennå. Cardboard VR Cardboard-modus Bilder for venstre og høyre øye til en VR-brille for mobil. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index fa6cca7f0e..02b1493d52 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -2507,6 +2507,7 @@ Wachten op de USB Ethernet-verbinding van de bril. Deze telefoon maakt die mogelijk niet beschikbaar voor apps. De XREAL-verbinding is onderbroken of gaf een niet-ondersteund antwoord. Opnieuw proberen… Experimentele ondersteuning voor 1S. Gebruik de Follow-modus en schakel stabilisatie uit in het menu van de bril. Trackingrichtingen en weergavemodi moeten nog op een apparaat worden getest. + Experimentele hoofdtracking voor Pro 2. Het aanpassen van helderheid en volume en het wisselen van weergavemodus worden nog niet ondersteund. Cardboard VR Cardboard-modus Beelden voor linker- en rechteroog voor een VR-bril voor je telefoon. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ab532f448a..a135e012d7 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -2560,6 +2560,7 @@ Oczekiwanie na połączenie USB Ethernet okularów. Ten telefon może nie udostępniać go aplikacjom. Połączenie z XREAL zostało przerwane lub zwróciło nieobsługiwaną odpowiedź. Ponawianie… Eksperymentalna obsługa 1S. Użyj trybu Follow i wyłącz stabilizację w menu okularów. Kierunki śledzenia i tryby wyświetlania wymagają jeszcze testów na urządzeniu. + Eksperymentalne śledzenie ruchów głowy dla Pro 2. Regulacja jasności i głośności oraz przełączanie trybu wyświetlania nie są jeszcze obsługiwane. Cardboard VR Tryb Cardboard Obraz dla lewego i prawego oka do gogli VR na telefon. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 32d7c1615b..b29e753e2d 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2518,6 +2518,7 @@ A aguardar a ligação Ethernet por USB dos óculos. Este telemóvel pode não a disponibilizar às apps. A ligação aos óculos XREAL foi interrompida ou devolveu uma resposta não suportada. A tentar novamente… Suporte experimental para os 1S. Utilize o modo Follow e desative a estabilização no menu dos óculos. As direções de seguimento e os modos de ecrã ainda têm de ser testados no dispositivo. + Seguimento experimental dos movimentos da cabeça para Pro 2. O ajuste do brilho e do volume e a mudança do modo de ecrã ainda não são suportados. Cardboard VR Modo Cardboard Imagens para o olho esquerdo e o direito, para uns óculos de RV para telemóvel. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index f23e816ca4..79239e0c5a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -2518,6 +2518,7 @@ Aguardando a conexão Ethernet por USB dos óculos. Este celular pode não disponibilizá-la para os apps. A conexão com os óculos XREAL foi interrompida ou retornou uma resposta incompatível. Tentando novamente… Suporte experimental ao 1S. Use o modo Follow e desative a estabilização no menu dos óculos. As direções do rastreamento e os modos de exibição ainda precisam de testes no dispositivo. + Rastreamento experimental da cabeça para Pro 2. Os ajustes de brilho e volume e a troca do modo de exibição ainda não são compatíveis. Cardboard VR Modo Cardboard Imagens para o olho esquerdo e o direito, para um óculos de RV de celular. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 3307a935e3..c0736cfe0c 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -2532,6 +2532,7 @@ Se așteaptă conexiunea USB Ethernet a ochelarilor. Este posibil ca acest telefon să nu o expună aplicațiilor. Conexiunea XREAL a fost întreruptă sau a returnat un răspuns neacceptat. Se reîncearcă… Suport experimental pentru 1S. Folosește modul Follow și dezactivează stabilizarea din meniul ochelarilor. Direcțiile de urmărire și modurile de afișare trebuie încă testate pe dispozitiv. + Urmărire experimentală a mișcărilor capului pentru Pro 2. Reglarea luminozității și a volumului și schimbarea modului de afișare nu sunt încă acceptate. Cardboard VR Mod Cardboard Imagini pentru ochiul stâng și cel drept, pentru un vizor VR pentru telefon. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index b912603ebb..6e4145bb3a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -2553,6 +2553,7 @@ Ожидание подключения очков по USB Ethernet. Этот телефон может не предоставлять его приложениям. Подключение к XREAL прервано или получен неподдерживаемый ответ. Повторная попытка… Экспериментальная поддержка 1S. Включите режим Follow и отключите стабилизацию в меню очков. Направления отслеживания и режимы отображения ещё нужно проверить на устройстве. + Экспериментальное отслеживание движений головы для Pro 2. Настройка яркости и громкости и переключение режимов отображения пока не поддерживаются. Разработчик Издатель Дата выхода diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 2ff6e6084c..1da71dc1cb 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2507,6 +2507,7 @@ Väntar på glasögonens USB Ethernet-anslutning. Telefonen kanske inte gör den tillgänglig för appar. XREAL-anslutningen avbröts eller gav ett svar som inte stöds. Försöker igen… Experimentellt stöd för 1S. Använd Follow-läget och stäng av stabiliseringen i glasögonens meny. Spårningsriktningar och visningslägen behöver fortfarande testas på enheten. + Experimentell huvudspårning för Pro 2. Justering av ljusstyrka och volym samt byte av visningsläge stöds inte ännu. Cardboard VR Cardboard-läge Bilder för vänster och höger öga till ett VR-headset för mobilen. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 3019dc8e4d..75dc4f5726 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -2482,6 +2482,7 @@ กำลังรอการเชื่อมต่อ USB Ethernet ของแว่นตา โทรศัพท์นี้อาจไม่เปิดให้แอปเข้าถึงการเชื่อมต่อนี้ การเชื่อมต่อ XREAL ขาดหายหรือได้รับการตอบกลับที่ไม่รองรับ กำลังลองใหม่… รองรับ 1S แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา ทิศทางการติดตามและโหมดการแสดงผลยังต้องทดสอบกับอุปกรณ์จริง + การติดตามศีรษะแบบทดลองสำหรับ Pro 2 ยังไม่รองรับการปรับความสว่าง ระดับเสียง และการสลับโหมดการแสดงผล Cardboard VR โหมด Cardboard ภาพสำหรับตาซ้ายและตาขวาสำหรับแว่น VR ของโทรศัพท์ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index f7a6c9c247..4f2442fb05 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -2493,6 +2493,7 @@ Gözlüğün USB Ethernet bağlantısı bekleniyor. Bu telefon bu bağlantıyı uygulamalara açmıyor olabilir. XREAL bağlantısı kesildi veya desteklenmeyen bir yanıt döndü. Yeniden deneniyor… Deneysel 1S desteği. Gözlük menüsünde Follow modunu kullanın ve görüntü sabitlemeyi kapatın. Takip yönlerinin ve ekran modlarının hâlâ cihazda test edilmesi gerekiyor. + Pro 2 için deneysel baş takibi. Parlaklık ve ses düzeyi ayarı ile ekran modu değiştirme henüz desteklenmiyor. Cardboard VR Cardboard modu Telefon VR gözlüğü için sol ve sağ göz görüntüleri. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 30c30d0b1f..002514a82a 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -2557,6 +2557,7 @@ Очікування з’єднання USB Ethernet від окулярів. Цей телефон може не надавати його додаткам. З’єднання з XREAL перервалося або повернуло непідтримувану відповідь. Повторна спроба… Експериментальна підтримка 1S. Увімкніть режим Follow і вимкніть стабілізацію в меню окулярів. Напрямки відстеження й режими відображення ще потрібно перевірити на пристрої. + Експериментальне відстеження рухів голови для Pro 2. Налаштування яскравості й гучності та перемикання режимів відображення ще не підтримуються. Cardboard VR Режим Cardboard Зображення для лівого й правого ока для VR-окулярів під телефон. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 73e1d1395a..14e1ffd7e4 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -2482,6 +2482,7 @@ Đang chờ kết nối USB Ethernet của kính. Điện thoại này có thể không cho ứng dụng truy cập kết nối đó. Kết nối XREAL bị gián đoạn hoặc trả về phản hồi không được hỗ trợ. Đang thử lại… Hỗ trợ 1S thử nghiệm. Dùng chế độ Follow và tắt ổn định hình ảnh trong menu của kính. Hướng theo dõi và các chế độ hiển thị vẫn cần thử nghiệm trên thiết bị. + Theo dõi chuyển động đầu thử nghiệm cho Pro 2. Chưa hỗ trợ điều chỉnh độ sáng, âm lượng và chuyển chế độ hiển thị. Cardboard VR Chế độ Cardboard Hình cho mắt trái và mắt phải dành cho kính VR điện thoại. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 59737e3256..f95690ecf1 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -2485,6 +2485,7 @@ 正在等待眼镜的 USB Ethernet 连接。这部手机可能不向应用开放此连接。 XREAL 连接中断或返回了不受支持的响应。正在重试… 实验性 1S 支持。请在眼镜菜单中使用跟随模式并关闭防抖。追踪方向和显示模式仍需在设备上测试。 + Pro 2 实验性头部追踪。暂不支持亮度、音量调节和显示模式切换。 开发商 发行商 发行日期 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 3c75bce457..eab8f68379 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -2485,6 +2485,7 @@ 正在等候眼鏡的 USB Ethernet 連線。這部手機可能不會向應用程式開放此連線。 XREAL 連線中斷或傳回不支援的回應。正在重試… 實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在裝置上測試。 + Pro 2 實驗性頭部追蹤。暫不支援亮度、音量調整及顯示模式切換。 開發商 發行商 發行日期 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index c87e74a208..af4ac4b745 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -2485,6 +2485,7 @@ 正在等待眼鏡的 USB Ethernet 連線。這支手機可能不會向應用程式開放此連線。 XREAL 連線中斷或傳回不支援的回應。正在重試… 實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在實機上測試。 + Pro 2 實驗性頭部追蹤。尚不支援亮度、音量調整及顯示模式切換。 開發商 發行商 發行日期 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 6e95848c4f..2a41437dbb 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2639,6 +2639,7 @@ Waiting for the glasses’ USB Ethernet connection. This phone may not expose it to apps. The XREAL connection was interrupted or returned an unsupported response. Retrying… Experimental 1S support. Use Follow mode and disable stabilization in the glasses menu. Tracking directions and display modes still need device testing. + Experimental Pro 2 head tracking. Brightness, volume, and display switching are not supported yet. Picture position Top Bottom diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt index 47f6b7a7cc..f2b097e748 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesCallbacksTest.kt @@ -13,6 +13,11 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import org.robolectric.annotation.LooperMode +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit @RunWith(RobolectricTestRunner::class) @Config(sdk = [28], manifest = Config.NONE) @@ -232,4 +237,95 @@ class GlassesCallbacksTest { field("sink").set(null, null) } } + + @Test fun pro2CallbacksUseSharedPoseAndRejectThePreviousConnection() { + fun v2(gen: Long) = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType) + .apply { isAccessible = true }.invoke(Glasses, gen) as VitureV2Link.Listener + var delivered: FloatArray? = null + var timestamp = 0L + field("sink").set(null, Glasses.PoseSink { x, y, z, w, time -> + delivered = floatArrayOf(x, y, z, w) + timestamp = time + }) + try { + val q = floatArrayOf(0f, 0f, 0.6f, 0.8f) + v2(0).onPose(ByteArray(24), q, 100) + assertEquals(null, delivered) + v2(1).onPose(ByteArray(24), q, 101) + org.junit.Assert.assertArrayEquals(q, delivered, 0f) + assertEquals(101L, timestamp) + assertEquals(1L, field("imuPackets").getLong(null)) + v2(1).onValue(VitureProtocol.MSG_GET_DISPLAY, 0x32) + shadowOf(Looper.getMainLooper()).idle() + assertFalse(Glasses.state.value.sbs) + v2(1).onValue(VitureProtocol.MSG_GET_BRIGHTNESS, 8) + v2(1).onReady() + v2(1).onTracking(true) + v2(1).onLost() + generation(2) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(2, Glasses.state.value.brightness) + assertTrue(Glasses.state.value.connected) + assertFalse(Glasses.state.value.supportsScreen3dof) + assertFalse(Glasses.state.value.tracking) + } finally { field("sink").set(null, null) } + } + + @Test fun pro2DemandEndingBeforeTheFirstRestartPoseStillStopsTheStream() { + val writes = LinkedBlockingQueue() + val incoming = LinkedBlockingQueue() + val firstPose = CountDownLatch(1) + val firstRead = CountDownLatch(1) + val delegate = Glasses::class.java.getDeclaredMethod("v2Listener", Long::class.javaPrimitiveType) + .apply { isAccessible = true }.invoke(Glasses, 1L) as VitureV2Link.Listener + val listener = object : VitureV2Link.Listener by delegate { + override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) { + delegate.onPose(raw, q, timeNs) + firstPose.countDown() + } + } + val transport = object : VitureV2Link.Transport { + override fun write(packet: ByteArray): Boolean { writes += packet; return true } + override fun read(timeoutMs: Long): VitureV2Link.Received? { + firstRead.countDown() + return incoming.poll(timeoutMs, TimeUnit.MILLISECONDS) + } + override fun close() {} + } + fun expectStream(stream: Int) = org.junit.Assert.assertArrayEquals( + VitureV2Protocol.imuControl(stream), writes.poll(2, TimeUnit.SECONDS)) + fun updateImu() = Glasses::class.java.getDeclaredMethod("updateImu") + .apply { isAccessible = true }.invoke(Glasses) + val link = VitureV2Link(transport, listener) + field("link").set(null, link) + field("sink").set(null, null) + try { + expectStream(VitureV2Protocol.STREAM_POSE) + assertTrue("Bootstrap write did not complete", firstRead.await(2, TimeUnit.SECONDS)) + val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0).putInt(1).putFloat(1f).putFloat(0f).putFloat(0f).putFloat(0f).array() + incoming += VitureV2Link.Received(VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload), System.nanoTime()) + assertTrue(firstPose.await(2, TimeUnit.SECONDS)) + shadowOf(Looper.getMainLooper()).idle() + expectStream(VitureV2Protocol.STREAM_OFF) + assertTrue(Glasses.state.value.supportsScreen3dof) + assertFalse(Glasses.state.value.tracking) + + field("sink").set(null, Glasses.PoseSink { _, _, _, _, _ -> }) + updateImu() + assertFalse(Glasses.state.value.tracking) + field("sink").set(null, null) + updateImu() + expectStream(VitureV2Protocol.STREAM_POSE) + expectStream(VitureV2Protocol.STREAM_OFF) + assertFalse(link.trackingActive) + assertFalse(Glasses.state.value.tracking) + } finally { + generation(2) + link.close() + field("link").set(null, null) + field("sink").set(null, null) + shadowOf(Looper.getMainLooper()).idle() + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt index ae274cece1..225805dc65 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt @@ -155,6 +155,58 @@ class GlassesUsbTest { assertEquals(listOf(gt), manager.requests) } + @Test fun pro2RequestsPermissionWithoutTheSdkAndDoesNotClaimCompanionProducts() { + val pro2 = device(0x1301, name = "VITURE Luma Ultra") + manager.devices[pro2.deviceName] = pro2 + refresh(ask = true) + assertEquals("VITURE Pro 2", state.value.model) + assertTrue(state.value.controllable) + assertTrue(state.value.experimental) + assertFalse(state.value.hardwareControls) + assertFalse(state.value.supportsDisplayModeControl) + assertFalse(state.value.supportsScreen3dof) + assertFalse(state.value.supportsSpatial) + assertEquals(listOf(pro2), manager.requests) + assertEquals(null, Glasses.deviceModel(device(0x1301, 0x1234, "VITURE Pro 2"))) + assertEquals(null, Glasses.deviceModel(device(0x1102, name = "VITURE Pro 2"))) + assertEquals(null, Glasses.deviceModel(device(0x1302, name = "VITURE Pro 2"))) + val ultra = Glasses.deviceModel(device(0x1104)) as VitureProtocol.Model + assertEquals(VitureProtocol.Family.ULTRA, ultra.family) + assertTrue(ultra.needsSdk) + } + + @Test fun pro2PoseAvailabilityDoesNotEnableDisplayOrHardwareWrites() { + val pro2 = device(0x1301) + manager.devices[pro2.deviceName] = pro2 + manager.granted.add(pro2.deviceName) + val sent = mutableListOf() + field("linkDevice").set(null, pro2) + field("link").set(null, object : GlassesLink { + override val hasImu = true + override fun send(msgId: Int, payload: ByteArray): Boolean { sent += msgId; return true } + override fun close() {} + }) + try { + refresh() + assertTrue(state.value.canControl) + assertTrue(state.value.supportsScreen3dof) + assertFalse(state.value.can3d) + assertFalse(state.value.supportsDisplayModeControl) + assertFalse(state.value.hardwareControls) + assertEquals(0, state.value.brightnessMax) + assertEquals(0, state.value.volumeMax) + Glasses.sendMode(0x32) + Glasses.setBrightness(5) + Glasses.setVolume(5) + shadowOf(Looper.getMainLooper()).idle() + assertTrue(sent.isEmpty()) + } finally { + field("link").set(null, null) + field("linkDevice").set(null, null) + (field("handler").get(null) as Handler).removeCallbacksAndMessages(null) + } + } + @Test fun gtVendorRequestsPermissionAndRetainsMaxProductName() { val gt = device(0xaf50, 0x3941, "RayNeo GT MAX") manager.devices[gt.deviceName] = gt diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt index 565e8b6145..cefc2e9e42 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/VitureProtocolTest.kt @@ -130,6 +130,31 @@ class VitureProtocolTest { assertArrayEquals(floatArrayOf(0f, 0f, sin(half).toFloat(), cos(half).toFloat()), q, 1e-5f) } + @Test fun directPro2KeepsSdkOnlyFamiliesAndUnknownProductsIsolated() { + val direct = VitureProtocol.model(0x1301, "VITURE Luma Ultra")!! + assertEquals("VITURE Pro 2", direct.name) + assertEquals(VitureProtocol.Family.PRO2, direct.family) + assertFalse(direct.needsSdk) + assertFalse(direct.hardwareControls) + assertFalse(direct.supportsDisplayModeControl) + assertFalse(direct.hasSunblock) + assertEquals(0, direct.brightnessMax) + assertEquals(0, direct.volumeMax) + + for (pid in listOf(0x1101, 0x1104, 0x1201, 0x1211)) { + val model = VitureProtocol.model(pid, null)!! + assertTrue(model.needsSdk) + assertTrue(model.hardwareControls) + assertTrue(model.supportsDisplayModeControl) + } + assertNull(VitureProtocol.model(0x1102, "VITURE Pro 2")) + assertNull(VitureProtocol.model(0x1302, "VITURE Pro 2")) + val sdk = VitureProtocol.sdkModel("Pro 2")!! + assertTrue(sdk.needsSdk) + assertTrue(sdk.hardwareControls) + assertTrue(sdk.supportsDisplayModeControl) + } + @Test fun imuFallsBackToEuler() { val payload = ByteBuffer.allocate(12).putFloat(0f).putFloat(0f).putFloat(30f).array() val q = VitureProtocol.imuQuaternion(payload)!! diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2LinkTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2LinkTest.kt new file mode 100644 index 0000000000..475a0c4d44 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2LinkTest.kt @@ -0,0 +1,404 @@ +package com.droiddeck.launcher.glasses + +import com.droiddeck.launcher.gpu.HeadPose +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.IOException +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference +import kotlin.math.sqrt + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class VitureV2LinkTest { + private val transport = FakeTransport() + private val listener = RecordingListener() + private var link: VitureV2Link? = null + + @After fun close() { link?.close() } + + @Test fun writeAndAckDoNotBecomeReadyWithoutAValidPose() { + val link = start() + transport.feed(ack()) + transport.feed(pose(1).also { it[8] = (it[8].toInt() xor 1).toByte() }) + transport.feed(pose(2, floatArrayOf(0f, 0f, 0f, 0f))) + transport.feed(VitureV2Protocol.packet(VitureV2Protocol.EVENT_RAW, ByteArray(56))) + transport.flush() + assertFalse(link.ready) + assertFalse(link.hasImu) + assertFalse(link.trackingActive) + assertEquals(0, listener.readyCount.get()) + assertTrue(listener.poses.isEmpty()) + assertEquals(2L, link.badFrames) + + val receiptTime = System.nanoTime() + val valid = pose(3) + transport.feed(valid, receiptTime) + transport.flush() + assertTrue(link.ready) + assertTrue(link.hasImu) + assertTrue(link.trackingActive) + assertEquals(1, listener.readyCount.get()) + assertEquals(listOf(true), listener.tracking) + assertEquals(1, listener.poses.size) + assertEquals(receiptTime, listener.poses.single().timeNs) + assertArrayEquals(valid, listener.poses.single().raw) + } + + @Test fun duplicatesAndBackwardTicksAreDroppedWhileUnsignedWrapAdvances() { + start() + for (tick in listOf(0xFFFFFFFEL, 0xFFFFFFFEL, 0xFFFFFFFDL, 0L, 0L, 0xFFFFFFFFL, 1L)) { + transport.feed(pose(tick)) + } + transport.flush() + assertEquals(3, listener.poses.size) + assertEquals(1, listener.readyCount.get()) + assertEquals(listOf(true), listener.tracking) + assertEquals(0L, link!!.badFrames) + } + + @Test fun poseCollectedDuringBootstrapWriteDoesNotEstablishReadiness() { + transport.collectDuringNextWrite(pose(1)) + val link = start() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertTrue(listener.poses.isEmpty()) + + transport.feed(pose(2)) + transport.flush() + assertTrue(link.ready) + assertTrue(link.trackingActive) + assertEquals(1, listener.readyCount.get()) + assertEquals(1, listener.poses.size) + } + + @Test fun poseCollectedDuringResumeWriteDoesNotRestartTracking() { + val link = startReady(100) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.flush() + + transport.collectDuringNextWrite(pose(101)) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.flush() + assertFalse(link.trackingActive) + assertEquals(1, listener.poses.size) + + transport.feed(pose(102)) + transport.flush() + assertTrue(link.trackingActive) + assertEquals(2, listener.poses.size) + assertEquals(listOf(true, false, true), listener.tracking) + } + + @Test fun stoppingAndRestartingRequiresANewPoseAndRejectsQueuedOldSamples() { + val link = startReady(100) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) + assertFalse(link.trackingActive) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.feed(pose(101)) + transport.feed(ack()) + transport.flush() + assertEquals(1, listener.poses.size) + assertTrue(link.ready) + assertFalse(link.trackingActive) + + val beforeRestart = System.nanoTime() + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.feed(pose(102), beforeRestart) + transport.feed(ack()) + transport.flush() + assertFalse(link.trackingActive) + assertEquals(1, listener.poses.size) + + transport.feed(pose(0)) + transport.flush() + assertTrue(link.trackingActive) + assertEquals(2, listener.poses.size) + assertEquals(1, listener.readyCount.get()) + assertEquals(listOf(true, false, true), listener.tracking) + } + + @Test fun onReadyCanStopBootstrapBeforeTheFirstPoseIsForwarded() { + val link = start() + listener.whenReady = { assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) } + transport.feed(pose(1)) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.flush() + assertEquals(1, listener.readyCount.get()) + assertTrue(link.ready) + assertFalse(link.trackingActive) + assertTrue(listener.poses.isEmpty()) + assertEquals(listOf(true, false), listener.tracking) + } + + @Test fun rapidStopStartCannotAcceptThePreviousStreamsPendingRead() { + val link = startReady() + val held = transport.hold(pose(2)) + try { + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(0))) + assertTrue(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + } finally { + held.release.countDown() + } + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.flush() + assertFalse(link.trackingActive) + assertEquals(1, listener.poses.size) + assertEquals(listOf(true, false), listener.tracking) + + transport.feed(pose(3)) + transport.flush() + assertTrue(link.trackingActive) + assertEquals(2, listener.poses.size) + } + + @Test fun onReadyCanCloseWithoutForwardingAPoseOrReportingLoss() { + val link = start() + listener.whenReady = link::close + transport.feed(pose(1)) + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertTrue(listener.poses.isEmpty()) + assertEquals(0, listener.lostCount.get()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun unsupportedSettersNeverProduceWritesAndQueriesKeepGenericIds() { + val link = startReady() + for ((id, payload) in listOf( + VitureProtocol.MSG_BRIGHTNESS to byteArrayOf(3), + VitureProtocol.MSG_VOLUME to byteArrayOf(3), + VitureProtocol.MSG_DISPLAY to byteArrayOf(0x32), + VitureProtocol.MSG_FILM to byteArrayOf(1), + VitureProtocol.MSG_IMU_RATE to byteArrayOf(3), + VitureProtocol.MSG_IMU to byteArrayOf(2), + VitureProtocol.MSG_IMU to byteArrayOf(), + VitureProtocol.MSG_GET_VOLUME to byteArrayOf(1), + )) assertFalse("msgId=$id", link.send(id, payload)) + assertTrue(link.send(VitureProtocol.MSG_GET_IMU, byteArrayOf())) + transport.flush() + assertTrue(transport.writes.isEmpty()) + + val queries = listOf( + Triple(VitureProtocol.MSG_GET_BRIGHTNESS, VitureV2Protocol.MSG_GET_BRIGHTNESS, 3), + Triple(VitureProtocol.MSG_GET_VOLUME, VitureV2Protocol.MSG_GET_VOLUME, 5), + Triple(VitureProtocol.MSG_GET_DISPLAY, VitureV2Protocol.MSG_GET_DISPLAY, 0x31), + ) + for ((genericId, wireId, value) in queries) { + assertTrue(link.send(genericId, byteArrayOf())) + transport.expectWrite(VitureV2Protocol.packet(wireId)) + transport.feed(VitureV2Protocol.packet(wireId + VitureV2Protocol.RESPONSE_OFFSET, + byteArrayOf(0, value.toByte()))) + } + transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET, + byteArrayOf(1, 7))) + transport.feed(VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_VOLUME + VitureV2Protocol.RESPONSE_OFFSET, + byteArrayOf(0, 7, 8))) + transport.flush() + assertEquals(queries.map { it.first to it.third }, listener.values) + } + + @Test fun failureToWriteBootstrapClosesTransportAndReportsLoss() { + transport.failNextWrite.set(true) + val link = VitureV2Link(transport, listener).also { this.link = it } + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.hasImu) + assertFalse(link.trackingActive) + assertEquals(0, listener.readyCount.get()) + assertEquals(1, listener.lostCount.get()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun rejectedStreamAckClosesWithoutMarkingTrackingActive() { + val link = start() + transport.feed(ack(status = 7)) + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertEquals(1, listener.lostCount.get()) + assertEquals(0, listener.readyCount.get()) + assertTrue(listener.tracking.isEmpty()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun readFailureClearsTrackingAndClosesTransport() { + val link = startReady() + transport.disconnect() + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertEquals(listOf(true, false), listener.tracking) + assertEquals(1, listener.lostCount.get()) + assertFalse(link.send(VitureProtocol.MSG_IMU, byteArrayOf(1))) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + } + + @Test fun explicitCloseSendsOffOnceAndDoesNotReportLoss() { + val link = startReady() + link.close() + transport.awaitClosed() + assertFalse(link.ready) + assertFalse(link.trackingActive) + assertEquals(listOf(true, false), listener.tracking) + assertEquals(0, listener.lostCount.get()) + assertEquals(1, transport.closeCount.get()) + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + link.close() + assertFalse(link.send(VitureProtocol.MSG_GET_BRIGHTNESS, byteArrayOf())) + assertEquals(1, transport.closeCount.get()) + assertTrue(transport.writes.isEmpty()) + } + + @Test fun sharedPoseProducesTheSourceRightUpBackRelativeRotation() { + startReady() + val baseline = listener.poses.single().q + val reference = HeadPose.recenter(HeadPose.fromGlasses(baseline[0], baseline[1], baseline[2], baseline[3]), + centerView = true) + val half = sqrt(0.5f) + val rotations = listOf( + floatArrayOf(half, half, 0f, 0f), + floatArrayOf(half, 0f, half, 0f), + floatArrayOf(half, 0f, 0f, half), + floatArrayOf(0.5f, -0.5f, 0.5f, -0.5f), + ) + rotations.forEachIndexed { index, q -> transport.feed(pose(index + 2L, q)) } + transport.flush() + for ((source, event) in rotations.zip(listener.poses.drop(1))) { + val q = event.q + val relative = HeadPose.relative(reference, HeadPose.fromGlasses(q[0], q[1], q[2], q[3])) + assertArrayEquals(HeadPose.fromQuaternion(source[1], source[2], source[3], source[0]), relative, 1e-5f) + } + assertEquals(rotations.size + 1, listener.poses.size) + } + + private fun start(): VitureV2Link = VitureV2Link(transport, listener).also { + link = it + transport.expectWrite(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + transport.flush() + } + + private fun startReady(tick: Long = 1): VitureV2Link = start().also { + transport.feed(pose(tick)) + transport.flush() + assertTrue(it.ready) + } + + private fun ack(status: Int = 0) = VitureV2Protocol.packet( + VitureV2Protocol.MSG_IMU_CONTROL + VitureV2Protocol.RESPONSE_OFFSET, byteArrayOf(status.toByte())) + + private fun pose(tick: Long, wxyz: FloatArray = floatArrayOf(1f, 0f, 0f, 0f)): ByteArray { + val payload = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0x126).putInt(tick.toInt()) + wxyz.forEach(payload::putFloat) + return VitureV2Protocol.packet(VitureV2Protocol.EVENT_POSE, payload.array()) + } + + private data class PoseEvent(val raw: ByteArray, val q: FloatArray, val timeNs: Long) + + private class RecordingListener : VitureV2Link.Listener { + val readyCount = AtomicInteger() + val lostCount = AtomicInteger() + val tracking = CopyOnWriteArrayList() + val values = CopyOnWriteArrayList>() + val poses = CopyOnWriteArrayList() + @Volatile var whenReady: (() -> Unit)? = null + override fun onReady() { readyCount.incrementAndGet(); whenReady?.invoke() } + override fun onValue(msgId: Int, value: Int) { values += msgId to value } + override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) { poses += PoseEvent(raw.copyOf(), q.copyOf(), timeNs) } + override fun onTracking(active: Boolean) { tracking += active } + override fun onLost() { lostCount.incrementAndGet() } + } + + private sealed interface ReadStep { + data class Packet(val received: VitureV2Link.Received) : ReadStep + data class Barrier(val reached: CountDownLatch) : ReadStep + data class HeldPacket( + val received: VitureV2Link.Received, + val entered: CountDownLatch = CountDownLatch(1), + val release: CountDownLatch = CountDownLatch(1), + ) : ReadStep + data object Disconnected : ReadStep + } + + private class FakeTransport : VitureV2Link.Transport { + val writes = LinkedBlockingQueue(64) + val closeCount = AtomicInteger() + val failNextWrite = AtomicBoolean() + private val collectedDuringWrite = AtomicReference() + private val incoming = LinkedBlockingQueue(128) + private val closed = CountDownLatch(1) + + override fun write(packet: ByteArray): Boolean { + check(writes.offer(packet.copyOf())) + val success = !failNextWrite.getAndSet(false) + if (success) collectedDuringWrite.getAndSet(null)?.let { feed(it, System.nanoTime()) } + return success + } + + override fun read(timeoutMs: Long): VitureV2Link.Received? = when ( + val step = incoming.poll(timeoutMs, TimeUnit.MILLISECONDS) + ) { + is ReadStep.Packet -> step.received + is ReadStep.Barrier -> { step.reached.countDown(); null } + is ReadStep.HeldPacket -> { + step.entered.countDown() + check(step.release.await(2, TimeUnit.SECONDS)) + step.received + } + ReadStep.Disconnected -> throw IOException("Device disconnected") + null -> null + } + + override fun close() { closeCount.incrementAndGet(); closed.countDown() } + + fun feed(packet: ByteArray, timeNs: Long = System.nanoTime()) { + check(incoming.offer(ReadStep.Packet(VitureV2Link.Received(packet.copyOf(), timeNs)))) + } + + fun collectDuringNextWrite(packet: ByteArray) { + check(collectedDuringWrite.compareAndSet(null, packet.copyOf())) + } + + fun disconnect() { check(incoming.offer(ReadStep.Disconnected)) } + + fun hold(packet: ByteArray): ReadStep.HeldPacket { + val held = ReadStep.HeldPacket(VitureV2Link.Received(packet.copyOf(), System.nanoTime())) + check(incoming.offer(held)) + assertTrue("Worker did not enter the held read", held.entered.await(2, TimeUnit.SECONDS)) + return held + } + + fun expectWrite(expected: ByteArray) { + assertArrayEquals(expected, writes.poll(2, TimeUnit.SECONDS)) + } + + fun flush() { + val reached = CountDownLatch(1) + check(incoming.offer(ReadStep.Barrier(reached))) + assertTrue("Worker did not consume queued reports", reached.await(2, TimeUnit.SECONDS)) + } + + fun awaitClosed() { assertTrue("Transport did not close", closed.await(2, TimeUnit.SECONDS)) } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2ProtocolTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2ProtocolTest.kt new file mode 100644 index 0000000000..95f0cfb551 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/glasses/VitureV2ProtocolTest.kt @@ -0,0 +1,175 @@ +// Fixtures adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick. +// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/. +package com.droiddeck.launcher.glasses + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sqrt + +class VitureV2ProtocolTest { + @Test fun requestsMatchUpstreamWireExamples() { + assertArrayEquals(hex("10 00 01 03 02 00 03 00 01 02"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)) + assertArrayEquals(hex("10 00 01 03 02 00 04 00 02 02"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW)) + assertArrayEquals(hex("10 00 01 03 02 00 00 00 00 00"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) + assertArrayEquals(hex("10 00 22 31 00 00 00 00"), + VitureV2Protocol.packet(VitureV2Protocol.MSG_GET_BRIGHTNESS)) + } + + @Test fun requestBoundsAndStreamLimitsAreEnforced() { + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(-1) } + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0x10000) } + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.packet(0, ByteArray(57)) } + assertThrows(IllegalArgumentException::class.java) { VitureV2Protocol.imuControl(3) } + assertThrows(IllegalArgumentException::class.java) { + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE, VitureV2Protocol.Rate.HZ_500) + } + assertArrayEquals(hex("10 00 01 03 02 00 07 00 02 05"), + VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_RAW, VitureV2Protocol.Rate.HZ_1000)) + val maximum = VitureV2Protocol.packet(0xFFFF, ByteArray(56) { 0xFF.toByte() }) + assertEquals(64, maximum.size) + assertEquals(0x37C8, (maximum[6].toInt() and 0xFF) or ((maximum[7].toInt() and 0xFF) shl 8)) + assertNotNull(VitureV2Protocol.parse(maximum)) + } + + @Test fun brightnessReplyMatchesUpstreamAndKeepsFailureStatus() { + val frame = VitureV2Protocol.parse(hex("10 00 22 51 02 00 03 00 00 03"))!! + val reply = VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_BRIGHTNESS)!! + assertTrue(reply.success) + assertEquals(0, reply.status) + assertArrayEquals(byteArrayOf(3), reply.body) + assertNull(VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_GET_VOLUME)) + assertNull(VitureV2Protocol.reply(frame, -1)) + val failure = VitureV2Protocol.parse(hex("10 00 01 23 01 00 07 00 07"))!! + val failedReply = VitureV2Protocol.reply(failure, VitureV2Protocol.MSG_IMU_CONTROL)!! + assertFalse(failedReply.success) + assertEquals(7, failedReply.status) + assertTrue(failedReply.body.isEmpty()) + val noStatus = VitureV2Protocol.parse(hex("10 00 01 23 00 00 00 00"))!! + assertNull(VitureV2Protocol.reply(noStatus, VitureV2Protocol.MSG_IMU_CONTROL)) + } + + @Test fun validatesReceiveBoundsBeforeReadingHeader() { + val valid = hex("10 00 22 51 02 00 03 00 00 03") + for (size in listOf(-1, 0, 7, 9, 11, 65, Int.MAX_VALUE)) { + assertNull("size=$size", VitureV2Protocol.parse(valid, size)) + } + assertNull(VitureV2Protocol.parse(ByteArray(0))) + assertNull(VitureV2Protocol.parse(valid.copyOf(65))) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[0] = 0x11 })) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[1] = 1 })) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[6] = 0xFF.toByte() })) + assertNull(VitureV2Protocol.parse(valid.copyOf().also { it[9] = 4 })) + } + + @Test fun rejectsOversizedAndTruncatedDeclaredPayloads() { + val valid = hex("10 00 22 51 02 00 03 00 00 03") + assertNull(VitureV2Protocol.parse(valid.copyOf(9))) + val tooLong = valid.copyOf(64).also { it[4] = 57 } + assertNull(VitureV2Protocol.parse(tooLong)) + tooLong[4] = 0xFF.toByte() + tooLong[5] = 0xFF.toByte() + assertNull(VitureV2Protocol.parse(tooLong)) + val padded = valid.copyOf(64) + val parsed = VitureV2Protocol.parse(padded)!! + assertArrayEquals(byteArrayOf(0, 3), parsed.payload) + padded[9] = 8 + assertArrayEquals(byteArrayOf(0, 3), parsed.payload) + } + + @Test fun poseFixturePreservesDeviceCounterAndConvertsWxyzToNormalizedXyzw() { + val frame = VitureV2Protocol.parse(hex( + "10 00 08 73 18 00 9c 08 " + + "26 01 00 00 59 d6 21 00 dd e3 2b 3e 52 5d 7c 3f dd 45 9a 3b e8 27 52 3a" + ))!! + val pose = VitureV2Protocol.pose(frame)!! + assertEquals(0x0021D659L, pose.deviceTick) + assertEquals(0x126L, pose.unknown) + val expected = floatArrayOf(Float.fromBits(0x3F7C5D52), Float.fromBits(0x3B9A45DD), + Float.fromBits(0x3A5227E8), Float.fromBits(0x3E2BE3DD)) + val norm = sqrt(expected.sumOf { it.toDouble() * it }).toFloat() + assertArrayEquals(expected.map { it / norm }.toFloatArray(), pose.quaternion, 1e-7f) + assertEquals(1.0, pose.quaternion.sumOf { it.toDouble() * it }, 1e-6) + } + + @Test fun poseNormalizesSmallScaleErrorsWithoutChangingAxesOrCounter() { + val payload = posePayload(0.5f, -0.5f, 0.5f, -0.5f) + ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putInt(4, -1) + val pose = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload))!! + assertEquals(0xFFFFFFFFL, pose.deviceTick) + assertArrayEquals(floatArrayOf(-0.5f, 0.5f, -0.5f, 0.5f), pose.quaternion, 0f) + val scaled = VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(1.01f, 0f, 0f, 0f)))!! + assertArrayEquals(floatArrayOf(0f, 0f, 0f, 1f), scaled.quaternion, 1e-7f) + } + + @Test fun rejectsMalformedPoseAndInvalidQuaternions() { + val valid = posePayload(1f, 0f, 0f, 0f) + assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_RAW, valid))) + for (size in listOf(0, 23, 25, 56)) { + assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, valid.copyOf(size)))) + } + for (bad in listOf(0f, 0.5f, 2f, Float.MAX_VALUE, Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) { + assertNull("w=$bad", VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, posePayload(bad, 0f, 0f, 0f)))) + } + for (component in 1..3) { + val payload = valid.copyOf() + ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(8 + component * 4, Float.NaN) + assertNull(VitureV2Protocol.pose(event(VitureV2Protocol.EVENT_POSE, payload))) + } + } + + @Test fun rawReadsUnalignedFloatsAndPreservesUnknownBytes() { + val payload = rawPayload() + val frame = event(VitureV2Protocol.EVENT_RAW, payload) + val sample = VitureV2Protocol.raw(frame)!! + assertEquals(0xFFFFFFFEL, sample.deviceTick) + assertArrayEquals(floatArrayOf(1.5f, -2f, 0.25f), sample.gyroRadPerSec, 0f) + assertArrayEquals(floatArrayOf(0.0024f, -0.3221f, -0.9287f), sample.accelG, 0f) + assertArrayEquals(payload, sample.payload) + frame.payload.fill(0) + assertArrayEquals(payload, sample.payload) + } + + @Test fun rejectsMalformedRawAndNonfiniteMeasurementsButKeepsOpaqueTail() { + val payload = rawPayload() + assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_POSE, payload))) + for (size in listOf(0, 24, 33, 34, 55)) { + assertNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload.copyOf(size)))) + } + for (offset in listOf(10, 14, 18, 22, 26, 30)) { + for (bad in listOf(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)) { + val invalid = payload.copyOf() + ByteBuffer.wrap(invalid).order(ByteOrder.LITTLE_ENDIAN).putFloat(offset, bad) + assertNull("offset=$offset, value=$bad", VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, invalid))) + } + } + ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN).putFloat(46, Float.NaN) + assertNotNull(VitureV2Protocol.raw(event(VitureV2Protocol.EVENT_RAW, payload))) + } + + private fun event(msgId: Int, payload: ByteArray) = + VitureV2Protocol.parse(VitureV2Protocol.packet(msgId, payload))!! + + private fun posePayload(w: Float, x: Float, y: Float, z: Float) = + ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0x126).putInt(123).putFloat(w).putFloat(x).putFloat(y).putFloat(z).array() + + private fun rawPayload() = ByteBuffer.allocate(56).order(ByteOrder.LITTLE_ENDIAN) + .putInt(0x126).putInt(-2).putShort(187) + .putFloat(1.5f).putFloat(-2f).putFloat(0.25f) + .putFloat(0.0024f).putFloat(-0.3221f).putFloat(-0.9287f) + .putFloat(117.30f).putFloat(60.75f).putFloat(254.85f) + .put(byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).array() + + private fun hex(value: String) = value.split(' ').map { it.toInt(16).toByte() }.toByteArray() +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt index 701d9d1635..97d0496769 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlassesPanelTest.kt @@ -30,6 +30,21 @@ import org.robolectric.annotation.Config class GlassesPanelTest { @get:Rule val compose = createRobolectricComposeRule() + @Test fun trackingOnlyDeviceHidesDisplayWritesButKeepsHeadTracking() { + show(supportsDisplayModeControl = false) + compose.onNodeWithTag("setting-glasses-hz").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-resolution-two_d").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-3d").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-3dof").assertExists() + } + + @Test fun trackingOnlyDeviceHidesVrDisplayWrites() { + show(supportsDisplayModeControl = false, tab = GlassesTab.VR, steamVrRunning = true) + compose.onNodeWithTag("setting-glasses-resolution-vr").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-3d-hz").assertDoesNotExist() + compose.onNodeWithTag("setting-glasses-auto3d").assertDoesNotExist() + } + @Test fun flatResolutionMenuShowsPerEyeResolutionsBesideRefresh() { show() compose.onNodeWithTag("setting-glasses-hz").assertExists() @@ -397,6 +412,7 @@ class GlassesPanelTest { outputActive: Boolean = inSession, controlAvailable: Boolean = true, supportsScreen3dof: Boolean = true, + supportsDisplayModeControl: Boolean = true, supportsSpatial: Boolean = false, supports30Hz: Boolean = false, sbs90: Boolean = true, @@ -406,6 +422,7 @@ class GlassesPanelTest { onRecenter: (() -> Unit)? = {}, ) { val state = GlassesState(present = true, connected = controlAvailable, controllable = true, + supportsDisplayModeControl = supportsDisplayModeControl, displayId = Display.DEFAULT_DISPLAY + 1, width = if (stereo) 3840 else 1920, height = 1200, model = "VITURE Luma Ultra", sbs = stereo, sbs90 = sbs90, supportsScreen3dof = supportsScreen3dof, supports30Hz = supports30Hz, supportsSpatial = supportsSpatial, resolutions = listOf( diff --git a/docs/third-party/viture-v2/LICENSE b/docs/third-party/viture-v2/LICENSE new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/docs/third-party/viture-v2/LICENSE @@ -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. diff --git a/docs/third-party/viture-v2/README.md b/docs/third-party/viture-v2/README.md new file mode 100644 index 0000000000..253b3b46f0 --- /dev/null +++ b/docs/third-party/viture-v2/README.md @@ -0,0 +1,47 @@ +# VITURE protocol V2 attribution and scope + +The frame builder, parser, pose/raw layouts, and commands in +`VitureV2Protocol.kt` are adapted from [elasticjava/viture-v2](https://github.com/elasticjava/viture-v2) +at commit `ece8c30485f7d357fefa362ae74f3eabac9b3899` (MIT). +Copyright (c) 2026 Holger Bartnick. The full license is in `LICENSE` here. + +Sources used are upstream `PROTOCOL.md`, `src/lib.rs`, and `src/xr.rs`. +Upstream developed and measured its driver on VITURE Pro 2 XR `35ca:1301`. +Its research used captures of the proprietary SDK's USB traffic and logging; +the resulting implementation communicates directly over USB without that SDK. +This is an SDK-free implementation, not a claim of SDK-independent protocol research. +Our earlier local proprietary SDK trace was not used for this adaptation. + +The Android transport and application integration are implemented in Kotlin. +Building this path requires no Rust toolchain, vendor SDK, vendor binary, +developer account, private download, or repository secret. It uses Android's +USB host permission and `UsbRequest` APIs. To explicitly build without the +optional vendor driver, pass the Gradle property `-PvitureSdkDir=`. + +The application enables this experimental transport only for `35ca:1301`. +It requires valid pose samples before advertising 3DoF, uses the upstream +120 Hz pose mode, and treats the device timestamp as an uninterpreted counter. +Delivered timestamps use host `System.nanoTime()` receipt times. Bootstrap and +resume reject samples collected before the enable write completes. This host-time +cutoff does not establish when hardware produced a sample or purge device/kernel +buffers. The pose +basis conversion follows upstream's Y-up rendering convention. Hardware captures +verify changing, normalized poses during head motion; the relative rotation mapping +is unit-tested. The user also reported a successful Pro 2 game test; see the +validation notes for the scope of that report. + +Raw gyro and accelerometer packets can be decoded with their complete payload +preserved, but raw data is not fused or used by the application. Upstream reports +that enabling pose and raw streams together can ACK successfully while sending +no samples, so the application requests pose alone. Accelerometer values remain +in g; gyroscope values are in radians/second according to upstream. + +Brightness, volume, and display queries are supported. Setters, display switching, +6DoF, cameras, and hand tracking are not implemented by this path. Upstream's +README/protocol document and source disagree about setter coverage; this +adaptation does not use those setters without device validation. + +The standalone `tools/viture/viture-v2-probe` captures descriptors, commands, +replies, and pose/raw packets for device compatibility testing. Its provenance +and license are included beside its source. Pro 2 hardware checks and their +limitations are recorded in [VALIDATION.md](VALIDATION.md). diff --git a/docs/third-party/viture-v2/VALIDATION.md b/docs/third-party/viture-v2/VALIDATION.md new file mode 100644 index 0000000000..8bdbf2bff4 --- /dev/null +++ b/docs/third-party/viture-v2/VALIDATION.md @@ -0,0 +1,102 @@ +# Pro 2 direct USB validation + +These tests used a Samsung Galaxy Z Fold7 (SM-F976U), Android 17, with glasses +connected to the phone and wireless ADB used for installation and log collection. +The tested Pro 2 identifies as `35ca:1301`, with interface 0 exposing 64-byte +interrupt IN `0x81` and interrupt OUT `0x01`. Its firmware query returned +`30.0.00.001_20260714`. Results apply to this device and firmware. + +## Protocol probe + +The SDK-free Java probe in `tools/viture/viture-v2-probe` uses the attributed MIT +protocol. Every run queried firmware, enabled one stream, and sent stream-off at +completion. Each Pro 2 run received a successful firmware response and successful +start/stop acknowledgments. All three had zero malformed frames or samples. + +| Run | Valid samples | Measured rate | Observation | +| --- | ---: | ---: | --- | +| Pose, initial 15-second window | 1,762 | 120.67 Hz | Normalized quaternions; components changed | +| Pose, 30-second motion window | 3,571 | 120.63 Hz | User turned, looked up/down, and tilted; all components varied | +| Raw, separate 15-second window | 1,471 | 100.77 Hz | Finite gyro and accelerometer values; acceleration magnitude 0.882–1.129 g | + +Rates use host receipt time between the first and last samples. Query/setup time +reduces the sampling interval within each window. Although both stream requests +specified the upstream 120 Hz setting, the raw stream delivered approximately +101 Hz. Device counters are retained without assigning time units. Pose quaternion +norms were within 0.00000007 of one. These measurements do not establish accuracy, +drift, physical axis signs in a rendered scene, or 6DoF. + +Raw gyro/accelerometer decoding is available for future work. The application uses +only the device's pose stream. Combined pose/raw streaming is deliberately excluded +because upstream observed acknowledgments without subsequent samples in that mode. + +## Reproducing the checks + +Build the application with `-PvitureSdkDir=` to explicitly exclude the optional +vendor SDK. No vendor SDK download, vendor account, binary upload, or repository +secret is required for Pro 2. See each tool's README/provenance document for Android +SDK/JDK requirements, build commands, USB permission, and log collection. + +The protocol probe is separate from the application driver. The +`tools/viture/viture-v2-driver-check` harness packages the actual compiled +`VitureV2Link`, `VitureV2Protocol`, and `GlassesLink` classes and records their hashes. +It verifies readiness from poses and a stop/restart/stop/close sequence. + +On the same Pro 2, the final production-driver check **passed**: 1,446 poses in the +12-second resumed capture at 120.65 Hz, plus three bootstrap poses. It reported one +ready callback, two tracking-on and two tracking-off callbacks, zero errors and +zero bad frames. Both 500 ms pause windows delivered zero further poses. After +close, readiness and tracking were both false. The complete sequence took 13.03 s. +This validates the production USB driver; it does not by itself exercise the full +DroidDeck UI or an in-game head-tracking session. + +All 115 selected host-side tests passed. They cover wire framing/checksums, +bounded parsing, pose and raw layouts, +invalid samples, readiness without trusting ACKs, host-receipt cutoffs and +duplicate/backward device-tick rejection, +stop/restart behavior, transport failures, relative coordinate conversion, exact +USB model routing, consumer removal before the first restarted pose, and UI hiding +of unsupported hardware/display controls. + +## Full application check + +The complete debug APK built successfully with `:app:assembleDebug -PvitureSdkDir=` +and passed the repository's runtime-input verification and APK signature checks. +The APK contains the upstream MIT license and contains none of `libglasses.so`, +`libcarina_vio.so`, `libcloud_protocol.so`, or `libdroiddeck_viture.so`. + +Installed as `com.droiddeck.launcher.xr`, version 0.5.0, on the same phone, it +recognized Pro 2 and exposed `supportsScreen3dof=true` after USB permission and +valid bootstrap samples. A five-second sample through DroidDeck's own `glasses` +agent endpoint returned **595 poses (118.98 Hz including startup)**, with quaternion +norms within 0.00000006 of one and zero bad frames. Tracking was false before the +sample, true during it, and false afterward; the connection remained ready with +no control error. This checks application integration and consumer-driven streaming, +not an in-game rendering or SteamVR session. + +Tested APK SHA-256: +`f5a2484ea1708a143cb94a96e084188cb0d2b122154a2645d3127c66f6d04f21`. + +## User game test + +After installing the tested build, the user reported that the Pro 2 game test +passed. This adds user-reported in-game validation to the automated USB and +application checks above. The game title, test duration, and separate recentering +or SteamVR checks were not recorded. + +## Local capture fingerprints + +Full motion logs are local diagnostic artifacts, not required build inputs. These +SHA-256 values identify the captures behind the table above: + +| Capture | SHA-256 | +| --- | --- | +| `pro2-pose-initial.jsonl` | `beb09072d8d7ce2b1378c41992b88787e0b09f3ab3ea330a413b3ef9e9f5b762` | +| `pro2-pose-motion.jsonl` | `d72f3bbd6564061e9bf4e06fec7f4c6dcdbfabeee626a99a7bff279b416ccc61` | +| `pro2-raw.jsonl` | `944ac2fe30c7b1a817bc4d3281ead620000be32aa2dbd96e6b104cf4d7063091` | +| `pro2-production-driver-final.jsonl` | `0f1c1073963a7c3052bf8bdbcb39e3ef8ec332367ab1a3e39b622d36fcd06db2` | +| `pro2-full-app.json` | `3e48d9c3e8a230ec84e09bb51395b8566618406abb93937b8e2b69c40b4854c5` | + +The provenance in [README.md](README.md) applies to all these checks: the upstream +MIT project used SDK traffic captures in its research. This adaptation contains +and loads no vendor SDK; it does not claim independent protocol discovery. diff --git a/tools/viture/viture-v2-driver-check/.gitignore b/tools/viture/viture-v2-driver-check/.gitignore new file mode 100644 index 0000000000..89f9ac04aa --- /dev/null +++ b/tools/viture/viture-v2-driver-check/.gitignore @@ -0,0 +1 @@ +out/ diff --git a/tools/viture/viture-v2-driver-check/AndroidManifest.xml b/tools/viture/viture-v2-driver-check/AndroidManifest.xml new file mode 100644 index 0000000000..0f9d2d7686 --- /dev/null +++ b/tools/viture/viture-v2-driver-check/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/tools/viture/viture-v2-driver-check/README.md b/tools/viture/viture-v2-driver-check/README.md new file mode 100644 index 0000000000..6255aa2a27 --- /dev/null +++ b/tools/viture/viture-v2-driver-check/README.md @@ -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-.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. diff --git a/tools/viture/viture-v2-driver-check/assets/LICENSE.kotlin-Apache-2.0 b/tools/viture/viture-v2-driver-check/assets/LICENSE.kotlin-Apache-2.0 new file mode 100644 index 0000000000..f433b1a53f --- /dev/null +++ b/tools/viture/viture-v2-driver-check/assets/LICENSE.kotlin-Apache-2.0 @@ -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 diff --git a/tools/viture/viture-v2-driver-check/assets/LICENSE.viture-v2 b/tools/viture/viture-v2-driver-check/assets/LICENSE.viture-v2 new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/tools/viture/viture-v2-driver-check/assets/LICENSE.viture-v2 @@ -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. diff --git a/tools/viture/viture-v2-driver-check/assets/NOTICE.txt b/tools/viture/viture-v2-driver-check/assets/NOTICE.txt new file mode 100644 index 0000000000..11a2ce316c --- /dev/null +++ b/tools/viture/viture-v2-driver-check/assets/NOTICE.txt @@ -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. diff --git a/tools/viture/viture-v2-driver-check/build.ps1 b/tools/viture/viture-v2-driver-check/build.ps1 new file mode 100644 index 0000000000..7c34e150e9 --- /dev/null +++ b/tools/viture/viture-v2-driver-check/build.ps1 @@ -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 } diff --git a/tools/viture/viture-v2-driver-check/src/com/droiddeck/viturev2check/MainActivity.java b/tools/viture/viture-v2-driver-check/src/com/droiddeck/viturev2check/MainActivity.java new file mode 100644 index 0000000000..d5e639c6af --- /dev/null +++ b/tools/viture/viture-v2-driver-check/src/com/droiddeck/viturev2check/MainActivity.java @@ -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 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(); } + } +} diff --git a/tools/viture/viture-v2-probe/.gitignore b/tools/viture/viture-v2-probe/.gitignore new file mode 100644 index 0000000000..89f9ac04aa --- /dev/null +++ b/tools/viture/viture-v2-probe/.gitignore @@ -0,0 +1 @@ +out/ diff --git a/tools/viture/viture-v2-probe/AndroidManifest.xml b/tools/viture/viture-v2-probe/AndroidManifest.xml new file mode 100644 index 0000000000..422546fb9b --- /dev/null +++ b/tools/viture/viture-v2-probe/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/tools/viture/viture-v2-probe/LICENSE.upstream b/tools/viture/viture-v2-probe/LICENSE.upstream new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/tools/viture/viture-v2-probe/LICENSE.upstream @@ -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. diff --git a/tools/viture/viture-v2-probe/PROVENANCE.md b/tools/viture/viture-v2-probe/PROVENANCE.md new file mode 100644 index 0000000000..217439944a --- /dev/null +++ b/tools/viture/viture-v2-probe/PROVENANCE.md @@ -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--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/` 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. diff --git a/tools/viture/viture-v2-probe/assets/LICENSE.upstream b/tools/viture/viture-v2-probe/assets/LICENSE.upstream new file mode 100644 index 0000000000..9c1d9de29a --- /dev/null +++ b/tools/viture/viture-v2-probe/assets/LICENSE.upstream @@ -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. diff --git a/tools/viture/viture-v2-probe/build.ps1 b/tools/viture/viture-v2-probe/build.ps1 new file mode 100644 index 0000000000..d3fa85e05e --- /dev/null +++ b/tools/viture/viture-v2-probe/build.ps1 @@ -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 +} diff --git a/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/MainActivity.java b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/MainActivity.java new file mode 100644 index 0000000000..4bcf40ccd8 --- /dev/null +++ b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/MainActivity.java @@ -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 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 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 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 inputs = new ArrayList<>(); + final List 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(); } + } +} diff --git a/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/Protocol.java b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/Protocol.java new file mode 100644 index 0000000000..852ae858d0 --- /dev/null +++ b/tools/viture/viture-v2-probe/src/com/droiddeck/viturev2probe/Protocol.java @@ -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; } + } +} diff --git a/tools/viture/viture-v2-probe/tests/com/droiddeck/viturev2probe/ProtocolTest.java b/tools/viture/viture-v2-probe/tests/com/droiddeck/viturev2probe/ProtocolTest.java new file mode 100644 index 0000000000..117a1687d8 --- /dev/null +++ b/tools/viture/viture-v2-probe/tests/com/droiddeck/viturev2probe/ProtocolTest.java @@ -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; + } +}