mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-24 15:26:04 +00:00
Add VITURE XR controls, head tracking, and SteamVR (#732)
* Add VITURE glasses support: hardware control, 3D, head tracking Glasses get their own controller over the MCU (permission, 120 Hz default, brightness, volume, sunblock, 2D/3D) and the game moves onto them when plugged in. The IMU drives Cardboard head tracking and the SteamVR driver. 3D falls back to one eye's view on phones that can't send the 3840x1080 signal. Options open from a glasses button in game and on the Steam page. * Drop the glasses settings like Steam's: Play-style button, Settings lip, tabs * Hang the glasses Settings lip over the top of the button * Space glasses MCU commands so the IMU rate sticks, fit fixed resolutions to the glasses * Keep Steam alive with SteamVR registered, run SteamVR at the glasses' rate, keep the glasses lip on top * Fit VR games on the glasses: full view, seated origin at the head, pad hands reach with the d-pad * Let the pad hands reach a metre out so buttons with deep colliders press * Show every VR frame in order at 120 fps: wait for SteamVR's GPU work, present only finished copies, skip the grace on idle shared counters * Glasses: SteamVR starts and stops with them, closer view with a field of view setting, Recenter on the pad * Glasses: SteamVR field of view defaults to 90° * VR pad hands: sticks move and aim the hands, left stick click switches the sticks to the game, d-pad pulls a held hand * Glasses: Play SteamVR beside the glasses button instead of starting SteamVR with them, pad hands drawn as Index controllers and off while other VR controllers are connected, glasses sheet tabs sized like Steam's * Track glasses mode, refresh-aware glasses window, align Play SteamVR with Play Steam * Fix 3D on the glasses: full-res SteamVR presenter, revert VR 3D at session end, coalesce vsync ticks, no session restart after end * Address review: glasses output after installs and session end, VR revert retry, display fallback, presenter swapchain retry, agent hex checks, drawer bumpers, glasses translations, docs * Harden VITURE stereo negotiation and output refresh tracking * Localize stereo recovery feedback and record Astra reconnect tests * Improve test failure diagnostics and refresh Astra firmware findings * Handle VITURE docks separately and reject truncated USB frames * Glasses: remember a 3D fallback per model, docks as display only, VR timing fixes - A 3D attempt that ends at the 640x480 fallback is remembered for that glasses model, so Play SteamVR no longer blacks out the glasses after every restart; Retry clears it and "3D for VR games" stays reachable - A VITURE Mobile Dock on its own no longer counts as glasses; through a dock Play SteamVR is hidden and the sheet shows the output and why there is no control - HDR is probed on the glasses when the session starts there - Glasses frames with a mismatched checksum are marked in the status frame log - SteamVR layer and driver vblank counters stay monotonic across refresh changes; one-eye render scale applies from activation and on mono/3D switches - Compositor binds announce the refresh clients were last told; the presenter retries a failed first swapchain - Dead strings and helpers removed; docs updated * Glasses: drop USB frames with a bad checksum * Glasses: count frames dropped for a bad checksum * Feat/viture xr (#907) * Add RayNeo Air and GT support to the XR glasses pipeline * Add RayNeo Air and GT support to the XR glasses pipeline * Checkpoint glasses tracking, calibration, and SteamVR launch integration * Checkpoint glasses tracking, calibration, and SteamVR launch integration * Add XREAL 1S support and correct GT and Pro 2 tracking * Add XREAL 1S support and correct GT and Pro 2 tracking * Fix mirrored glasses tracking and recover SteamVR after device loss * Fix mirrored glasses tracking and recover SteamVR after device loss * Document confirmed XREAL 1S brightness control * Document confirmed XREAL 1S brightness control * Fix SteamVR glasses defaults and rendering controls * Fix SteamVR glasses defaults and rendering controls * chore: keep only the 3 newest session log folders (#852) * chore: add agent comment rules (#748) Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> * Fix SteamVR polling, VITURE checksums, and fence tracking Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter. Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage. * Fix SteamVR polling, VITURE checksums, and fence tracking Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter. Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage. * fix: wireless ADB page names the child-process switch the way Android shows it (#848) * l10n: refresh stale and untranslated strings in es, fr, ko, ru (#850) * l10n: refresh stale and untranslated strings in es, fr, ko, ru - mode_added_art_hint: now mentions Steam then SteamGridDB (all four locales). - wincomp_needs_installer / wincomp_installers_note: es and ko still described the old "coming soon" behaviour; align with the current English text. - summary_remove_game: was still English in all four locales. Machine-assisted translation; native-speaker review is welcome. * l10n(es): say registro, not grabación, for the missing installer record --------- Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com> * fix: a failed cloud save recovery no longer ends the app (#846) The cloud-recovery thread started at every app start had nothing to catch an error, so one went to CrashHandler, which halts the process with status 2. In unit tests the thread can outlive the test that started it, fail on the torn-down preferences, and take the whole test run down. The error is now logged and the thread ends. Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com> * fix: an interrupted Linux runtime download resumes instead of starting again (#847) * fix: an interrupted Linux runtime download resumes instead of starting again installOnce() asked the downloader to resume but always deleted the archive in its finally block, so the next attempt began at zero. The archive is now named after the release version and checksum, a failed download keeps what it fetched, and archives of other releases (and the old fixed name) are removed. A checksum or extraction failure still deletes the file. * test: Downloader resumes a cut-off download from the bytes it kept Starts a socket server that promises the whole file, hangs up part way and then answers a Range request, and checks that the second downloadFile call resumes with the right offset and ends with identical bytes. * fix: a resumed download discards a 206 that does not start where the kept bytes end Downloader appended every 206 response to the partial file without looking at Content-Range. A server or proxy that answers a Range request with a different offset would leave a corrupt file. Check that the range starts at the kept length; otherwise delete the partial file and start again without a Range header. Adds a test with a server that answers the Range request from offset 0. --------- Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com> * l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings (#849) * l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings Adds the strings values-de, values-it and values-pt were missing (14 each) and the six that values-fr, values-es and values-ru were missing. Machine-assisted drafts that follow each file's existing register and terms; native review is welcome. * l10n: correct missing active swap translations --------- Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com> Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com> * fix: droiddeckctl reaches variant-package builds (recover #842) (#854) fix: droiddeckctl reaches builds shipped under a variant package The provider authority and the start Activity's component were fixed to com.droiddeck.launcher, so droiddeckctl could not talk to the antutu, ludashi or pubg builds from tools/release/variants.txt. DROIDDECK_PACKAGE now picks the package; the Activity's class name stays the same in every variant. Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com> * feat: droiddeckctl reports on-screen pacing (recover #843) (#855) feat: droiddeckctl pacing reports the frames that reached the screen Reads SurfaceFlinger's timestats for the game's layer (or the session's SurfaceView) over a capture: frames on screen, fps on screen, the present-to-present histogram and how many intervals were off the usual cadence. Records split by a refresh-rate change are summed. A game's own fps counter counts frames handed over, so it can't show dropped or doubled frames. Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com> * fix: Steam can restart more than twice in a session (#754) * fix: Steam can restart more than twice in a session Every exit 42 counted toward the cap that stops an update which will not install, and the count was never cleared, so the third restart of a session ended it however far apart they were. A client that ran for a minute before asking is not that loop: the count starts again. * fix: measure the client's run time as it exits The time spent collecting logs and checking FEX after the client exits counted toward its run, so a slow cleanup could make a quick exit 42 look like a long one and clear the count. --------- Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com> Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> * fix: the front end keeps its page when the Fold is folded or unfolded (#832) * fix: the front end keeps its page when the Fold is folded or unfolded MainActivity, FileManagerActivity, FilePickerActivity and StoreLoginActivity did not declare the screen-size configuration changes, so folding or unfolding a foldable recreated them and dropped their in-memory state. They now handle orientation, screenSize, screenLayout, smallestScreenSize and density themselves, like SessionActivity already does. uiMode is left out on purpose. * fix: store login keeps rebuilding its toolbar when the display density changes StoreLoginActivity builds its toolbar in code with dp-to-pixel values taken at creation time and has no onConfigurationChanged. It no longer declares density in configChanges, so a density change recreates it as before this PR. Size and layout changes are still handled in place. --------- Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com> * Release pointer buttons without replaying stale motion (#803) * Fix cursor warping on native touch down * Preserve input cleanup without replaying stale pointer motion --------- Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com> * l10n: translate the strings added since #284 into zh-CN, zh-HK, zh-TW and ja (#539) * l10n: translate the 184 strings added since #284 (zh-CN/HK/TW, ja) The stores, cloud saves, Windows components, Steam touch, desktop removal and background-downloads strings landed after #284's translation snapshot, so every one of them fell back to English. Translate all 184 into Simplified Chinese, Traditional Chinese (Taiwan and Hong Kong) and Japanese, keeping each locale file's own vocabulary (工作階段/會話, 解除安裝/卸載, 元件/組件, 設定). Also fix four Hong Kong strings that kept the simplified 着色器. * l10n(zh): fix stale and ambiguous strings found in review Severe: summary_remove_game was untranslated English in all three files; mode_added_art_hint, wincomp_installers_note and wincomp_needs_installer still described the pre-#480/#492 English. Also: distinguish the Setup wizard from Android system settings in zh-HK/zh-TW (初始設定 / 系統設定 / Android 設定), unify library as 收藏庫, component as 組件 in zh-HK, session as 會話 in zh-HK, account as 帳戶 in zh-HK, Trending as 趋势/趨勢, Forget as 清除, reword the re-applied-at-launch, action-failed and already-in-Games strings, and play as 執行/開啟遊戲 in zh-TW/zh-HK. * l10n(ja): fix stale and ambiguous strings found in review --------- Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com> Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com> * Rebuild and verify Windows VR runtime components * Rebuild and verify Windows VR runtime components * Add top, bottom, and centered picture positions for Steam sessions (#871) * fix: dependency scan ignores folders above the game folder (#859) * DroidDeck-Proton: get releases from the Droid-Deck org repo DroidDeck-Proton is now built and released on Droid-Deck/DroidDeck-Proton (11-9.1 is Latest there), so the Components page, the update check and the guest installer read releases from the org repo instead of The412Banner's. * feat: low-latency controller and touch toggles in the session drawer (#808) * fix: SteamGridDB lookups no longer stick as "no match" after a failure; add a search to the art chooser (#876) * feat: Steam home wall fills from the signed-in library instead of store picks (#878) * test: cover GPU family and support classification (#880) * Fix local builds on Linux failing after the first Comet build (#866) * feat: sort the store library and installed tabs, and switch between card and list views (#798) * feat: three-finger tap toggles Steam's on-screen keyboard in game mode (#782) * fix: keep Quest-patched Turnip as the auto default (#853) * Fix deploy_local.sh and droiddeckctl not finding a phone connected over wireless debugging (#864) * fix: keep proot sessions alive when the kernel loses fork events (#457) * fix(quest): correct desktop and Steam display corruption across sessions (#733) fix(quest): stabilize desktop and Steam layer presentation Keep Quest SDR scenes and the black backdrop off the Android Vulkan swapchain regardless of session order or HDR preferences. Only report the first frame after client content is submitted. Add backdrop lifecycle and first-frame regression coverage. Record the user's successful Quest 3 Test 2 result. Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com> * fix: keep SteamVR syscall hooks and report Steam crashes (#905) * fix: preserve SteamVR syscall hooks * fix: report Steam crashes through gamescope * fix: honor glasses pacing and resolution in SteamVR launches --------- Co-authored-by: connor g <connorsspam1992@gmail.com> Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com> Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com> Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com> Co-authored-by: Kirk <kirtoy.junsay@gmail.com> Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com> Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com> Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com> Co-authored-by: asdf17128 <asdf17128@gmail.com> Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com> Co-authored-by: Dantalian <wsu091227@qq.com> Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com> Co-authored-by: The412Banner <the412banner@users.noreply.github.com> Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com> Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com> Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com> Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com> Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com> Co-authored-by: Jagger15 <jagger2333@live.com> * Glasses: keep a pending 2D restore and the SteamVR recovery offer, show Play SteamVR only with a picture * Translate the glasses calibration, XREAL and SteamVR recovery strings * SteamVR recovery: give a finished teardown time to collect logs before restarting * Credit the projects the XR glasses support builds on * Joy-Cons: SteamVR hands from their gyro while SteamVR runs, one combined pad otherwise * Headsets: settings badge on Play SteamVR instead of a top-right button, both shown only once connected * Hand tracking: camera-tracked Joy-Cons and bare hands in SteamVR, drawn as white gloves - Joy-Con movement from the accelerometer (report reordering, per-Joy-Con calibration, zero-velocity updates) - MediaPipe pose and hand landmarks from the device camera, placement check, per-hand Kalman filter with the Joy-Con - No controller connected: bare camera hands with Quest-style gestures, 1€ filtered, rendered as a white glove model built from a distance field - SteamVR safe mode cleared before each start so one crash no longer blocks the driver --------- Co-authored-by: MaxsTechReview <6025299+maxjivi05@users.noreply.github.com> Co-authored-by: informalTechCode <informaltechyt@gmail.com> Co-authored-by: connor g <connorsspam1992@gmail.com> Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com> Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com> Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com> Co-authored-by: Kirk <kirtoy.junsay@gmail.com> Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com> Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com> Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com> Co-authored-by: asdf17128 <asdf17128@gmail.com> Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com> Co-authored-by: Dantalian <wsu091227@qq.com> Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com> Co-authored-by: The412Banner <the412banner@users.noreply.github.com> Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com> Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com> Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com> Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com> Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com> Co-authored-by: Jagger15 <jagger2333@live.com>
This commit is contained in:
221 files changed
+24369
-491
No files matched your search
@@ -0,0 +1,862 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.sin
|
||||
import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
|
||||
data class GlassesState(
|
||||
val present: Boolean = false,
|
||||
val model: String = "VITURE",
|
||||
val controllable: Boolean = false,
|
||||
val permission: Glasses.Permission = Glasses.Permission.NONE,
|
||||
val connected: Boolean = false,
|
||||
val displayId: Int = Display.INVALID_DISPLAY,
|
||||
val width: Int = 0,
|
||||
val height: Int = 0,
|
||||
val hz: Float = 0f,
|
||||
val sbs: Boolean = false,
|
||||
val switching3d: Boolean = false,
|
||||
val brightness: Int = -1,
|
||||
val volume: Int = -1,
|
||||
val brightnessMax: Int = 8,
|
||||
val volumeMax: Int = 8,
|
||||
val sunblock: Boolean = false,
|
||||
val hardwareControls: Boolean = true,
|
||||
val hasSunblock: Boolean = true,
|
||||
val controlError: String? = null,
|
||||
val tracking: Boolean = false,
|
||||
val diagonalFovDeg: Float = 46f,
|
||||
val noSignal: Boolean = false,
|
||||
val sbsSupport: Int = SBS_UNKNOWN,
|
||||
val sbs90: Boolean = false,
|
||||
val experimental: Boolean = false,
|
||||
) {
|
||||
val hasDisplay: Boolean get() = displayId != Display.INVALID_DISPLAY
|
||||
val usable: Boolean get() = hasDisplay && !noSignal
|
||||
val canControl: Boolean get() = connected && controllable
|
||||
val can3d: Boolean get() = canControl && !noSignal && sbsSupport != SBS_FAILS
|
||||
val verticalFovDeg: Float get() {
|
||||
val half = Math.toRadians(diagonalFovDeg / 2.0)
|
||||
val aspect = if (width > 0 && height > 0)
|
||||
width.toDouble() / (if (sbs) 2 else 1) / height else 16.0 / 9.0
|
||||
val v = kotlin.math.atan(kotlin.math.tan(half) / kotlin.math.sqrt(1 + aspect * aspect))
|
||||
return Math.toDegrees(2 * v).toFloat()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SBS_UNKNOWN = 0
|
||||
const val SBS_WORKS = 1
|
||||
const val SBS_FAILS = -1
|
||||
}
|
||||
}
|
||||
|
||||
data class GlassesSettings(
|
||||
val refreshHz: Int = 120,
|
||||
val sbsHz: Int = 60,
|
||||
val sunblock: Boolean? = null,
|
||||
val gameOnGlasses: Boolean = true,
|
||||
val headTracking: Boolean = true,
|
||||
val auto3d: Boolean = false,
|
||||
val picture3d: Int = PICTURE_AUTO,
|
||||
val screenWidthDm: Int = 20,
|
||||
val screenDistanceDm: Int = 30,
|
||||
val vrFovDeg: Int = VR_FOV_DEFAULT,
|
||||
) {
|
||||
companion object {
|
||||
const val VR_FOV_MIN = 24
|
||||
const val VR_FOV_MAX = 90
|
||||
const val VR_FOV_DEFAULT = 90
|
||||
const val PICTURE_AUTO = 0
|
||||
const val PICTURE_SCREEN = 1
|
||||
const val PICTURE_SBS = 2
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
object Glasses {
|
||||
enum class Permission { NONE, ASKING, DENIED, GRANTED }
|
||||
|
||||
fun interface PoseSink {
|
||||
fun onPose(x: Float, y: Float, z: Float, w: Float, timeNs: Long)
|
||||
}
|
||||
|
||||
private const val TAG = "Glasses"
|
||||
private const val ACTION_PERMISSION = "com.droiddeck.launcher.glasses.USB_PERMISSION"
|
||||
private const val PREFS = "glasses"
|
||||
private const val KEY_SBS_FAILED = "sbsFailed"
|
||||
private const val SBS_CONFIRM_MS = 20_000L
|
||||
|
||||
private val _state = MutableStateFlow(GlassesState())
|
||||
val state: StateFlow<GlassesState> = _state.asStateFlow()
|
||||
private val _settings = MutableStateFlow(GlassesSettings())
|
||||
val settings: StateFlow<GlassesSettings> = _settings.asStateFlow()
|
||||
private val _calibration = MutableStateFlow(GlassesCalibrationState())
|
||||
val calibration: StateFlow<GlassesCalibrationState> = _calibration.asStateFlow()
|
||||
private lateinit var calibrationStore: RayNeoCalibrationStore
|
||||
private var calibrationKey: String? = null
|
||||
private var calibrationRevision = 0L
|
||||
|
||||
private lateinit var app: Context
|
||||
private lateinit var handler: Handler
|
||||
private lateinit var usb: UsbManager
|
||||
private lateinit var displays: DisplayManager
|
||||
@Volatile private var link: GlassesLink? = null
|
||||
@Volatile private var linkGeneration = 0L
|
||||
private var linkDevice: UsbDevice? = null
|
||||
private var model: GlassesModel? = null
|
||||
private var asked = false
|
||||
private var lastModeSentAt = 0L
|
||||
private val modeState = GlassesModeState(SBS_CONFIRM_MS)
|
||||
private val confirmMode = Runnable { refresh() }
|
||||
private var glassesMode = 0
|
||||
private var autoModeSent = false
|
||||
|
||||
@Volatile private var sink: PoseSink? = null
|
||||
@Volatile private var probe: ((ByteArray?, FloatArray?) -> Unit)? = null
|
||||
@Volatile private var latest: FloatArray? = null
|
||||
@Volatile private var imuPackets = 0L
|
||||
private val simulating = java.util.concurrent.atomic.AtomicReference<Thread?>(null)
|
||||
private val frames = ArrayDeque<String>()
|
||||
|
||||
fun init(context: Context) {
|
||||
if (::handler.isInitialized) return
|
||||
app = context.applicationContext
|
||||
usb = app.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
displays = app.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
|
||||
_settings.value = load()
|
||||
calibrationStore = RayNeoCalibrationStore(app.getSharedPreferences(PREFS, Context.MODE_PRIVATE))
|
||||
handler = Handler(HandlerThread("droiddeck-glasses").apply { start() }.looper)
|
||||
handler.post {
|
||||
val filter = IntentFilter(ACTION_PERMISSION).apply {
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33) app.registerReceiver(receiver, filter, null, handler, Context.RECEIVER_NOT_EXPORTED)
|
||||
else app.registerReceiver(receiver, filter, null, handler)
|
||||
displays.registerDisplayListener(displayListener, handler)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
fun rescan() = post { refresh() }
|
||||
|
||||
fun startCalibration() = post {
|
||||
val l = link as? RayNeoLink ?: return@post
|
||||
if (!l.ready || _calibration.value.running || simulating.get() != null) return@post
|
||||
_calibration.value = _calibration.value.copy(phase = CalibrationPhase.SETTLING, progress = 0)
|
||||
l.startCalibration(++calibrationRevision)
|
||||
updateImu()
|
||||
}
|
||||
|
||||
fun cancelCalibration() = post {
|
||||
(link as? RayNeoLink)?.cancelCalibration(++calibrationRevision, calibrationKey?.let(calibrationStore::load))
|
||||
_calibration.value = _calibration.value.copy(phase = CalibrationPhase.IDLE, progress = 0)
|
||||
updateImu()
|
||||
}
|
||||
|
||||
fun resetCalibration() = post {
|
||||
(link as? RayNeoLink)?.resetCalibration(++calibrationRevision)
|
||||
calibrationKey?.let { calibrationStore.save(it, null) }
|
||||
_calibration.value = _calibration.value.copy(saved = false, phase = CalibrationPhase.IDLE, progress = 0)
|
||||
updateImu()
|
||||
}
|
||||
|
||||
fun query() = post {
|
||||
val l = link ?: return@post
|
||||
listOf(VitureProtocol.MSG_GET_DISPLAY, VitureProtocol.MSG_GET_BRIGHTNESS, VitureProtocol.MSG_GET_VOLUME, VitureProtocol.MSG_GET_IMU).forEachIndexed { i, msg ->
|
||||
handler.postDelayed({ if (link === l) l.send(msg) }, VitureLink.COMMAND_GAP_MS * i)
|
||||
}
|
||||
}
|
||||
|
||||
fun sendMode(mode: Int) = post {
|
||||
if (!_state.value.canControl) return@post
|
||||
if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) lastModeSentAt = SystemClock.uptimeMillis()
|
||||
}
|
||||
|
||||
fun requestControl() = post {
|
||||
asked = false
|
||||
refresh(ask = true)
|
||||
}
|
||||
|
||||
fun setRefreshHz(hz: Int) = post {
|
||||
update { it.copy(refreshHz = hz.coerceIn(60, 120)) }
|
||||
if (!_state.value.sbs) applyMode(force = true)
|
||||
}
|
||||
|
||||
fun setSbsHz(hz: Int) = post {
|
||||
update { it.copy(sbsHz = if (hz >= 90) 90 else 60) }
|
||||
if (_state.value.sbs && _state.value.can3d) sendMode(true)
|
||||
}
|
||||
|
||||
fun set3d(on: Boolean) = post {
|
||||
val s = _state.value
|
||||
if (!s.canControl || (on && s.noSignal)) return@post
|
||||
modeState.manual()
|
||||
if (on) {
|
||||
markSbsFailed(linkDevice?.productId, false)
|
||||
rememberSbs(GlassesState.SBS_UNKNOWN)
|
||||
}
|
||||
sendMode(on)
|
||||
}
|
||||
|
||||
fun set3dForVr(on: Boolean) = post {
|
||||
val s = _state.value
|
||||
if (on) {
|
||||
if (!s.can3d || s.sbs || modeState.pendingStereo) return@post
|
||||
if (sendMode(true)) modeState.startVr()
|
||||
} else if (modeState.stopVr() && s.canControl) {
|
||||
sendMode(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun setBrightness(level: Int) = post {
|
||||
val s = _state.value
|
||||
if (!s.canControl || s.brightnessMax == 0) return@post
|
||||
val v = level.coerceIn(0, s.brightnessMax)
|
||||
if (link?.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(v.toByte(), 0)) == true && link !is XrealLink)
|
||||
publish { it.copy(brightness = v) }
|
||||
}
|
||||
|
||||
fun setVolume(level: Int) = post {
|
||||
val s = _state.value
|
||||
if (!s.canControl || s.volumeMax == 0) return@post
|
||||
val v = level.coerceIn(0, s.volumeMax)
|
||||
if (link?.send(VitureProtocol.MSG_VOLUME, byteArrayOf(v.toByte(), 0)) == true) publish { it.copy(volume = v) }
|
||||
}
|
||||
|
||||
fun setSunblock(on: Boolean) = post {
|
||||
update { it.copy(sunblock = on) }
|
||||
sendFilm(on)
|
||||
}
|
||||
|
||||
fun setSbsSupport(support: Int) = post {
|
||||
val s = support.coerceIn(GlassesState.SBS_FAILS, GlassesState.SBS_WORKS)
|
||||
markSbsFailed(linkDevice?.productId, s == GlassesState.SBS_FAILS)
|
||||
rememberSbs(s)
|
||||
}
|
||||
fun setGameOnGlasses(on: Boolean) = post { update { it.copy(gameOnGlasses = on) } }
|
||||
fun setHeadTracking(on: Boolean) = post { update { it.copy(headTracking = on) } }
|
||||
fun setAuto3d(on: Boolean) = post { update { it.copy(auto3d = on) } }
|
||||
fun setPicture3d(picture: Int) = post { update { it.copy(picture3d = picture.coerceIn(0, 2)) } }
|
||||
fun setScreenWidthDm(dm: Int) = post { update { it.copy(screenWidthDm = dm.coerceIn(5, 200)) } }
|
||||
fun setScreenDistanceDm(dm: Int) = post { update { it.copy(screenDistanceDm = dm.coerceIn(5, 200)) } }
|
||||
fun setVrFovDeg(deg: Int) = post { update { it.copy(vrFovDeg = deg.coerceIn(GlassesSettings.VR_FOV_MIN, GlassesSettings.VR_FOV_MAX)) } }
|
||||
|
||||
fun outputHz(): Int = GlassesRendering.outputHz(_settings.value, _state.value)
|
||||
|
||||
fun glassesDisplay(): Display? = _state.value.displayId.takeIf { it != Display.INVALID_DISPLAY }?.let { displays.getDisplay(it) }
|
||||
|
||||
fun setPoseSink(s: PoseSink) {
|
||||
synchronized(this) { sink = s }
|
||||
post { updateImu() }
|
||||
}
|
||||
|
||||
fun clearPoseSink(s: PoseSink) {
|
||||
synchronized(this) { if (sink === s) sink = null }
|
||||
post { updateImu() }
|
||||
}
|
||||
|
||||
fun simulate(seconds: Int, holdYaw: Double? = null, holdPitch: Double? = null): Boolean {
|
||||
val hold = holdYaw != null || holdPitch != null
|
||||
val t = Thread({
|
||||
val start = SystemClock.elapsedRealtimeNanos()
|
||||
val end = start + seconds * 1_000_000_000L
|
||||
while (SystemClock.elapsedRealtimeNanos() < end && simulating.get() === Thread.currentThread()) {
|
||||
val now = SystemClock.elapsedRealtimeNanos()
|
||||
val t = (now - start) / 1e9
|
||||
val yaw = if (hold) holdYaw ?: 0.0 else 40.0 * sin(t * 2 * Math.PI / 6.0)
|
||||
val pitch = if (hold) holdPitch ?: 0.0 else 15.0 * sin(t * 2 * Math.PI / 4.0)
|
||||
val roll = if (hold) 0.0 else 5.0 * sin(t * 2 * Math.PI / 5.0)
|
||||
val q = VitureProtocol.eulerZxy(roll.toFloat(), pitch.toFloat(), yaw.toFloat())
|
||||
deliver(q, now)
|
||||
SystemClock.sleep(4)
|
||||
}
|
||||
simulating.compareAndSet(Thread.currentThread(), null)
|
||||
}, "glasses-simulate")
|
||||
if (!simulating.compareAndSet(null, t)) return false
|
||||
t.start()
|
||||
return true
|
||||
}
|
||||
|
||||
fun stopSimulation() {
|
||||
simulating.set(null)
|
||||
}
|
||||
|
||||
fun status(): JSONObject {
|
||||
val s = _state.value
|
||||
val g = _settings.value
|
||||
val q = latest
|
||||
return JSONObject()
|
||||
.put("present", s.present).put("model", s.model).put("controllable", s.controllable)
|
||||
.put("permission", s.permission.name).put("connected", s.connected)
|
||||
.put("controlError", s.controlError ?: JSONObject.NULL)
|
||||
.put("experimental", s.experimental)
|
||||
.put("display", if (s.hasDisplay) JSONObject().put("id", s.displayId).put("width", s.width).put("height", s.height).put("hz", s.hz.toDouble()) else JSONObject.NULL)
|
||||
.put("sbs", s.sbs).put("deviceMode", glassesMode).put("switching3d", s.switching3d)
|
||||
.put("brightness", s.brightness).put("volume", s.volume)
|
||||
.put("brightnessMax", s.brightnessMax).put("volumeMax", s.volumeMax).put("sunblock", s.sunblock)
|
||||
.put("tracking", s.tracking).put("simulating", simulating.get() != null).put("imuPackets", imuPackets)
|
||||
.put("calibration", JSONObject().put("supported", _calibration.value.supported)
|
||||
.put("saved", _calibration.value.saved).put("phase", _calibration.value.phase.name)
|
||||
.put("progress", _calibration.value.progress))
|
||||
.put("badFrames", link?.badFrames ?: 0L)
|
||||
.put("pose", q?.let { JSONArray().put(it[0].toDouble()).put(it[1].toDouble()).put(it[2].toDouble()).put(it[3].toDouble()) } ?: JSONObject.NULL)
|
||||
.put("fovDeg", s.diagonalFovDeg.toDouble()).put("noSignal", s.noSignal).put("sbsSupport", s.sbsSupport)
|
||||
.put("settings", JSONObject().put("refreshHz", g.refreshHz).put("sbsHz", g.sbsHz).put("sunblock", g.sunblock ?: JSONObject.NULL)
|
||||
.put("gameOnGlasses", g.gameOnGlasses).put("headTracking", g.headTracking).put("auto3d", g.auto3d)
|
||||
.put("picture3d", g.picture3d).put("screenWidthDm", g.screenWidthDm).put("screenDistanceDm", g.screenDistanceDm)
|
||||
.put("vrFovDeg", g.vrFovDeg))
|
||||
}
|
||||
|
||||
fun recentFrames(): JSONArray = synchronized(frames) { JSONArray(frames.toList()) }
|
||||
|
||||
fun sendRaw(msgId: Int, payload: ByteArray): Boolean {
|
||||
val l = link ?: return false
|
||||
return l.send(msgId, payload)
|
||||
}
|
||||
|
||||
private fun post(block: () -> Unit) {
|
||||
if (!::handler.isInitialized) return
|
||||
handler.post(block)
|
||||
}
|
||||
|
||||
private fun publish(transform: (GlassesState) -> GlassesState) {
|
||||
_state.value = transform(_state.value)
|
||||
}
|
||||
|
||||
private fun update(transform: (GlassesSettings) -> GlassesSettings) {
|
||||
val next = transform(_settings.value)
|
||||
_settings.value = next
|
||||
save(next)
|
||||
}
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
ACTION_PERMISSION -> {
|
||||
val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
|
||||
Log.i(TAG, "USB permission ${if (granted) "granted" else "denied"}")
|
||||
if (!granted) publish { it.copy(permission = Permission.DENIED) }
|
||||
refresh()
|
||||
}
|
||||
UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
|
||||
if (intent.device()?.let { isGlassesVendor(it.vendorId) } == true) asked = false
|
||||
refresh(ask = true)
|
||||
}
|
||||
UsbManager.ACTION_USB_DEVICE_DETACHED -> if (intent.device()?.let { isGlassesVendor(it.vendorId) } == true) {
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = refresh()
|
||||
override fun onDisplayRemoved(displayId: Int) = refresh()
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
if (displayId == _state.value.displayId || displayId != Display.DEFAULT_DISPLAY) refresh()
|
||||
}
|
||||
}
|
||||
|
||||
private fun refresh(ask: Boolean = false) {
|
||||
val devices = usb.deviceList.values.filter {
|
||||
it.vendorId == VitureProtocol.VENDOR_ID || deviceModel(it) != null
|
||||
}
|
||||
val known = devices.mapNotNull { device ->
|
||||
deviceModel(device)?.let { device to it }
|
||||
}
|
||||
val selected = known.firstOrNull { canOpenModel(it.second) } ?: known.firstOrNull()
|
||||
val device = selected?.first
|
||||
val m = selected?.second
|
||||
val controllable = m?.let(::canOpenModel) == true
|
||||
// XREAL uses Android's Ethernet sockets, without opening or claiming USB interfaces.
|
||||
val permitted = controllable && device != null && (m === XrealModel || usb.hasPermission(device))
|
||||
val identity = device?.let {
|
||||
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
|
||||
}
|
||||
if (modeState.updateDevice(identity, SystemClock.uptimeMillis())) {
|
||||
rememberSbs(if (identity != null && sbsFailed(identity.productId)) GlassesState.SBS_FAILS else GlassesState.SBS_UNKNOWN)
|
||||
}
|
||||
if (device == null || (linkDevice != null && linkDevice?.deviceName != device.deviceName)) closeLink()
|
||||
model = m
|
||||
val display = findDisplay(devices.isNotEmpty())
|
||||
val mode = display?.mode
|
||||
val width = mode?.physicalWidth ?: 0
|
||||
val height = mode?.physicalHeight ?: 0
|
||||
val sbsByDisplay = width >= 3000
|
||||
val noSignal = display != null && width in 1 until 1280
|
||||
when (modeState.observe(sbsByDisplay, SystemClock.uptimeMillis())) {
|
||||
GlassesModeState.Confirmation.FAILED -> {
|
||||
Log.w(TAG, "3D signal was not confirmed at ${width}x$height; restoring 2D")
|
||||
if (noSignal) markSbsFailed(device?.productId, true)
|
||||
rememberSbs(GlassesState.SBS_FAILS)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
if (sbsByDisplay) {
|
||||
markSbsFailed(device?.productId, false)
|
||||
rememberSbs(GlassesState.SBS_WORKS)
|
||||
}
|
||||
if (controllable && device != null && !permitted && (ask || !asked) && _state.value.permission != Permission.ASKING) askPermission(device)
|
||||
if (device != null && permitted && link == null) openLink(device)
|
||||
publish {
|
||||
it.copy(
|
||||
present = device != null || display != null,
|
||||
model = m?.name ?: display?.let(::displayName) ?: "VITURE",
|
||||
controllable = controllable,
|
||||
permission = when {
|
||||
!controllable -> Permission.NONE
|
||||
permitted -> Permission.GRANTED
|
||||
it.permission == Permission.ASKING || it.permission == Permission.DENIED -> it.permission
|
||||
else -> Permission.NONE
|
||||
},
|
||||
connected = link?.ready == true,
|
||||
controlError = when {
|
||||
m is VitureProtocol.Model && m.needsSdk && !VitureSdk.available -> app.getString(R.string.glasses_driver_missing)
|
||||
device == null || link?.ready == true -> null
|
||||
else -> it.controlError
|
||||
},
|
||||
displayId = display?.displayId ?: Display.INVALID_DISPLAY,
|
||||
width = width, height = height, hz = mode?.refreshRate ?: 0f,
|
||||
sbs = sbsByDisplay,
|
||||
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,
|
||||
hasSunblock = m?.hasSunblock == true,
|
||||
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
|
||||
tracking = it.tracking && link != null,
|
||||
noSignal = noSignal,
|
||||
sbs90 = m?.sbs90 == true,
|
||||
experimental = m === XrealModel,
|
||||
)
|
||||
}
|
||||
if (link != null) applyMode(force = false)
|
||||
scheduleModeCheck()
|
||||
}
|
||||
|
||||
internal fun isGlassesVendor(vid: Int) = vid == VitureProtocol.VENDOR_ID || RayNeoModel.isVendor(vid) || vid == XrealModel.VENDOR_ID
|
||||
|
||||
private fun canOpenModel(m: GlassesModel): Boolean = m.controllable &&
|
||||
(m !is VitureProtocol.Model || !m.needsSdk || VitureSdk.available)
|
||||
|
||||
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)
|
||||
?: VitureProtocol.model(device.productId, name)
|
||||
}
|
||||
else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
|
||||
else RayNeoModel.model(device.vendorId, device.productId, name)
|
||||
}
|
||||
|
||||
internal fun isGlassesDisplayName(name: String) =
|
||||
name.contains("VITURE", ignoreCase = true) || RayNeoModel.isDisplay(name) || XrealModel.isDisplay(name)
|
||||
|
||||
private fun findDisplay(usbPresent: Boolean): Display? {
|
||||
return selectGlassesDisplay(displays.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).toList(), usbPresent)
|
||||
}
|
||||
|
||||
internal fun selectGlassesDisplay(displays: List<Display>, usbPresent: Boolean): Display? {
|
||||
val candidates = displays
|
||||
.filter { it.displayId != Display.DEFAULT_DISPLAY && it.flags and Display.FLAG_PRESENTATION != 0 }
|
||||
// Android can expose the glasses name on either the logical display or
|
||||
// its product metadata. A generic label on one must not hide the other.
|
||||
return candidates.firstOrNull { display ->
|
||||
isGlassesDisplayName(display.name) ||
|
||||
(Build.VERSION.SDK_INT >= 31 && display.deviceProductInfo?.let { product ->
|
||||
product.name?.let(::isGlassesDisplayName) == true ||
|
||||
RayNeoModel.isDisplayProduct(product.name, product.manufacturerPnpId, product.productId)
|
||||
} == true)
|
||||
}
|
||||
?: candidates.singleOrNull()?.takeIf { usbPresent && unnamedPanel(it) }
|
||||
}
|
||||
|
||||
private fun unnamedPanel(d: Display): Boolean {
|
||||
if (Build.VERSION.SDK_INT < 31) return true
|
||||
return d.deviceProductInfo?.name.isNullOrBlank()
|
||||
}
|
||||
|
||||
private fun displayName(d: Display): String? {
|
||||
if (Build.VERSION.SDK_INT >= 31) d.deviceProductInfo?.name?.takeIf { it.isNotBlank() }?.let { return it }
|
||||
return d.name
|
||||
}
|
||||
|
||||
private fun askPermission(device: UsbDevice) {
|
||||
asked = true
|
||||
publish { it.copy(permission = Permission.ASKING) }
|
||||
val flags = if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0
|
||||
val pi = PendingIntent.getBroadcast(app, 0, Intent(ACTION_PERMISSION).setPackage(app.packageName), flags)
|
||||
runCatching { usb.requestPermission(device, pi) }.onFailure { Log.w(TAG, "requestPermission", it) }
|
||||
}
|
||||
|
||||
private fun openLink(device: UsbDevice) {
|
||||
val generation = ++linkGeneration
|
||||
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) {
|
||||
VitureSdkLink.open(usb, device, File(app.cacheDir, "viture"), sdkListener(generation),
|
||||
(model as? VitureProtocol.Model)?.family)
|
||||
} else VitureLink.open(usb, device, linkListener(generation))
|
||||
} else if (model === XrealModel) {
|
||||
XrealLink.open(app, xrealListener(generation))
|
||||
} else {
|
||||
val baseKey = calibrationKey!!
|
||||
val gtUsb = RayNeoProtocol.isGt(device.vendorId, device.productId)
|
||||
RayNeoLink.open(usb, device, rayNeoListener(generation)) { board ->
|
||||
calibrationStore.load(RayNeoCalibrationStore.profileKey(baseKey, gtUsb, board))
|
||||
}
|
||||
}
|
||||
val opened = l ?: run {
|
||||
linkGeneration++
|
||||
Log.w(TAG, "could not open ${device.deviceName}")
|
||||
publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) }
|
||||
return
|
||||
}
|
||||
link = opened
|
||||
_calibration.value = GlassesCalibrationState(supported = opened is RayNeoLink,
|
||||
saved = opened is RayNeoLink && calibrationKey?.let(calibrationStore::load) != null)
|
||||
linkDevice = device
|
||||
glassesMode = 0
|
||||
autoModeSent = false
|
||||
Log.i(TAG, "opened ${model?.name} pid=0x%04X imu=%s".format(device.productId, opened.hasImu))
|
||||
publish { it.copy(connected = opened.ready, controlError = null) }
|
||||
listOf(VitureProtocol.MSG_GET_BRIGHTNESS, VitureProtocol.MSG_GET_VOLUME, VitureProtocol.MSG_GET_DISPLAY).forEachIndexed { i, msg ->
|
||||
handler.postDelayed({ if (link === opened) opened.send(msg) }, VitureLink.COMMAND_GAP_MS * (i + 1))
|
||||
}
|
||||
handler.postDelayed({
|
||||
if (link !== opened) return@postDelayed
|
||||
_settings.value.sunblock?.let { sendFilm(it) }
|
||||
updateImu()
|
||||
applyMode(force = false)
|
||||
}, 300)
|
||||
}
|
||||
|
||||
private fun xrealListener(generation: Long) = object : XrealLink.Listener {
|
||||
override fun onReady() = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
publish { it.copy(connected = true, controlError = null) }
|
||||
autoModeSent = false
|
||||
updateImu()
|
||||
applyMode(force = false)
|
||||
}
|
||||
override fun onValue(message: Int, value: Int) = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
when (message) {
|
||||
VitureProtocol.MSG_GET_DISPLAY -> glassesMode = value
|
||||
VitureProtocol.MSG_BRIGHTNESS -> publish { it.copy(brightness = value) }
|
||||
VitureProtocol.MSG_FILM -> publish { it.copy(sunblock = value != 0) }
|
||||
}
|
||||
}
|
||||
override fun onPose(raw: ByteArray, pose: FloatArray, timeNs: Long) {
|
||||
if (generation != linkGeneration) return
|
||||
imuPackets++
|
||||
probe?.invoke(raw, pose)
|
||||
if (simulating.get() == null) deliver(pose, timeNs)
|
||||
}
|
||||
override fun onUnavailable(networkMissing: Boolean) = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
publish { it.copy(connected = false, tracking = false,
|
||||
controlError = app.getString(if (networkMissing) R.string.glasses_xreal_network_missing else R.string.glasses_xreal_connection_failed)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun sdkListener(generation: Long) = object : VitureSdkLink.Listener {
|
||||
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) }
|
||||
VitureProtocol.MSG_FILM -> publish { it.copy(sunblock = value != 0) }
|
||||
}
|
||||
}
|
||||
override fun onPose(q: FloatArray, timeNs: Long) {
|
||||
if (generation != linkGeneration) return
|
||||
imuPackets++
|
||||
probe?.invoke(null, q)
|
||||
if (simulating.get() == null) deliver(q, timeNs)
|
||||
}
|
||||
override fun onLost() = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
closeLink()
|
||||
publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) }
|
||||
// Let a reconnect or explicit Allow retry restart the SDK, not an endless failure loop.
|
||||
}
|
||||
}
|
||||
|
||||
private fun rayNeoListener(generation: Long) = object : RayNeoLink.Listener {
|
||||
override fun onDeviceInfo(boardId: Int, calibrationSaved: Boolean) = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
val device = linkDevice ?: return@post
|
||||
val base = calibrationStore.key(device.vendorId, device.productId,
|
||||
runCatching { device.serialNumber }.getOrNull(), model?.name.orEmpty())
|
||||
calibrationKey = RayNeoCalibrationStore.profileKey(base,
|
||||
RayNeoProtocol.isGt(device.vendorId, device.productId), boardId)
|
||||
_calibration.value = _calibration.value.copy(saved = calibrationSaved)
|
||||
}
|
||||
override fun onCalibration(revision: Long, phase: CalibrationPhase, progress: Int) = post {
|
||||
if (generation != linkGeneration || revision != calibrationRevision) return@post
|
||||
if (phase != CalibrationPhase.IDLE && !_calibration.value.running) return@post
|
||||
_calibration.value = _calibration.value.copy(phase = phase, progress = progress)
|
||||
if (!_calibration.value.running) updateImu()
|
||||
}
|
||||
override fun onCalibrationSaved(revision: Long, value: RayNeoCalibration?) = post {
|
||||
if (generation != linkGeneration || revision != calibrationRevision) return@post
|
||||
if (value != null && !_calibration.value.running) return@post
|
||||
calibrationKey?.let { calibrationStore.save(it, value) }
|
||||
_calibration.value = _calibration.value.copy(saved = value != null)
|
||||
}
|
||||
override fun onReady() = post {
|
||||
if (generation == linkGeneration) {
|
||||
publish { it.copy(connected = true) }
|
||||
updateImu()
|
||||
applyMode(force = false)
|
||||
}
|
||||
}
|
||||
override fun onPose(raw: ByteArray, xyzw: FloatArray, timeNs: Long) {
|
||||
if (generation != linkGeneration) return
|
||||
imuPackets++
|
||||
probe?.invoke(raw, xyzw)
|
||||
if (simulating.get() == null) deliver(xyzw, timeNs)
|
||||
}
|
||||
override fun onLost() = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
closeLink()
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeLink() {
|
||||
val l = link ?: return
|
||||
linkGeneration++
|
||||
link = null
|
||||
linkDevice = null
|
||||
calibrationKey = null
|
||||
_calibration.value = GlassesCalibrationState(phase = if (_calibration.value.running) CalibrationPhase.FAILED else CalibrationPhase.IDLE)
|
||||
glassesMode = 0
|
||||
l.close()
|
||||
publish { it.copy(connected = false, tracking = false) }
|
||||
Log.i(TAG, "link closed")
|
||||
}
|
||||
|
||||
private fun rememberSbs(support: Int) {
|
||||
if (_state.value.sbsSupport == support) return
|
||||
publish { it.copy(sbsSupport = support) }
|
||||
}
|
||||
|
||||
private fun sbsFailed(productId: Int): Boolean =
|
||||
app.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY_SBS_FAILED, null)?.contains(productId.toString(16)) == true
|
||||
|
||||
private fun markSbsFailed(productId: Int?, failed: Boolean) {
|
||||
if (productId == null || sbsFailed(productId) == failed) return
|
||||
val prefs = app.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
val ids = prefs.getStringSet(KEY_SBS_FAILED, null).orEmpty()
|
||||
val id = productId.toString(16)
|
||||
prefs.edit().putStringSet(KEY_SBS_FAILED, if (failed) ids + id else ids - id).apply()
|
||||
}
|
||||
|
||||
private fun applyMode(force: Boolean) {
|
||||
val s = _state.value
|
||||
val m = model ?: return
|
||||
if (!s.canControl) return
|
||||
if (modeState.restorePending) {
|
||||
sendMode(false)
|
||||
return
|
||||
}
|
||||
if (!s.usable || s.sbs || modeState.pendingStereo) return
|
||||
val hz = _settings.value.refreshHz
|
||||
if (glassesMode == m.mode(hz, false)) return
|
||||
if (!force) {
|
||||
if (autoModeSent || SystemClock.uptimeMillis() - lastModeSentAt < 8_000) return
|
||||
if (glassesMode == 0 && abs(s.hz - hz) < 1.5f) return
|
||||
autoModeSent = true
|
||||
}
|
||||
sendMode(false)
|
||||
}
|
||||
|
||||
private fun sendMode(sbs: Boolean): Boolean {
|
||||
val m = model ?: return false
|
||||
val g = _settings.value
|
||||
val mode = m.mode(if (sbs) g.sbsHz else g.refreshHz, sbs)
|
||||
if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) {
|
||||
if (link is RayNeoLink) glassesMode = mode
|
||||
lastModeSentAt = SystemClock.uptimeMillis()
|
||||
modeState.sent(sbs, lastModeSentAt)
|
||||
publish { it.copy(switching3d = modeState.pendingStereo) }
|
||||
scheduleModeCheck()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun scheduleModeCheck() {
|
||||
handler.removeCallbacks(confirmMode)
|
||||
modeState.nextCheckAt?.let { at ->
|
||||
handler.postDelayed(confirmMode, (at - SystemClock.uptimeMillis()).coerceAtLeast(0))
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendFilm(on: Boolean) {
|
||||
if (!_state.value.canControl || !_state.value.hardwareControls || !_state.value.hasSunblock) return
|
||||
if (link?.send(VitureProtocol.MSG_FILM, byteArrayOf(if (on) 1 else 0)) == true && link !is XrealLink)
|
||||
publish { it.copy(sunblock = on) }
|
||||
}
|
||||
|
||||
private fun updateImu() {
|
||||
val l = link ?: return
|
||||
if (!l.ready) return
|
||||
val want = (sink != null || probe != null || _calibration.value.running) && l.hasImu
|
||||
if (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) }
|
||||
}
|
||||
|
||||
private fun linkListener(generation: Long) = object : VitureLink.Listener {
|
||||
override fun onFrame(frame: VitureProtocol.Frame) = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
val line = "%s 0x%04X %s".format(
|
||||
when (frame.magic) { VitureProtocol.MAGIC_REPORT -> "FD"; VitureProtocol.MAGIC_COMMAND -> "FE"; else -> "FC" },
|
||||
frame.msgId, frame.payload.joinToString("") { "%02X".format(it) },
|
||||
)
|
||||
synchronized(frames) {
|
||||
frames.addLast(line)
|
||||
while (frames.size > 64) frames.removeFirst()
|
||||
}
|
||||
Log.i(TAG, "frame $line")
|
||||
onReport(frame)
|
||||
}
|
||||
|
||||
override fun onImu(payload: ByteArray, timeNs: Long) {
|
||||
if (generation != linkGeneration) return
|
||||
imuPackets++
|
||||
probe?.invoke(payload, null)
|
||||
if (simulating.get() != null) return
|
||||
VitureProtocol.imuQuaternion(payload)?.let { deliver(it, timeNs) }
|
||||
}
|
||||
|
||||
override fun onLost() = post {
|
||||
if (generation != linkGeneration) return@post
|
||||
closeLink()
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
private fun deliver(q: FloatArray, timeNs: Long) {
|
||||
latest = q
|
||||
sink?.onPose(q[0], q[1], q[2], q[3], timeNs)
|
||||
}
|
||||
|
||||
private fun onReport(frame: VitureProtocol.Frame) {
|
||||
val p = frame.payload
|
||||
val event = p.firstOrNull()?.toInt()?.and(0xFF) ?: return
|
||||
val answer = if (p.size >= 2 && event == 0) p[1].toInt() and 0xFF else null
|
||||
when (frame.msgId) {
|
||||
VitureProtocol.EVENT_DISPLAY -> {
|
||||
Log.i(TAG, "glasses switched to mode 0x%02X".format(event))
|
||||
glassesMode = event
|
||||
}
|
||||
VitureProtocol.EVENT_DISPLAY_STEP -> model?.modeForStep(event)?.let { mode ->
|
||||
Log.i(TAG, "glasses report mode 0x%02X".format(mode))
|
||||
glassesMode = mode
|
||||
}
|
||||
VitureProtocol.EVENT_BRIGHTNESS -> publish { it.copy(brightness = event) }
|
||||
VitureProtocol.EVENT_VOLUME -> publish { it.copy(volume = event) }
|
||||
VitureProtocol.MSG_GET_BRIGHTNESS, VitureProtocol.MSG_BRIGHTNESS -> answer?.let { v -> publish { it.copy(brightness = v) } }
|
||||
VitureProtocol.MSG_GET_VOLUME, VitureProtocol.MSG_VOLUME -> answer?.let { v -> publish { it.copy(volume = v) } }
|
||||
VitureProtocol.MSG_DISPLAY -> if (event != 0) {
|
||||
Log.w(TAG, "glasses refused display mode 0x%02X".format(p.getOrNull(1)?.toInt()?.and(0xFF) ?: 0))
|
||||
modeState.cancelPending()
|
||||
publish { it.copy(switching3d = false) }
|
||||
scheduleModeCheck()
|
||||
} else answer?.let { glassesMode = it }
|
||||
VitureProtocol.MSG_GET_DISPLAY -> answer?.let { v ->
|
||||
glassesMode = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun sampleImu(ms: Long): JSONObject {
|
||||
val raw = java.util.Collections.synchronizedList(mutableListOf<Pair<ByteArray?, FloatArray?>>())
|
||||
val counter = java.util.concurrent.atomic.AtomicInteger()
|
||||
val began = SystemClock.elapsedRealtime()
|
||||
probe = { payload, pose -> val n = counter.incrementAndGet(); if (raw.size < 4 || n % 60 == 0) raw.add(payload?.copyOf() to pose?.copyOf()) }
|
||||
post { updateImu() }
|
||||
SystemClock.sleep(ms)
|
||||
probe = null
|
||||
post { updateImu() }
|
||||
val seconds = (SystemClock.elapsedRealtime() - began) / 1000.0
|
||||
val count = counter.get()
|
||||
val samples = JSONArray()
|
||||
synchronized(raw) {
|
||||
raw.forEach { (b, pose) ->
|
||||
val rayneo = b != null && RayNeoProtocol.classifyPacket(b) is RayNeoPacket.Sensor
|
||||
val q = pose ?: if (b == null || rayneo) null else VitureProtocol.imuQuaternion(b)
|
||||
samples.put(JSONObject()
|
||||
.put("hex", b?.joinToString("") { "%02X".format(it) } ?: JSONObject.NULL)
|
||||
.put("euler", if (b == null || b.size < 12 || rayneo || pose != null) JSONObject.NULL else JSONArray().put(VitureProtocol.beFloat(b, 0).toDouble()).put(VitureProtocol.beFloat(b, 4).toDouble()).put(VitureProtocol.beFloat(b, 8).toDouble()))
|
||||
.put("quat", q?.let { JSONArray().put(it[0].toDouble()).put(it[1].toDouble()).put(it[2].toDouble()).put(it[3].toDouble()) } ?: JSONObject.NULL))
|
||||
}
|
||||
}
|
||||
return JSONObject().put("packets", count).put("rateHz", count / seconds).put("samples", samples)
|
||||
}
|
||||
|
||||
private fun Intent.device(): UsbDevice? =
|
||||
if (Build.VERSION.SDK_INT >= 33) getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
|
||||
else @Suppress("DEPRECATION") getParcelableExtra(UsbManager.EXTRA_DEVICE)
|
||||
|
||||
private fun load(): GlassesSettings {
|
||||
val p = app.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
return GlassesSettings(
|
||||
refreshHz = p.getInt("refreshHz", 120),
|
||||
sbsHz = p.getInt("sbsHz", 60),
|
||||
sunblock = if (p.contains("sunblock")) p.getBoolean("sunblock", false) else null,
|
||||
gameOnGlasses = p.getBoolean("gameOnGlasses", true),
|
||||
headTracking = p.getBoolean("headTracking", true),
|
||||
auto3d = p.getBoolean("auto3d", GlassesSettings().auto3d),
|
||||
picture3d = p.getInt("picture3d", GlassesSettings.PICTURE_AUTO),
|
||||
screenWidthDm = p.getInt("screenWidthDm", 20),
|
||||
screenDistanceDm = p.getInt("screenDistanceDm", 30),
|
||||
vrFovDeg = p.getInt("vrFovDeg", GlassesSettings.VR_FOV_DEFAULT).coerceIn(GlassesSettings.VR_FOV_MIN, GlassesSettings.VR_FOV_MAX),
|
||||
)
|
||||
}
|
||||
|
||||
private fun save(s: GlassesSettings) {
|
||||
app.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().apply {
|
||||
putInt("refreshHz", s.refreshHz)
|
||||
putInt("sbsHz", s.sbsHz)
|
||||
s.sunblock?.let { putBoolean("sunblock", it) } ?: remove("sunblock")
|
||||
putBoolean("gameOnGlasses", s.gameOnGlasses)
|
||||
putBoolean("headTracking", s.headTracking)
|
||||
putBoolean("auto3d", s.auto3d)
|
||||
putInt("picture3d", s.picture3d)
|
||||
putInt("screenWidthDm", s.screenWidthDm)
|
||||
putInt("screenDistanceDm", s.screenDistanceDm)
|
||||
putInt("vrFovDeg", s.vrFovDeg)
|
||||
}.apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
/** Hardware properties; display refresh is selected from Android's advertised modes. */
|
||||
interface GlassesModel {
|
||||
val name: String
|
||||
val controllable: Boolean
|
||||
val brightnessMax: Int
|
||||
val volumeMax: Int
|
||||
val diagonalFovDeg: Float
|
||||
val sbs90: Boolean
|
||||
val hasSunblock: Boolean get() = true
|
||||
fun mode(hz: Int, sbs: Boolean): Int
|
||||
fun modeForStep(step: Int): Int?
|
||||
}
|
||||
|
||||
/** The command IDs here are the existing glasses controller's internal vocabulary.
|
||||
* Each transport translates them to its own wire protocol; unsupported controls return false.
|
||||
*/
|
||||
internal interface GlassesLink {
|
||||
val hasImu: Boolean
|
||||
val badFrames: Long get() = 0L
|
||||
val ready: Boolean get() = true
|
||||
fun send(msgId: Int, payload: ByteArray = ByteArray(0)): Boolean
|
||||
fun close()
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
internal class GlassesModeState(private val timeoutMs: Long) {
|
||||
enum class Confirmation { NONE, WAITING, CONFIRMED, FAILED }
|
||||
data class Device(val productId: Int, val serial: String?)
|
||||
|
||||
private var deadline: Long? = null
|
||||
private var device: Device? = null
|
||||
private var attached = false
|
||||
private var reconnectDeadline: Long? = null
|
||||
private var vrOwned = false
|
||||
var restorePending = false
|
||||
private set
|
||||
val pendingStereo: Boolean get() = deadline != null
|
||||
val nextCheckAt: Long? get() = listOfNotNull(deadline, reconnectDeadline).minOrNull()
|
||||
|
||||
fun updateDevice(current: Device?, now: Long): Boolean {
|
||||
if (reconnectDeadline?.let { now >= it } == true) abandon()
|
||||
if (current == null) {
|
||||
if (attached) reconnectDeadline = now + timeoutMs
|
||||
attached = false
|
||||
return false
|
||||
}
|
||||
val previous = device
|
||||
val changed = previous == null || previous.productId != current.productId ||
|
||||
(previous.serial != null && current.serial != null && previous.serial != current.serial)
|
||||
if (changed) abandon()
|
||||
device = if (!changed && current.serial == null) previous else current
|
||||
attached = true
|
||||
reconnectDeadline = null
|
||||
return changed
|
||||
}
|
||||
|
||||
private fun abandon() {
|
||||
deadline = null
|
||||
reconnectDeadline = null
|
||||
vrOwned = false
|
||||
restorePending = false
|
||||
}
|
||||
|
||||
fun manual() {
|
||||
vrOwned = false
|
||||
restorePending = false
|
||||
}
|
||||
|
||||
fun startVr() {
|
||||
vrOwned = true
|
||||
restorePending = false
|
||||
}
|
||||
|
||||
fun stopVr(): Boolean {
|
||||
if (vrOwned) {
|
||||
vrOwned = false
|
||||
restorePending = true
|
||||
}
|
||||
return restorePending
|
||||
}
|
||||
|
||||
fun sent(stereo: Boolean, now: Long) {
|
||||
deadline = if (stereo) now + timeoutMs else null
|
||||
if (!stereo) restorePending = false
|
||||
}
|
||||
|
||||
fun cancelPending() {
|
||||
deadline = null
|
||||
}
|
||||
|
||||
fun observe(stereo: Boolean, now: Long): Confirmation {
|
||||
val until = deadline ?: return Confirmation.NONE
|
||||
if (stereo) {
|
||||
deadline = null
|
||||
return Confirmation.CONFIRMED
|
||||
}
|
||||
if (now < until) return Confirmation.WAITING
|
||||
if (!attached) {
|
||||
abandon()
|
||||
return Confirmation.NONE
|
||||
}
|
||||
deadline = null
|
||||
vrOwned = false
|
||||
restorePending = true
|
||||
return Confirmation.FAILED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
|
||||
/** Share the actual picture mode with settings so controls match the rendered view. */
|
||||
internal object GlassesRendering {
|
||||
enum class Picture { FLAT, VIRTUAL_SCREEN, STEREO }
|
||||
|
||||
fun outputHz(settings: GlassesSettings, state: GlassesState): Int =
|
||||
if (state.sbs) if (state.sbs90) settings.sbsHz else 60 else settings.refreshHz
|
||||
|
||||
fun mirrorRefreshLimit(settings: GlassesSettings, state: GlassesState, outputActive: Boolean): Int =
|
||||
if (state.usable && !outputActive) outputHz(settings, state) else 0
|
||||
|
||||
fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when {
|
||||
mirrorRefreshLimit <= 0 -> requested
|
||||
requested <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(requested, mirrorRefreshLimit)
|
||||
}
|
||||
|
||||
fun usesGlasses(state: GlassesState, outputActive: Boolean, steamVrRunning: Boolean): Boolean =
|
||||
outputActive || (steamVrRunning && state.usable)
|
||||
|
||||
fun picture(settings: GlassesSettings, stereoDisplay: Boolean, steamVrRunning: Boolean): Picture =
|
||||
when (settings.picture3d) {
|
||||
GlassesSettings.PICTURE_SCREEN -> Picture.VIRTUAL_SCREEN
|
||||
GlassesSettings.PICTURE_SBS -> Picture.STEREO
|
||||
else -> when {
|
||||
steamVrRunning -> Picture.STEREO
|
||||
stereoDisplay -> Picture.VIRTUAL_SCREEN
|
||||
else -> Picture.FLAT
|
||||
}
|
||||
}
|
||||
|
||||
fun cardboard(
|
||||
base: Cardboard,
|
||||
settings: GlassesSettings,
|
||||
state: GlassesState,
|
||||
outputActive: Boolean,
|
||||
steamVrRunning: Boolean,
|
||||
): Cardboard {
|
||||
// Mirror output still uses the glasses' picture and sensors during VR.
|
||||
if (!usesGlasses(state, outputActive, steamVrRunning)) {
|
||||
// SteamVR uses the renderer's enabled flag as headset proximity.
|
||||
// A flat phone preview still needs an active HMD and one SBS eye;
|
||||
// otherwise SteamVR enters standby and leaves a frozen frame.
|
||||
return if (steamVrRunning && !base.enabled) base.copy(
|
||||
enabled = true,
|
||||
source = Cardboard.SOURCE_SBS,
|
||||
viewer = Cardboard.Viewer.NONE.id,
|
||||
mono = true,
|
||||
) else base
|
||||
}
|
||||
val picture = picture(settings, state.sbs, steamVrRunning)
|
||||
if (picture == Picture.FLAT) return Cardboard.OFF
|
||||
return Cardboard(
|
||||
enabled = true,
|
||||
source = if (picture == Picture.STEREO) Cardboard.SOURCE_SBS else Cardboard.SOURCE_SCREEN,
|
||||
viewer = Cardboard.Viewer.VITURE.id,
|
||||
ipdMm = base.ipdMm,
|
||||
screenWidthDm = settings.screenWidthDm,
|
||||
screenDistanceDm = settings.screenDistanceDm,
|
||||
headTracking = settings.headTracking && state.canControl,
|
||||
mono = !state.sbs,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.app.Presentation
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
import kotlin.math.abs
|
||||
|
||||
class GlassesScreen(context: Context, display: Display, refreshHz: Int, private val callback: SurfaceHolder.Callback) : Presentation(context, display) {
|
||||
val surfaceView = SurfaceView(getContext())
|
||||
val holder: SurfaceHolder get() = surfaceView.holder
|
||||
private var wantHz = refreshHz
|
||||
|
||||
val hz: Float get() = display.mode.refreshRate
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val root = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
|
||||
root.addView(surfaceView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
|
||||
setContentView(root)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
applyMode()
|
||||
surfaceView.holder.addCallback(callback)
|
||||
}
|
||||
|
||||
fun prefer(hz: Int) {
|
||||
wantHz = hz
|
||||
// A 2D/SBS transition can replace the active mode without changing Hz.
|
||||
applyMode()
|
||||
}
|
||||
|
||||
private fun applyMode() {
|
||||
val w = window ?: return
|
||||
val current = display.mode
|
||||
val best = display.supportedModes.filter {
|
||||
it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight
|
||||
}.minByOrNull { abs(it.refreshRate - wantHz) } ?: return
|
||||
if (w.attributes.preferredDisplayModeId != best.modeId) {
|
||||
Log.i("GlassesScreen", "display ${display.displayId}: prefer mode ${best.modeId} " +
|
||||
"${best.physicalWidth}x${best.physicalHeight}@${best.refreshRate} (requested $wantHz Hz)")
|
||||
w.attributes = w.attributes.apply { preferredDisplayModeId = best.modeId }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.content.SharedPreferences
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
enum class CalibrationPhase { IDLE, SETTLING, COLLECTING, MOVING, TURN_OVER, SAVED, FAILED }
|
||||
|
||||
data class GlassesCalibrationState(
|
||||
val supported: Boolean = false,
|
||||
val saved: Boolean = false,
|
||||
val phase: CalibrationPhase = CalibrationPhase.IDLE,
|
||||
val progress: Int = 0,
|
||||
) {
|
||||
val running: Boolean get() = phase in setOf(CalibrationPhase.SETTLING, CalibrationPhase.COLLECTING,
|
||||
CalibrationPhase.MOVING, CalibrationPhase.TURN_OVER)
|
||||
}
|
||||
|
||||
internal data class RayNeoCalibration(val gyroBiasDps: Vec3, val level: Quaternion) {
|
||||
fun encode(): String = JSONObject().put("version", 1)
|
||||
.put("bias", JSONArray(listOf(gyroBiasDps.x, gyroBiasDps.y, gyroBiasDps.z)))
|
||||
.put("level", JSONArray(listOf(level.w, level.x, level.y, level.z))).toString()
|
||||
|
||||
companion object {
|
||||
fun decode(json: String?): RayNeoCalibration? = runCatching {
|
||||
val obj = JSONObject(json ?: return null)
|
||||
require(obj.getInt("version") == 1)
|
||||
val b = obj.getJSONArray("bias"); val q = obj.getJSONArray("level")
|
||||
require(b.length() == 3 && q.length() == 4)
|
||||
val bias = Vec3(b.getDouble(0).toFloat(), b.getDouble(1).toFloat(), b.getDouble(2).toFloat())
|
||||
val level = Quaternion(q.getDouble(0).toFloat(), q.getDouble(1).toFloat(), q.getDouble(2).toFloat(), q.getDouble(3).toFloat())
|
||||
require(listOf(bias.x, bias.y, bias.z, level.w, level.x, level.y, level.z).all { it.isFinite() })
|
||||
require(bias.length() <= 6f && level.w in 0.96f..1.001f)
|
||||
val norm = level.w * level.w + level.x * level.x + level.y * level.y + level.z * level.z
|
||||
require(norm in 0.99f..1.01f)
|
||||
RayNeoCalibration(bias, level.normalized())
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
internal class RayNeoCalibrationStore(private val prefs: SharedPreferences) {
|
||||
companion object {
|
||||
// GT and GT Max can share USB identity fields. Keep the non-Max mounting
|
||||
// correction separate from existing Max profiles and their legacy keys.
|
||||
fun profileKey(base: String, gtUsb: Boolean, boardId: Int): String =
|
||||
if (gtUsb && boardId == RayNeoProtocol.BOARD_GT) "$base:gt-standard-v1" else base
|
||||
}
|
||||
// A serial isolates physical units. Devices without one share their model profile.
|
||||
fun key(vid: Int, pid: Int, serial: String?, modelName: String = ""): String =
|
||||
"rayneo-cal-v1:$vid:$pid:${serial?.takeIf { it.isNotBlank() } ?: "model:$modelName"}"
|
||||
fun load(key: String): RayNeoCalibration? = RayNeoCalibration.decode(prefs.getString(key, null))
|
||||
fun save(key: String, value: RayNeoCalibration?) {
|
||||
if (value == null) prefs.edit().remove(key).apply()
|
||||
else prefs.edit().putString(key, value.encode()).apply()
|
||||
}
|
||||
}
|
||||
|
||||
/** One upside-down stationary pose estimates gyro bias and tilt, never yaw or accelerometer scale. */
|
||||
internal class RayNeoCalibrationCollector(private val axes: RayNeoSensorAxes, private val beganMs: Long) {
|
||||
var phase = CalibrationPhase.SETTLING; private set
|
||||
var progress = 0; private set
|
||||
private var windowStart = -1L
|
||||
private var lastMs = -1L
|
||||
private var count = 0
|
||||
private var meanA = Vec3(0f, 0f, 0f)
|
||||
private var meanG = Vec3(0f, 0f, 0f)
|
||||
private var aVariance = 0f
|
||||
private var gVariance = 0f
|
||||
|
||||
private fun clear(next: CalibrationPhase) {
|
||||
phase = next; progress = 0; windowStart = -1; count = 0
|
||||
meanA = Vec3(0f, 0f, 0f); meanG = meanA; aVariance = 0f; gVariance = 0f
|
||||
}
|
||||
|
||||
fun update(sample: RayNeoSensorSample, nowMs: Long): RayNeoCalibration? {
|
||||
if (phase == CalibrationPhase.FAILED || phase == CalibrationPhase.SAVED) return null
|
||||
if (nowMs - beganMs >= 30_000) { clear(CalibrationPhase.FAILED); return null }
|
||||
val gap = lastMs >= 0 && nowMs - lastMs > 250
|
||||
lastMs = nowMs
|
||||
if (nowMs - beganMs < 3000) return null
|
||||
val a = axes.map(Vec3(sample.accelMps2[0], sample.accelMps2[1], sample.accelMps2[2]))
|
||||
val g = Vec3(sample.gyroDps[0], sample.gyroDps[1], sample.gyroDps[2])
|
||||
if (a.length() !in 8.5f..11f || !g.length().isFinite() || g.length() > 6f || gap) {
|
||||
clear(CalibrationPhase.MOVING); return null
|
||||
}
|
||||
if (a.normalized().y > -0.94f) { clear(CalibrationPhase.TURN_OVER); return null }
|
||||
if (windowStart < 0) windowStart = nowMs
|
||||
phase = CalibrationPhase.COLLECTING
|
||||
count++
|
||||
val da = a - meanA; val dg = g - meanG
|
||||
meanA += da * (1f / count); meanG += dg * (1f / count)
|
||||
fun dot(x: Vec3, y: Vec3) = x.x * y.x + x.y * y.y + x.z * y.z
|
||||
aVariance += dot(da, a - meanA); gVariance += dot(dg, g - meanG)
|
||||
if (count > 25 && (aVariance / count > 0.04f || gVariance / count > 2.25f)) {
|
||||
clear(CalibrationPhase.MOVING); return null
|
||||
}
|
||||
progress = ((nowMs - windowStart) * 100 / 5000).toInt().coerceIn(0, 99)
|
||||
if (nowMs - windowStart < 5000 || count < 200) return null
|
||||
val down = meanA.normalized()
|
||||
val axis = down.cross(Vec3(0f, -1f, 0f))
|
||||
val result = RayNeoCalibration(meanG, Quaternion(1f - down.y, axis.x, axis.y, axis.z).normalized())
|
||||
phase = CalibrationPhase.SAVED; progress = 100
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbDeviceConnection
|
||||
import android.hardware.usb.UsbManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
|
||||
/** RayNeo command/response and IMU share one endpoint. Keep reads on a single worker. */
|
||||
internal class RayNeoLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val endpoints: RayNeoEndpointSelection,
|
||||
private val listener: Listener,
|
||||
private val gt: Boolean,
|
||||
private val loadCalibration: (Int) -> RayNeoCalibration?,
|
||||
) : GlassesLink {
|
||||
interface Listener {
|
||||
fun onReady()
|
||||
fun onPose(raw: ByteArray, xyzw: FloatArray, timeNs: Long)
|
||||
fun onLost()
|
||||
fun onCalibration(revision: Long, phase: CalibrationPhase, progress: Int) {}
|
||||
fun onCalibrationSaved(revision: Long, value: RayNeoCalibration?) {}
|
||||
fun onDeviceInfo(boardId: Int, calibrationSaved: Boolean) {}
|
||||
}
|
||||
|
||||
@Volatile private var running = true
|
||||
@Volatile override var ready = false
|
||||
private set
|
||||
@Volatile private var wantImu = false
|
||||
private val writeLock = Any()
|
||||
private val assembler = RayNeoPacketAssembler()
|
||||
private val readBuffer = ByteArray(maxOf(endpoints.inEndpoint.maxPacketSize, 64))
|
||||
private var failures = 0
|
||||
private lateinit var worker: Thread
|
||||
private var calibration: RayNeoCalibration? = null
|
||||
private data class CalibrationCommand(val revision: Long, val action: Int, val saved: RayNeoCalibration? = null)
|
||||
private val calibrationCommand = java.util.concurrent.atomic.AtomicReference<CalibrationCommand?>(null)
|
||||
fun startCalibration(revision: Long) { calibrationCommand.set(CalibrationCommand(revision, 1)) }
|
||||
fun cancelCalibration(revision: Long, saved: RayNeoCalibration?) { calibrationCommand.set(CalibrationCommand(revision, 2, saved)) }
|
||||
fun resetCalibration(revision: Long) { calibrationCommand.set(CalibrationCommand(revision, 3)) }
|
||||
override val hasImu = true
|
||||
|
||||
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
||||
if (!running) return false
|
||||
return when (msgId) {
|
||||
VitureProtocol.MSG_IMU -> {
|
||||
wantImu = payload.firstOrNull() == 1.toByte()
|
||||
true
|
||||
}
|
||||
VitureProtocol.MSG_DISPLAY -> {
|
||||
val mode = payload.firstOrNull()?.toInt()?.and(0xff)
|
||||
ready && (mode == RayNeoProtocol.CMD_SWITCH_TO_3D || mode == RayNeoProtocol.CMD_SWITCH_TO_2D) &&
|
||||
command(mode)
|
||||
}
|
||||
// No VITURE brightness, volume, film, rate or raw command is sent to RayNeo.
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
private fun command(cmd: Int): Boolean = synchronized(writeLock) {
|
||||
if (!running) return false
|
||||
val packet = RayNeoProtocol.buildCommandPacket(cmd, 0, endpoints.outEndpoint.maxPacketSize)
|
||||
connection.bulkTransfer(endpoints.outEndpoint, packet, packet.size, 250) == packet.size
|
||||
}
|
||||
|
||||
private fun read(timeoutMs: Int): ByteArray? {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (running && SystemClock.elapsedRealtime() < deadline) {
|
||||
assembler.nextPacket()?.let { return it }
|
||||
val began = SystemClock.elapsedRealtime()
|
||||
val count = connection.bulkTransfer(endpoints.inEndpoint, readBuffer, readBuffer.size, 50)
|
||||
if (count > 0) {
|
||||
failures = 0
|
||||
assembler.append(readBuffer, count)
|
||||
} else if (count < 0 && SystemClock.elapsedRealtime() - began < 25) {
|
||||
if (++failures >= 50) error("RayNeo USB link lost")
|
||||
SystemClock.sleep(5)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun response(cmd: Int, timeoutMs: Int): RayNeoPacket.Response? {
|
||||
val deadline = SystemClock.elapsedRealtime() + timeoutMs
|
||||
while (running && SystemClock.elapsedRealtime() < deadline) {
|
||||
val packet = read(100)?.let(RayNeoProtocol::classifyPacket)
|
||||
if (packet is RayNeoPacket.Response && packet.cmd == cmd) return packet
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
var streaming = false
|
||||
try {
|
||||
check(command(RayNeoProtocol.CMD_ACQUIRE_DEVICE_INFO)) { "RayNeo device-info write failed" }
|
||||
val info = response(RayNeoProtocol.CMD_ACQUIRE_DEVICE_INFO, 2500)
|
||||
?.let { RayNeoProtocol.parseDeviceInfo(it.raw) } ?: error("RayNeo device-info timed out")
|
||||
val profile = RayNeoSensorProfile.forDevice(gt, info.boardId)
|
||||
val rotation = profile.rotationXDeg
|
||||
val gtMaxAxes = profile.gtMaxAxes
|
||||
calibration = loadCalibration(info.boardId)
|
||||
listener.onDeviceInfo(info.boardId, calibration != null)
|
||||
Log.i("RayNeoLink", "Device board=0x%02x gt=%s".format(info.boardId, gt))
|
||||
var filter = RayNeoOrientationFilter(rotation, gtMaxAxes, calibration)
|
||||
var collector: RayNeoCalibrationCollector? = null
|
||||
var calibrationRevision = 0L
|
||||
var lastCalibrationUpdate = 0L
|
||||
var warmupUntil = 0L
|
||||
var lastSensor = 0L
|
||||
ready = true
|
||||
listener.onReady()
|
||||
while (running) {
|
||||
val request = calibrationCommand.getAndSet(null)
|
||||
if (request != null) calibrationRevision = request.revision
|
||||
when (request?.action) {
|
||||
1 -> collector = RayNeoCalibrationCollector(RayNeoSensorAxes(rotation, gtMaxAxes), SystemClock.elapsedRealtime())
|
||||
2 -> {
|
||||
collector = null
|
||||
if (calibration != request.saved) {
|
||||
calibration = request.saved
|
||||
filter = RayNeoOrientationFilter(rotation, gtMaxAxes, calibration)
|
||||
}
|
||||
listener.onCalibration(calibrationRevision, CalibrationPhase.IDLE, 0)
|
||||
}
|
||||
3 -> {
|
||||
collector = null; calibration = null
|
||||
filter = RayNeoOrientationFilter(rotation, gtMaxAxes)
|
||||
listener.onCalibrationSaved(calibrationRevision, null)
|
||||
listener.onCalibration(calibrationRevision, CalibrationPhase.IDLE, 0)
|
||||
}
|
||||
}
|
||||
if (wantImu != streaming) {
|
||||
val cmd = if (wantImu) RayNeoProtocol.CMD_OPEN_IMU else RayNeoProtocol.CMD_CLOSE_IMU
|
||||
check(command(cmd) && response(cmd, 1500) != null) { "RayNeo IMU command timed out" }
|
||||
streaming = cmd == RayNeoProtocol.CMD_OPEN_IMU
|
||||
filter = RayNeoOrientationFilter(rotation, gtMaxAxes, calibration)
|
||||
lastSensor = SystemClock.elapsedRealtime()
|
||||
warmupUntil = lastSensor + 2000
|
||||
}
|
||||
val raw = read(100)
|
||||
if (streaming && SystemClock.elapsedRealtime() - lastSensor > 4000) error("RayNeo IMU stream stalled")
|
||||
if (raw == null) continue
|
||||
val packet = RayNeoProtocol.classifyPacket(raw)
|
||||
if (streaming && packet is RayNeoPacket.Sensor) {
|
||||
lastSensor = SystemClock.elapsedRealtime()
|
||||
collector?.let { c ->
|
||||
val result = c.update(packet.sample, lastSensor)
|
||||
if (result != null && calibrationCommand.get() == null) {
|
||||
calibration = result
|
||||
filter = RayNeoOrientationFilter(rotation, gtMaxAxes, result)
|
||||
warmupUntil = lastSensor + 2000
|
||||
listener.onCalibrationSaved(calibrationRevision, result)
|
||||
}
|
||||
if (lastSensor - lastCalibrationUpdate >= 200 || result != null || c.phase == CalibrationPhase.FAILED) {
|
||||
listener.onCalibration(calibrationRevision, c.phase, c.progress)
|
||||
lastCalibrationUpdate = lastSensor
|
||||
}
|
||||
if (result != null || c.phase == CalibrationPhase.FAILED) collector = null
|
||||
}
|
||||
val wxyz = filter.update(packet.sample)
|
||||
if (wantImu && collector == null && lastSensor >= warmupUntil) {
|
||||
// Normalize basis and component order at the hardware boundary.
|
||||
listener.onPose(raw, RayNeoOrientationFilter.glassesPose(wxyz),
|
||||
SystemClock.elapsedRealtimeNanos())
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (running) Log.w("RayNeoLink", "RayNeo stream failed", e)
|
||||
} finally {
|
||||
ready = false
|
||||
if (running) listener.onLost()
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
synchronized(writeLock) {
|
||||
if (!running) return
|
||||
// Best effort: stop the sensor before releasing the claimed interface.
|
||||
if (ready) runCatching { command(RayNeoProtocol.CMD_CLOSE_IMU) }
|
||||
running = false
|
||||
}
|
||||
if (Thread.currentThread() !== worker) worker.join(500)
|
||||
runCatching { connection.releaseInterface(endpoints.usbInterface) }
|
||||
connection.close()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun open(usb: UsbManager, device: UsbDevice, listener: Listener, loadCalibration: (Int) -> RayNeoCalibration? = { null }): RayNeoLink? {
|
||||
val endpoints = RayNeoProtocol.selectEndpoints(device) ?: return null
|
||||
val conn = usb.openDevice(device) ?: return null
|
||||
if (!conn.claimInterface(endpoints.usbInterface, true)) {
|
||||
conn.close()
|
||||
return null
|
||||
}
|
||||
return RayNeoLink(conn, endpoints, listener, RayNeoProtocol.isGt(device.vendorId, device.productId), loadCalibration).also { link ->
|
||||
link.worker = Thread({ link.run() }, "rayneo-imu").apply { isDaemon = true }
|
||||
link.worker.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
object RayNeoModel {
|
||||
private val modelName = Regex("(?i)(ray\\s*neo|tcl).*\\b(air|gt)(?=\\b|[0-9])")
|
||||
|
||||
fun isVendor(vid: Int) = vid == RayNeoProtocol.VENDOR_ID ||
|
||||
vid == RayNeoProtocol.GT_VENDOR_ID || vid == 0x22d9
|
||||
|
||||
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
|
||||
if (!isVendor(vid)) return null
|
||||
// GT's identity is confirmed by verncat's SDK; do not claim other products
|
||||
// from that vendor just because their name resembles a supported model.
|
||||
val gt = RayNeoProtocol.isGt(vid, pid)
|
||||
if (vid == RayNeoProtocol.GT_VENDOR_ID && !gt) return null
|
||||
if (!(vid == RayNeoProtocol.VENDOR_ID && pid == RayNeoProtocol.PRODUCT_ID) &&
|
||||
!gt &&
|
||||
!modelName.containsMatchIn(name.orEmpty())) return null
|
||||
return Model(name?.trim()?.takeIf { modelName.containsMatchIn(it) }
|
||||
?: if (gt) "RayNeo GT series" else "RayNeo Air")
|
||||
}
|
||||
|
||||
fun isDisplay(name: String): Boolean =
|
||||
name.contains("rayneo", ignoreCase = true) || name.contains("ray neo", ignoreCase = true) ||
|
||||
modelName.containsMatchIn(name)
|
||||
|
||||
// Observed on GT Max: Android exposes an unbranded EDID monitor name.
|
||||
// Match its product metadata, not every display called SmartGlasses/TCL.
|
||||
fun isDisplayProduct(name: String?, manufacturer: String?, productId: String?): Boolean =
|
||||
name?.trim().equals("SmartGlasses", ignoreCase = true) &&
|
||||
manufacturer.equals("TCL", ignoreCase = true) && productId == "980"
|
||||
|
||||
private class Model(override val name: String) : GlassesModel {
|
||||
override val controllable = true
|
||||
override val brightnessMax = 0
|
||||
override val volumeMax = 0
|
||||
override val diagonalFovDeg = 46f // Conservative existing default, not a calibrated model profile.
|
||||
override val sbs90 = false
|
||||
override fun mode(hz: Int, sbs: Boolean) =
|
||||
if (sbs) RayNeoProtocol.CMD_SWITCH_TO_3D else RayNeoProtocol.CMD_SWITCH_TO_2D
|
||||
override fun modeForStep(step: Int): Int? = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0).
|
||||
// See docs/third-party/rayneo/. Returns scaffold quaternions in (w, x, y, z) order.
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
internal data class Vec3(val x: Float, val y: Float, val z: Float) {
|
||||
fun length(): Float = sqrt(x * x + y * y + z * z)
|
||||
|
||||
fun normalized(): Vec3 {
|
||||
val n = length()
|
||||
if (n < 1e-6f) {
|
||||
return Vec3(0f, 0f, 0f)
|
||||
}
|
||||
return Vec3(x / n, y / n, z / n)
|
||||
}
|
||||
|
||||
fun cross(other: Vec3): Vec3 {
|
||||
return Vec3(
|
||||
y * other.z - z * other.y,
|
||||
z * other.x - x * other.z,
|
||||
x * other.y - y * other.x
|
||||
)
|
||||
}
|
||||
|
||||
operator fun plus(other: Vec3): Vec3 = Vec3(x + other.x, y + other.y, z + other.z)
|
||||
operator fun minus(other: Vec3): Vec3 = Vec3(x - other.x, y - other.y, z - other.z)
|
||||
operator fun times(scale: Float): Vec3 = Vec3(x * scale, y * scale, z * scale)
|
||||
}
|
||||
|
||||
internal data class Quaternion(val w: Float, val x: Float, val y: Float, val z: Float) {
|
||||
operator fun times(other: Quaternion): Quaternion {
|
||||
return Quaternion(
|
||||
w = w * other.w - x * other.x - y * other.y - z * other.z,
|
||||
x = w * other.x + x * other.w + y * other.z - z * other.y,
|
||||
y = w * other.y - x * other.z + y * other.w + z * other.x,
|
||||
z = w * other.z + x * other.y - y * other.x + z * other.w
|
||||
)
|
||||
}
|
||||
|
||||
operator fun times(scale: Float): Quaternion {
|
||||
return Quaternion(w * scale, x * scale, y * scale, z * scale)
|
||||
}
|
||||
|
||||
fun normalized(): Quaternion {
|
||||
val n = sqrt(w * w + x * x + y * y + z * z)
|
||||
if (n < 1e-6f) {
|
||||
return IDENTITY
|
||||
}
|
||||
return Quaternion(w / n, x / n, y / n, z / n)
|
||||
}
|
||||
|
||||
fun conjugate(): Quaternion = Quaternion(w, -x, -y, -z)
|
||||
|
||||
fun rotate(v: Vec3): Vec3 {
|
||||
val qv = Quaternion(0f, v.x, v.y, v.z)
|
||||
val r = this * qv * conjugate()
|
||||
return Vec3(r.x, r.y, r.z)
|
||||
}
|
||||
|
||||
fun integrateBodyRate(omegaRadPerSec: Vec3, dtSec: Float): Quaternion {
|
||||
val omega = Quaternion(0f, omegaRadPerSec.x, omegaRadPerSec.y, omegaRadPerSec.z)
|
||||
val qDot = (this * omega) * 0.5f
|
||||
return Quaternion(
|
||||
w + qDot.w * dtSec,
|
||||
x + qDot.x * dtSec,
|
||||
y + qDot.y * dtSec,
|
||||
z + qDot.z * dtSec
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
val IDENTITY = Quaternion(1f, 0f, 0f, 0f)
|
||||
|
||||
fun fromAxisAngle(axis: Vec3, angleRad: Float): Quaternion {
|
||||
val nAxis = axis.normalized()
|
||||
val half = angleRad * 0.5f
|
||||
val s = sin(half)
|
||||
val c = cos(half)
|
||||
return Quaternion(c, nAxis.x * s, nAxis.y * s, nAxis.z * s).normalized()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class RayNeoSensorProfile(val rotationXDeg: Float, val gtMaxAxes: Boolean) {
|
||||
companion object {
|
||||
fun forDevice(gtUsb: Boolean, boardId: Int) = when {
|
||||
gtUsb && boardId == RayNeoProtocol.BOARD_GT -> RayNeoSensorProfile(-25f, false)
|
||||
gtUsb -> RayNeoSensorProfile(35f, true)
|
||||
boardId == RayNeoProtocol.BOARD_AIR_4_PRO -> RayNeoSensorProfile(-20f, false)
|
||||
else -> RayNeoSensorProfile(0f, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class RayNeoSensorAxes(imuRotationXDeg: Float, private val gt: Boolean) {
|
||||
private val rotation = Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f),
|
||||
Math.toRadians((if (gt) 35f else imuRotationXDeg).toDouble()).toFloat())
|
||||
|
||||
fun map(v: Vec3): Vec3 = rotation.rotate(if (gt) Vec3(-v.y, v.z, -v.x) else v)
|
||||
}
|
||||
|
||||
internal class RayNeoOrientationFilter(
|
||||
imuRotationXDeg: Float,
|
||||
gt: Boolean = false,
|
||||
private val calibration: RayNeoCalibration? = null,
|
||||
) {
|
||||
private val worldUp = Vec3(0f, 1f, 0f)
|
||||
private val accelGain = 1.5f
|
||||
private val dpsToRad = (Math.PI.toFloat() / 180f)
|
||||
private val gravityMps2 = 9.81f
|
||||
private val stationaryAccelTol = 1.25f
|
||||
private val stationaryGyroRadPerSec = 0.18f
|
||||
private val gyroBiasUpdateHz = 0.5f
|
||||
private val axes = RayNeoSensorAxes(imuRotationXDeg, gt)
|
||||
|
||||
private var q = Quaternion.IDENTITY
|
||||
private var gravityInitialized = false
|
||||
private var gyroBias = Vec3(0f, 0f, 0f)
|
||||
private var lastTick100us: Long = -1L
|
||||
private var lastRealtimeNs: Long = 0L
|
||||
|
||||
companion object {
|
||||
/** Scaffold: right +X, up +Y, back +Z. VITURE: right -Y, up +Z, back -X.
|
||||
* Conjugate by HeadPose.GLASSES_AXES before entering the unchanged VITURE pose path.
|
||||
* This is a basis conversion, not a projection or seated-origin adjustment.
|
||||
*/
|
||||
fun glassesPose(wxyz: FloatArray): FloatArray =
|
||||
floatArrayOf(-wxyz[3], -wxyz[1], wxyz[2], wxyz[0])
|
||||
}
|
||||
|
||||
fun update(sample: RayNeoSensorSample): FloatArray {
|
||||
var accel = Vec3(sample.accelMps2[0], sample.accelMps2[1], sample.accelMps2[2])
|
||||
var gyro = Vec3(sample.gyroDps[0], sample.gyroDps[1], sample.gyroDps[2])
|
||||
calibration?.let { gyro -= it.gyroBiasDps }
|
||||
accel = axes.map(accel)
|
||||
gyro = axes.map(gyro) * dpsToRad
|
||||
calibration?.let {
|
||||
accel = it.level.rotate(accel)
|
||||
gyro = it.level.rotate(gyro)
|
||||
}
|
||||
|
||||
val nowNs = System.nanoTime()
|
||||
var dtSec = 0.01f
|
||||
if (lastTick100us >= 0L && sample.deviceTick100us != lastTick100us) {
|
||||
dtSec = (((sample.deviceTick100us - lastTick100us) and 0xffffffffL).toFloat() * 1e-4f)
|
||||
} else if (lastRealtimeNs > 0L && nowNs > lastRealtimeNs) {
|
||||
dtSec = ((nowNs - lastRealtimeNs).toFloat() * 1e-9f)
|
||||
}
|
||||
if (dtSec < 0.001f || dtSec > 0.1f) {
|
||||
dtSec = 0.01f
|
||||
}
|
||||
lastTick100us = sample.deviceTick100us
|
||||
lastRealtimeNs = nowNs
|
||||
|
||||
val accelNorm = accel.length()
|
||||
val stationary =
|
||||
kotlin.math.abs(accelNorm - gravityMps2) < stationaryAccelTol &&
|
||||
gyro.length() < stationaryGyroRadPerSec
|
||||
if (stationary) {
|
||||
val alpha = minOf(1f, dtSec * gyroBiasUpdateHz)
|
||||
gyroBias = gyroBias * (1f - alpha) + gyro * alpha
|
||||
}
|
||||
gyro -= gyroBias
|
||||
|
||||
if (accelNorm > 1e-3f) {
|
||||
val measuredUp = accel.normalized()
|
||||
if (!gravityInitialized) {
|
||||
// Align gravity before publishing the first pose. Starting at
|
||||
// identity and settling after recenter can rotate the horizon.
|
||||
val axis = measuredUp.cross(worldUp)
|
||||
q = if (measuredUp.y < -0.9999f) {
|
||||
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.PI.toFloat())
|
||||
} else {
|
||||
Quaternion(1f + measuredUp.y, axis.x, axis.y, axis.z).normalized()
|
||||
}
|
||||
gravityInitialized = true
|
||||
}
|
||||
val predictedUp = q.conjugate().rotate(worldUp).normalized()
|
||||
// q maps body to world: measured x predicted reduces gravity error.
|
||||
val correction = measuredUp.cross(predictedUp)
|
||||
gyro += correction * accelGain
|
||||
}
|
||||
|
||||
q = q.integrateBodyRate(gyro, dtSec).normalized()
|
||||
return floatArrayOf(q.w, q.x, q.y, q.z)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
// Adapted from informalTechCode/RayNeo-Air-Series-3DoF-Scaffold (Apache-2.0).
|
||||
// See docs/third-party/rayneo/ for license and protocol attribution.
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.hardware.usb.UsbConstants
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbEndpoint
|
||||
import android.hardware.usb.UsbInterface
|
||||
import java.util.Arrays
|
||||
|
||||
private fun Byte.u(): Int = toInt() and 0xFF
|
||||
|
||||
data class RayNeoSensorSample(
|
||||
val accelMps2: FloatArray,
|
||||
val gyroDps: FloatArray,
|
||||
val temperatureC: Float,
|
||||
val magnet: FloatArray,
|
||||
val proximity: Float,
|
||||
val light: Float,
|
||||
val deviceTick100us: Long
|
||||
)
|
||||
|
||||
data class RayNeoDeviceInfo(
|
||||
val boardId: Int,
|
||||
val sideBySideEnabled: Boolean
|
||||
)
|
||||
|
||||
sealed interface RayNeoPacket {
|
||||
data class Sensor(val sample: RayNeoSensorSample) : RayNeoPacket
|
||||
data class Response(val cmd: Int, val raw: ByteArray) : RayNeoPacket
|
||||
data object Unknown : RayNeoPacket
|
||||
}
|
||||
|
||||
data class RayNeoEndpointSelection(
|
||||
val usbInterface: UsbInterface,
|
||||
val inEndpoint: UsbEndpoint,
|
||||
val outEndpoint: UsbEndpoint
|
||||
)
|
||||
|
||||
object RayNeoProtocol {
|
||||
const val VENDOR_ID = 0x1BBB
|
||||
const val PRODUCT_ID = 0xAF50
|
||||
// verncat/RayNeo-Air-3S-Pro-OpenVR PR #3 (MIT), tested on GT hardware.
|
||||
const val GT_VENDOR_ID = 0x3941
|
||||
private const val GT_CONTROL_INTERFACE = 5
|
||||
|
||||
fun isGt(vid: Int, pid: Int) = vid == GT_VENDOR_ID && pid == PRODUCT_ID
|
||||
|
||||
const val BOARD_AIR_4_PRO = 0x3A
|
||||
const val BOARD_GT = 0x40 // Observed on the user's non-Max GT.
|
||||
|
||||
const val PKT_MAGIC = 0x99
|
||||
const val PKT_SENSOR = 0x65
|
||||
const val PKT_RESPONSE = 0xC8
|
||||
|
||||
const val CMD_ACQUIRE_DEVICE_INFO = 0
|
||||
const val CMD_OPEN_IMU = 1
|
||||
const val CMD_CLOSE_IMU = 2
|
||||
const val CMD_SWITCH_TO_3D = 6
|
||||
const val CMD_SWITCH_TO_2D = 7
|
||||
|
||||
private const val RESPONSE_CMD_OFFSET = 8
|
||||
|
||||
private const val ACCEL_OFFSET = 4
|
||||
private const val GYRO_OFFSET = 16
|
||||
private const val TEMP_OFFSET = 28
|
||||
private const val MAG_X_OFFSET = 32
|
||||
private const val TICK_OFFSET = 40
|
||||
private const val PSENSOR_OFFSET = 44
|
||||
private const val LSENSOR_OFFSET = 48
|
||||
private const val MAG_Z_OFFSET = 52
|
||||
|
||||
private const val DEVINFO_BOARD_ID_OFFSET = 21
|
||||
private const val DEVINFO_SIDE_BY_SIDE_OFFSET = 43
|
||||
|
||||
fun buildCommandPacket(cmd: Int, arg: Int, packetSize: Int): ByteArray {
|
||||
val len = maxOf(packetSize, 64)
|
||||
val pkt = ByteArray(len)
|
||||
pkt[0] = 0x66
|
||||
pkt[1] = cmd.toByte()
|
||||
pkt[2] = arg.toByte()
|
||||
return pkt
|
||||
}
|
||||
|
||||
fun classifyPacket(raw: ByteArray): RayNeoPacket {
|
||||
if (raw.size < 4 || raw[0].u() != PKT_MAGIC || raw[2].u() != raw.size) {
|
||||
return RayNeoPacket.Unknown
|
||||
}
|
||||
|
||||
return when (raw[1].u()) {
|
||||
PKT_SENSOR -> {
|
||||
val sample = parseSensorSample(raw)
|
||||
if (sample != null) RayNeoPacket.Sensor(sample) else RayNeoPacket.Unknown
|
||||
}
|
||||
PKT_RESPONSE -> {
|
||||
if (raw.size <= RESPONSE_CMD_OFFSET) {
|
||||
RayNeoPacket.Unknown
|
||||
} else {
|
||||
RayNeoPacket.Response(raw[RESPONSE_CMD_OFFSET].u(), raw)
|
||||
}
|
||||
}
|
||||
else -> RayNeoPacket.Unknown
|
||||
}
|
||||
}
|
||||
|
||||
fun parseDeviceInfo(raw: ByteArray): RayNeoDeviceInfo? {
|
||||
if (raw.size <= DEVINFO_SIDE_BY_SIDE_OFFSET || raw[2].u() != raw.size || raw[0].u() != PKT_MAGIC ||
|
||||
raw[1].u() != PKT_RESPONSE || raw[RESPONSE_CMD_OFFSET].u() != CMD_ACQUIRE_DEVICE_INFO) {
|
||||
return null
|
||||
}
|
||||
|
||||
return RayNeoDeviceInfo(
|
||||
boardId = raw[DEVINFO_BOARD_ID_OFFSET].u(),
|
||||
sideBySideEnabled = raw[DEVINFO_SIDE_BY_SIDE_OFFSET].u() != 0
|
||||
)
|
||||
}
|
||||
|
||||
fun selectEndpoints(device: UsbDevice): RayNeoEndpointSelection? {
|
||||
val gt = isGt(device.vendorId, device.productId)
|
||||
val gtCandidates = mutableListOf<RayNeoEndpointSelection>()
|
||||
var fallback: RayNeoEndpointSelection? = null
|
||||
|
||||
for (i in 0 until device.interfaceCount) {
|
||||
val usbInterface = device.getInterface(i)
|
||||
var inEndpoint: UsbEndpoint? = null
|
||||
var outEndpoint: UsbEndpoint? = null
|
||||
|
||||
for (j in 0 until usbInterface.endpointCount) {
|
||||
val endpoint = usbInterface.getEndpoint(j)
|
||||
if (endpoint.type != UsbConstants.USB_ENDPOINT_XFER_INT &&
|
||||
endpoint.type != UsbConstants.USB_ENDPOINT_XFER_BULK) {
|
||||
continue
|
||||
}
|
||||
// Exclude small button reports from GT's protocol transport.
|
||||
if (gt && endpoint.maxPacketSize < 64) continue
|
||||
|
||||
if (endpoint.direction == UsbConstants.USB_DIR_IN && inEndpoint == null) {
|
||||
inEndpoint = endpoint
|
||||
} else if (endpoint.direction == UsbConstants.USB_DIR_OUT && outEndpoint == null) {
|
||||
outEndpoint = endpoint
|
||||
}
|
||||
}
|
||||
|
||||
if (inEndpoint != null && outEndpoint != null) {
|
||||
val selection = RayNeoEndpointSelection(usbInterface, inEndpoint, outEndpoint)
|
||||
if (gt) {
|
||||
if (usbInterface.id == GT_CONTROL_INTERFACE) return selection
|
||||
gtCandidates += selection
|
||||
continue
|
||||
}
|
||||
if (inEndpoint.type == UsbConstants.USB_ENDPOINT_XFER_INT &&
|
||||
outEndpoint.type == UsbConstants.USB_ENDPOINT_XFER_INT
|
||||
) {
|
||||
return selection
|
||||
}
|
||||
if (fallback == null) {
|
||||
fallback = selection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Interface numbers can change with firmware. Use a unique protocol-sized
|
||||
// pair when interface 5 is absent, never an arbitrary composite interface.
|
||||
return if (gt) gtCandidates.singleOrNull() else fallback
|
||||
}
|
||||
|
||||
private fun parseSensorSample(raw: ByteArray): RayNeoSensorSample? {
|
||||
if (raw.size < MAG_Z_OFFSET + 4 ||
|
||||
(ACCEL_OFFSET until TEMP_OFFSET step 4).any { !readF32LE(raw, it).isFinite() }) {
|
||||
return null
|
||||
}
|
||||
|
||||
return RayNeoSensorSample(
|
||||
accelMps2 = floatArrayOf(
|
||||
readF32LE(raw, ACCEL_OFFSET + 0),
|
||||
readF32LE(raw, ACCEL_OFFSET + 4),
|
||||
readF32LE(raw, ACCEL_OFFSET + 8)
|
||||
),
|
||||
gyroDps = floatArrayOf(
|
||||
readF32LE(raw, GYRO_OFFSET + 0),
|
||||
readF32LE(raw, GYRO_OFFSET + 4),
|
||||
readF32LE(raw, GYRO_OFFSET + 8)
|
||||
),
|
||||
temperatureC = readF32LE(raw, TEMP_OFFSET),
|
||||
magnet = floatArrayOf(
|
||||
readF32LE(raw, MAG_X_OFFSET),
|
||||
readF32LE(raw, MAG_X_OFFSET + 4),
|
||||
readF32LE(raw, MAG_Z_OFFSET)
|
||||
),
|
||||
proximity = readF32LE(raw, PSENSOR_OFFSET),
|
||||
light = readF32LE(raw, LSENSOR_OFFSET),
|
||||
deviceTick100us = readU32LE(raw, TICK_OFFSET).toLong() and 0xffffffffL
|
||||
)
|
||||
}
|
||||
|
||||
private fun readU32LE(raw: ByteArray, offset: Int): Int {
|
||||
val b0 = raw[offset].u()
|
||||
val b1 = raw[offset + 1].u()
|
||||
val b2 = raw[offset + 2].u()
|
||||
val b3 = raw[offset + 3].u()
|
||||
return b0 or (b1 shl 8) or (b2 shl 16) or (b3 shl 24)
|
||||
}
|
||||
|
||||
private fun readF32LE(raw: ByteArray, offset: Int): Float {
|
||||
return Float.fromBits(readU32LE(raw, offset))
|
||||
}
|
||||
}
|
||||
|
||||
class RayNeoPacketAssembler {
|
||||
private val stash = ByteArray(4096)
|
||||
private var len = 0
|
||||
|
||||
fun append(data: ByteArray, count: Int) {
|
||||
require(count in 0..data.size)
|
||||
if (count <= 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if (count >= stash.size || len + count > stash.size) {
|
||||
len = 0
|
||||
}
|
||||
|
||||
val copyLen = minOf(count, stash.size - len)
|
||||
System.arraycopy(data, 0, stash, len, copyLen)
|
||||
len += copyLen
|
||||
}
|
||||
|
||||
fun nextPacket(): ByteArray? {
|
||||
var offset = 0
|
||||
while (offset + 4 <= len) {
|
||||
if (stash[offset].u() != RayNeoProtocol.PKT_MAGIC) {
|
||||
offset++
|
||||
continue
|
||||
}
|
||||
|
||||
val packetLen = stash[offset + 2].u()
|
||||
if (packetLen < 4 || packetLen > 64 ||
|
||||
stash[offset + 1].u() !in listOf(RayNeoProtocol.PKT_SENSOR, RayNeoProtocol.PKT_RESPONSE)) {
|
||||
offset++
|
||||
continue
|
||||
}
|
||||
if (offset + packetLen > len) {
|
||||
break
|
||||
}
|
||||
|
||||
val packet = Arrays.copyOfRange(stash, offset, offset + packetLen)
|
||||
compact(offset + packetLen)
|
||||
return packet
|
||||
}
|
||||
|
||||
if (offset > 0) {
|
||||
compact(offset)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun compact(consumed: Int) {
|
||||
if (consumed <= 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if (consumed >= len) {
|
||||
len = 0
|
||||
return
|
||||
}
|
||||
|
||||
System.arraycopy(stash, consumed, stash, 0, len - consumed)
|
||||
len -= consumed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
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.os.SystemClock
|
||||
import android.util.Log
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
internal class VitureLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val mcu: UsbInterface,
|
||||
private val mcuOut: UsbEndpoint,
|
||||
private val mcuIn: UsbEndpoint?,
|
||||
private val imu: UsbInterface?,
|
||||
private val imuIn: UsbEndpoint?,
|
||||
private val listener: Listener,
|
||||
) : GlassesLink {
|
||||
interface Listener {
|
||||
fun onFrame(frame: VitureProtocol.Frame)
|
||||
fun onImu(payload: ByteArray, timeNs: Long)
|
||||
fun onLost()
|
||||
}
|
||||
|
||||
@Volatile private var running = true
|
||||
private val writeLock = Any()
|
||||
private var lastSendAt = 0L
|
||||
private val readers = mutableListOf<Thread>()
|
||||
private val bad = AtomicLong()
|
||||
|
||||
override val hasImu: Boolean get() = imuIn != null
|
||||
override val badFrames: Long get() = bad.get()
|
||||
|
||||
private fun startReaders() {
|
||||
mcuIn?.let { ep -> readers += reader("viture-mcu", ep) { buf, n -> onPacket(buf, n, false) } }
|
||||
imuIn?.let { ep ->
|
||||
readers += reader("viture-imu", ep) { buf, n -> onPacket(buf, n, true) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun onPacket(buf: ByteArray, size: Int, imuEndpoint: Boolean) {
|
||||
val frame = VitureProtocol.parse(buf, size) ?: return
|
||||
if (!frame.crcOk) {
|
||||
if (bad.incrementAndGet() == 1L) Log.w(TAG, "dropping frames with a bad checksum")
|
||||
return
|
||||
}
|
||||
if (imuEndpoint && frame.magic == VitureProtocol.MAGIC_IMU)
|
||||
listener.onImu(frame.payload, SystemClock.elapsedRealtimeNanos())
|
||||
else listener.onFrame(frame)
|
||||
}
|
||||
|
||||
private fun reader(name: String, ep: UsbEndpoint, onPacket: (ByteArray, Int) -> Unit): Thread =
|
||||
Thread({
|
||||
val buf = ByteArray(VitureProtocol.PACKET_SIZE)
|
||||
var failures = 0
|
||||
while (running) {
|
||||
val started = SystemClock.uptimeMillis()
|
||||
val n = connection.bulkTransfer(ep, buf, buf.size, READ_TIMEOUT_MS)
|
||||
if (!running) break
|
||||
if (n > 0) {
|
||||
failures = 0
|
||||
runCatching { onPacket(buf, n) }.onFailure { Log.w(TAG, "$name packet", it) }
|
||||
} else if (n < 0 && SystemClock.uptimeMillis() - started < READ_TIMEOUT_MS / 2) {
|
||||
failures++
|
||||
SystemClock.sleep(2)
|
||||
if (failures >= LOST_AFTER) {
|
||||
Log.w(TAG, "$name: reads keep failing, link lost")
|
||||
if (running) listener.onLost()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}, name).apply { isDaemon = true; priority = Thread.MAX_PRIORITY; start() }
|
||||
|
||||
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
||||
val pkt = VitureProtocol.packet(msgId, payload)
|
||||
val n = synchronized(writeLock) {
|
||||
if (!running) return false
|
||||
val wait = lastSendAt + COMMAND_GAP_MS - SystemClock.uptimeMillis()
|
||||
if (wait > 0) SystemClock.sleep(wait)
|
||||
connection.bulkTransfer(mcuOut, pkt, pkt.size, WRITE_TIMEOUT_MS).also { lastSendAt = SystemClock.uptimeMillis() }
|
||||
}
|
||||
Log.i(TAG, "send 0x%04X [%s] -> %d".format(msgId, payload.joinToString("") { "%02X".format(it) }, n))
|
||||
return n == pkt.size
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
synchronized(writeLock) { running = false }
|
||||
val self = Thread.currentThread()
|
||||
readers.forEach { if (it !== self) runCatching { it.join(READ_TIMEOUT_MS * 4L) } }
|
||||
runCatching { connection.releaseInterface(mcu) }
|
||||
imu?.let { runCatching { connection.releaseInterface(it) } }
|
||||
runCatching { connection.close() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "VitureLink"
|
||||
private const val READ_TIMEOUT_MS = 100
|
||||
private const val WRITE_TIMEOUT_MS = 250
|
||||
private const val LOST_AFTER = 50
|
||||
const val COMMAND_GAP_MS = 60L
|
||||
|
||||
fun open(usb: UsbManager, device: UsbDevice, listener: Listener): VitureLink? {
|
||||
val hid = (0 until device.interfaceCount).map(device::getInterface)
|
||||
.filter { it.interfaceClass == UsbConstants.USB_CLASS_HID }
|
||||
.sortedBy { it.id }
|
||||
for (intf in hid) Log.i(TAG, "iface ${intf.id} eps " + (0 until intf.endpointCount).joinToString {
|
||||
val ep = intf.getEndpoint(it)
|
||||
"0x%02X".format(ep.address)
|
||||
})
|
||||
val mcu = hid.lastOrNull { it.outEndpoint() != null } ?: return null
|
||||
val imu = hid.firstOrNull { it.id != mcu.id && it.inEndpoint() != null }
|
||||
val conn = usb.openDevice(device) ?: return null
|
||||
if (!conn.claimInterface(mcu, true)) {
|
||||
conn.close()
|
||||
return null
|
||||
}
|
||||
val imuClaimed = imu != null && conn.claimInterface(imu, true)
|
||||
val link = VitureLink(conn, mcu, mcu.outEndpoint()!!, mcu.inEndpoint(),
|
||||
imu.takeIf { imuClaimed }, imu.takeIf { imuClaimed }?.inEndpoint(), listener)
|
||||
link.startReaders()
|
||||
return link
|
||||
}
|
||||
|
||||
private fun UsbInterface.outEndpoint(): UsbEndpoint? = (0 until endpointCount).map(::getEndpoint)
|
||||
.firstOrNull { it.direction == UsbConstants.USB_DIR_OUT && it.type == UsbConstants.USB_ENDPOINT_XFER_INT }
|
||||
|
||||
private fun UsbInterface.inEndpoint(): UsbEndpoint? = (0 until endpointCount).map(::getEndpoint)
|
||||
.firstOrNull { it.direction == UsbConstants.USB_DIR_IN && it.type == UsbConstants.USB_ENDPOINT_XFER_INT }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
object VitureProtocol {
|
||||
const val VENDOR_ID = 0x35CA
|
||||
const val PACKET_SIZE = 64
|
||||
private const val HEADER = 0x12
|
||||
|
||||
const val MAGIC_COMMAND = 0xFE
|
||||
const val MAGIC_REPORT = 0xFD
|
||||
const val MAGIC_IMU = 0xFC
|
||||
|
||||
const val MSG_GET_BRIGHTNESS = 0x0005
|
||||
const val MSG_BRIGHTNESS = 0x0006
|
||||
const val MSG_GET_DISPLAY = 0x0007
|
||||
const val MSG_DISPLAY = 0x0008
|
||||
const val MSG_FILM = 0x000E
|
||||
const val MSG_IMU = 0x0015
|
||||
const val MSG_GET_IMU = 0x0017
|
||||
const val MSG_IMU_RATE = 0x0018
|
||||
const val MSG_GET_VOLUME = 0x0032
|
||||
const val MSG_VOLUME = 0x0033
|
||||
|
||||
const val EVENT_BRIGHTNESS = 0x0301
|
||||
const val EVENT_DISPLAY = 0x0302
|
||||
const val EVENT_VOLUME = 0x0304
|
||||
const val EVENT_DISPLAY_STEP = 0x030D
|
||||
|
||||
const val IMU_RATE_240 = 3
|
||||
|
||||
enum class Family { ONE, PRO, LUMA, ULTRA, BEAST, PRO2 }
|
||||
|
||||
class Model(override val name: String, val family: Family) : GlassesModel {
|
||||
override val controllable: Boolean get() = true
|
||||
val needsSdk: Boolean get() = family == Family.ULTRA || family == Family.BEAST || family == Family.PRO2
|
||||
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 hasSunblock: Boolean get() = family != Family.PRO2
|
||||
override val diagonalFovDeg: Float get() = when (family) {
|
||||
Family.ONE -> 43f
|
||||
Family.PRO -> 46f
|
||||
Family.PRO2, Family.LUMA, Family.ULTRA -> 50f
|
||||
Family.BEAST -> 58f
|
||||
}
|
||||
|
||||
override fun mode(hz: Int, sbs: Boolean): Int = when {
|
||||
tall && sbs -> if (hz >= 90 && sbs90) 0x45 else 0x42
|
||||
tall -> when { hz >= 120 -> 0x44; hz >= 90 -> 0x43; else -> 0x41 }
|
||||
sbs -> if (hz >= 90 && sbs90) 0x35 else 0x32
|
||||
else -> when { hz >= 120 -> 0x34; hz >= 90 -> 0x33; else -> 0x31 }
|
||||
}
|
||||
|
||||
override fun modeForStep(step: Int): Int? = if (tall) null else when (step) {
|
||||
1 -> 0x31
|
||||
2 -> 0x33
|
||||
3 -> 0x34
|
||||
4 -> 0x32
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** SDK validates the PID before returning this market name. Never guess a new PID. */
|
||||
fun sdkModel(marketName: String): Model? {
|
||||
val family = when (marketName) {
|
||||
"One", "Lite" -> Family.ONE
|
||||
"Pro" -> Family.PRO
|
||||
"Pro 2" -> Family.PRO2
|
||||
"Luma", "Luma Pro", "Luma Cyber" -> Family.LUMA
|
||||
"Luma Ultra" -> Family.ULTRA
|
||||
"Beast" -> Family.BEAST
|
||||
else -> return null
|
||||
}
|
||||
return Model("VITURE $marketName", family)
|
||||
}
|
||||
|
||||
fun model(productId: Int, productName: String?): Model? {
|
||||
val family = when (productId) {
|
||||
0x1011, 0x1013, 0x1015, 0x1017, 0x101b -> Family.ONE
|
||||
0x1019, 0x101d -> Family.PRO
|
||||
0x1121, 0x1131, 0x1141, 0x1151 -> Family.LUMA
|
||||
0x1101, 0x1104 -> Family.ULTRA
|
||||
0x1201, 0x1211 -> Family.BEAST
|
||||
else -> return null
|
||||
}
|
||||
val fallback = when (productId) {
|
||||
0x1015, 0x101b -> "VITURE One Lite"
|
||||
0x1011, 0x1013, 0x1017 -> "VITURE One"
|
||||
0x1019 -> "VITURE Pro"
|
||||
0x101d -> "VITURE Pro XR"
|
||||
0x1131 -> "VITURE Luma"
|
||||
0x1121, 0x1141, 0x1151 -> "VITURE Luma Pro"
|
||||
0x1101, 0x1104 -> "VITURE Luma Ultra"
|
||||
else -> "VITURE Beast"
|
||||
}
|
||||
val name = productName?.trim()?.removeSuffix(" Glasses")?.takeIf { it.startsWith("VITURE", ignoreCase = true) } ?: fallback
|
||||
return Model(name, family)
|
||||
}
|
||||
|
||||
private val CRC_TABLE = IntArray(256) { i ->
|
||||
var c = i shl 8
|
||||
repeat(8) { c = if (c and 0x8000 != 0) (c shl 1) xor 0x1021 else c shl 1 }
|
||||
c and 0xFFFF
|
||||
}
|
||||
|
||||
fun crc16(data: ByteArray, offset: Int, length: Int): Int {
|
||||
var crc = 0
|
||||
for (i in offset until offset + length) {
|
||||
crc = (CRC_TABLE[((data[i].toInt() and 0xFF) xor (crc ushr 8)) and 0xFF] xor (crc shl 8)) and 0xFFFF
|
||||
}
|
||||
return crc
|
||||
}
|
||||
|
||||
fun packet(msgId: Int, payload: ByteArray = ByteArray(0)): ByteArray {
|
||||
require(payload.size <= PACKET_SIZE - HEADER)
|
||||
val buf = ByteArray(PACKET_SIZE)
|
||||
buf[0] = 0xFF.toByte()
|
||||
buf[1] = MAGIC_COMMAND.toByte()
|
||||
val len = payload.size + 0x0C
|
||||
buf[4] = len.toByte()
|
||||
buf[5] = (len shr 8).toByte()
|
||||
buf[14] = msgId.toByte()
|
||||
buf[15] = (msgId shr 8).toByte()
|
||||
payload.copyInto(buf, HEADER)
|
||||
val crc = crc16(buf, 4, len + 2)
|
||||
buf[2] = crc.toByte()
|
||||
buf[3] = (crc shr 8).toByte()
|
||||
return buf
|
||||
}
|
||||
|
||||
class Frame(val magic: Int, val msgId: Int, val payload: ByteArray, val crcOk: Boolean)
|
||||
|
||||
fun parse(buf: ByteArray, size: Int): Frame? {
|
||||
if (size < HEADER || size > buf.size || (buf[0].toInt() and 0xFF) != 0xFF) return null
|
||||
val magic = buf[1].toInt() and 0xFF
|
||||
if (magic != MAGIC_COMMAND && magic != MAGIC_REPORT && magic != MAGIC_IMU) return null
|
||||
val len = u16(buf, 4)
|
||||
if (len < 0x0C || len + 6 > size) return null
|
||||
val dataLen = len - 0x0C
|
||||
val crcOk = crc16(buf, 4, len + 2) == u16(buf, 2)
|
||||
return Frame(magic, u16(buf, 14), buf.copyOfRange(HEADER, HEADER + dataLen), crcOk)
|
||||
}
|
||||
|
||||
private fun u16(buf: ByteArray, at: Int) = (buf[at].toInt() and 0xFF) or ((buf[at + 1].toInt() and 0xFF) shl 8)
|
||||
|
||||
fun beFloat(b: ByteArray, at: Int): Float = java.lang.Float.intBitsToFloat(
|
||||
((b[at].toInt() and 0xFF) shl 24) or ((b[at + 1].toInt() and 0xFF) shl 16) or
|
||||
((b[at + 2].toInt() and 0xFF) shl 8) or (b[at + 3].toInt() and 0xFF),
|
||||
)
|
||||
|
||||
fun imuQuaternion(payload: ByteArray): FloatArray? {
|
||||
if (payload.size >= 36) {
|
||||
val w = beFloat(payload, 20)
|
||||
val x = beFloat(payload, 24)
|
||||
val y = beFloat(payload, 28)
|
||||
val z = beFloat(payload, 32)
|
||||
val n = sqrt(w * w + x * x + y * y + z * z)
|
||||
if (n.isFinite() && n > 0.9f && n < 1.1f) return floatArrayOf(x / n, y / n, z / n, w / n)
|
||||
}
|
||||
if (payload.size < 12) return null
|
||||
val roll = beFloat(payload, 0)
|
||||
val pitch = beFloat(payload, 4)
|
||||
val yaw = beFloat(payload, 8)
|
||||
if (!roll.isFinite() || !pitch.isFinite() || !yaw.isFinite()) return null
|
||||
return eulerZxy(roll, pitch, yaw)
|
||||
}
|
||||
|
||||
fun eulerZxy(rollDeg: Float, pitchDeg: Float, yawDeg: Float): FloatArray {
|
||||
val r = Math.toRadians(rollDeg.toDouble()) / 2
|
||||
val p = Math.toRadians(pitchDeg.toDouble()) / 2
|
||||
val y = Math.toRadians(yawDeg.toDouble()) / 2
|
||||
val cx = cos(r); val sx = sin(r)
|
||||
val cy = cos(p); val sy = sin(p)
|
||||
val cz = cos(y); val sz = sin(y)
|
||||
return floatArrayOf(
|
||||
(sx * cy * cz - cx * sy * sz).toFloat(),
|
||||
(cx * sy * cz + sx * cy * sz).toFloat(),
|
||||
(cx * cy * sz + sx * sy * cz).toFloat(),
|
||||
(cx * cy * cz - sx * sy * sz).toFloat(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.util.Log
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** JNI adapter to VITURE's Android C SDK. The vendor binary is a local build input. */
|
||||
internal object VitureSdk {
|
||||
val available: Boolean by lazy {
|
||||
runCatching {
|
||||
System.loadLibrary("droiddeck_viture")
|
||||
nativeAvailable()
|
||||
}.onFailure { Log.w("VitureSdk", "VITURE driver unavailable", it) }.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun marketName(pid: Int): String? = if (available) nativeMarketName(pid) else null
|
||||
external fun nativeAvailable(): Boolean
|
||||
external fun nativeMarketName(pid: Int): String?
|
||||
external fun nativeOpen(pid: Int, fd: Int, cacheDirectory: String): Long
|
||||
external fun nativeType(token: Long): Int
|
||||
external fun nativeTracking(token: Long, enabled: Boolean): Int
|
||||
external fun nativeCommand(token: Long, command: Int, value: Int): Int
|
||||
/** Returns CLOCK_BOOTTIME receipt time, zero for no new pose, or a negative SDK error. */
|
||||
external fun nativePose(token: Long, wxyz: FloatArray): Long
|
||||
external fun nativeNextState(token: Long, event: IntArray): Int
|
||||
external fun nativeClose(token: Long)
|
||||
|
||||
const val CARINA = 2
|
||||
const val GET_DISPLAY = 1
|
||||
const val SET_DISPLAY = 2
|
||||
const val GET_BRIGHTNESS = 3
|
||||
const val SET_BRIGHTNESS = 4
|
||||
const val GET_VOLUME = 5
|
||||
const val SET_VOLUME = 6
|
||||
const val SET_FILM = 7
|
||||
}
|
||||
|
||||
internal object VitureSdkPose {
|
||||
// Pro 2 hardware captures use OpenGL axes despite the generic Gen2 callback's
|
||||
// NWU documentation. Keep that model-specific exception out of other Gen2 devices.
|
||||
fun usesOpenGlAxes(carina: Boolean, family: VitureProtocol.Family?) =
|
||||
carina || family == VitureProtocol.Family.PRO2
|
||||
|
||||
/** SDK quaternions are wxyz; normalize their coordinate basis at the boundary. */
|
||||
fun toGlasses(wxyz: FloatArray, openGlAxes: Boolean): FloatArray? {
|
||||
if (wxyz.size != 4 || wxyz.any { !it.isFinite() }) return null
|
||||
val length = sqrt(wxyz.sumOf { it.toDouble() * it }.toFloat())
|
||||
if (!length.isFinite() || length < 0.5f || length > 1.5f) return null
|
||||
val q = if (openGlAxes) floatArrayOf(-wxyz[3], -wxyz[1], wxyz[2], wxyz[0])
|
||||
else floatArrayOf(wxyz[1], wxyz[2], wxyz[3], wxyz[0])
|
||||
return q.map { it / length }.toFloatArray()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbDeviceConnection
|
||||
import android.hardware.usb.UsbManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/** SDK owns interface selection (including Ultra bulk endpoints) and all USB I/O. */
|
||||
internal class VitureSdkLink private constructor(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val token: Long,
|
||||
private val listener: Listener,
|
||||
family: VitureProtocol.Family?,
|
||||
) : GlassesLink {
|
||||
interface Listener {
|
||||
fun onValue(msgId: Int, value: Int)
|
||||
fun onPose(q: FloatArray, timeNs: Long)
|
||||
fun onLost()
|
||||
}
|
||||
|
||||
private val lock = Any()
|
||||
@Volatile private var running = true
|
||||
@Volatile private var tracking = false
|
||||
override val ready: Boolean get() = running
|
||||
override val hasImu = true
|
||||
private val openGlAxes = VitureSdkPose.usesOpenGlAxes(VitureSdk.nativeType(token) == VitureSdk.CARINA, family)
|
||||
private val worker = Thread({ poll() }, "viture-sdk-pose").apply { isDaemon = true; start() }
|
||||
|
||||
override fun send(msgId: Int, payload: ByteArray): Boolean = synchronized(lock) {
|
||||
if (!running) return false
|
||||
val value = payload.firstOrNull()?.toInt()?.and(0xff) ?: 0
|
||||
when (msgId) {
|
||||
VitureProtocol.MSG_IMU -> {
|
||||
val wanted = value != 0
|
||||
if (wanted == tracking) return true
|
||||
val rc = VitureSdk.nativeTracking(token, wanted)
|
||||
if (rc == 0 || !wanted) tracking = wanted
|
||||
return result("tracking", rc)
|
||||
}
|
||||
// Frequency is negotiated against SDK capabilities, including Pro 2's pose limit.
|
||||
VitureProtocol.MSG_IMU_RATE -> return tracking
|
||||
VitureProtocol.MSG_GET_IMU -> return true
|
||||
}
|
||||
val operation = when (msgId) {
|
||||
VitureProtocol.MSG_GET_DISPLAY -> VitureSdk.GET_DISPLAY
|
||||
VitureProtocol.MSG_DISPLAY -> VitureSdk.SET_DISPLAY
|
||||
VitureProtocol.MSG_GET_BRIGHTNESS -> VitureSdk.GET_BRIGHTNESS
|
||||
VitureProtocol.MSG_BRIGHTNESS -> VitureSdk.SET_BRIGHTNESS
|
||||
VitureProtocol.MSG_GET_VOLUME -> VitureSdk.GET_VOLUME
|
||||
VitureProtocol.MSG_VOLUME -> VitureSdk.SET_VOLUME
|
||||
VitureProtocol.MSG_FILM -> VitureSdk.SET_FILM
|
||||
else -> return false
|
||||
}
|
||||
val rc = VitureSdk.nativeCommand(token, operation, value)
|
||||
if (rc < 0) return result("command $operation", rc)
|
||||
if (operation == VitureSdk.GET_DISPLAY || operation == VitureSdk.GET_BRIGHTNESS || operation == VitureSdk.GET_VOLUME)
|
||||
listener.onValue(msgId, rc)
|
||||
else if (operation == VitureSdk.SET_DISPLAY) {
|
||||
val actual = VitureSdk.nativeCommand(token, VitureSdk.GET_DISPLAY, 0)
|
||||
if (actual >= 0) listener.onValue(VitureProtocol.MSG_GET_DISPLAY, actual)
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
private fun result(operation: String, rc: Int): Boolean {
|
||||
if (rc < 0) Log.w("VitureSdkLink", "$operation failed: $rc")
|
||||
return rc == 0
|
||||
}
|
||||
|
||||
private fun poll() {
|
||||
val pose = FloatArray(4)
|
||||
val event = IntArray(2)
|
||||
var failures = 0
|
||||
while (running) {
|
||||
val timestamp = synchronized(lock) {
|
||||
if (running) repeat(6) {
|
||||
if (VitureSdk.nativeNextState(token, event) == 1) when (event[0]) {
|
||||
0 -> listener.onValue(VitureProtocol.MSG_GET_BRIGHTNESS, event[1])
|
||||
1 -> listener.onValue(VitureProtocol.MSG_GET_VOLUME, event[1])
|
||||
// A device event can use a different display-mode namespace.
|
||||
2 -> send(VitureProtocol.MSG_GET_DISPLAY)
|
||||
3 -> listener.onValue(VitureProtocol.MSG_FILM, event[1])
|
||||
}
|
||||
}
|
||||
if (!running || !tracking) 0L else VitureSdk.nativePose(token, pose)
|
||||
}
|
||||
if (timestamp > 0) {
|
||||
failures = 0
|
||||
VitureSdkPose.toGlasses(pose, openGlAxes)?.let { listener.onPose(it, timestamp) }
|
||||
} else if (timestamp == -2L || timestamp == -3L) {
|
||||
if (++failures >= 10) {
|
||||
Log.w("VitureSdkLink", "closing after $failures pose USB errors; last SDK result: $timestamp")
|
||||
listener.onLost()
|
||||
break
|
||||
}
|
||||
}
|
||||
SystemClock.sleep(if (tracking) 4 else 25)
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
synchronized(lock) {
|
||||
if (!running) return
|
||||
running = false
|
||||
VitureSdk.nativeClose(token)
|
||||
// Keep Java's descriptor alive until the SDK and its worker threads have stopped.
|
||||
connection.close()
|
||||
}
|
||||
if (Thread.currentThread() !== worker) worker.join(1000)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun open(usb: UsbManager, device: UsbDevice, cacheDirectory: File, listener: Listener,
|
||||
family: VitureProtocol.Family? = null): VitureSdkLink? {
|
||||
if (!VitureSdk.available) return null
|
||||
val conn = usb.openDevice(device) ?: return null
|
||||
val token = runCatching {
|
||||
cacheDirectory.mkdirs()
|
||||
VitureSdk.nativeOpen(device.productId, conn.fileDescriptor, cacheDirectory.absolutePath)
|
||||
}.onFailure { Log.w("VitureSdkLink", "SDK initialization failed", it) }.getOrDefault(0)
|
||||
if (token <= 0) { conn.close(); return null }
|
||||
return runCatching { VitureSdkLink(conn, token, listener, family) }.getOrElse {
|
||||
VitureSdk.nativeClose(token)
|
||||
conn.close()
|
||||
Log.w("VitureSdkLink", "SDK worker could not start", it)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.NetworkCapabilities
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Socket
|
||||
|
||||
internal interface XrealChannels : Closeable {
|
||||
val controlInput: InputStream
|
||||
val controlOutput: OutputStream
|
||||
val reports: InputStream
|
||||
}
|
||||
|
||||
internal interface XrealConnector : Closeable {
|
||||
fun connect(): XrealChannels
|
||||
}
|
||||
|
||||
internal class XrealNetworkMissing : IOException("XREAL USB Ethernet network is not available")
|
||||
|
||||
/** Bind individual sockets, never the process: Steam must retain its Internet network. */
|
||||
internal class AndroidXrealConnector(context: Context) : XrealConnector {
|
||||
private val manager = context.getSystemService(ConnectivityManager::class.java)
|
||||
private val address = InetAddress.getByName(XrealProtocol.HOST)
|
||||
private val lock = Any()
|
||||
private val sockets = mutableSetOf<Socket>()
|
||||
private var closed = false
|
||||
|
||||
companion object {
|
||||
internal fun hasDirectRoute(properties: LinkProperties, address: InetAddress): Boolean =
|
||||
properties.routes.any { !it.hasGateway() && it.destination.prefixLength > 0 && it.matches(address) }
|
||||
}
|
||||
|
||||
override fun connect(): XrealChannels {
|
||||
val network = manager.allNetworks.firstOrNull { network ->
|
||||
manager.getNetworkCapabilities(network)?.let {
|
||||
it.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) &&
|
||||
!it.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
|
||||
} == true && manager.getLinkProperties(network)?.let { hasDirectRoute(it, address) } == true
|
||||
} ?: throw XrealNetworkMissing()
|
||||
fun open(port: Int): Socket {
|
||||
val socket = Socket()
|
||||
synchronized(lock) {
|
||||
if (closed) { socket.close(); throw IOException("XREAL connection closed") }
|
||||
sockets.add(socket)
|
||||
}
|
||||
try {
|
||||
network.bindSocket(socket)
|
||||
socket.soTimeout = 2000
|
||||
socket.tcpNoDelay = true
|
||||
socket.connect(InetSocketAddress(address, port), 1500)
|
||||
return socket
|
||||
} catch (e: Exception) {
|
||||
release(socket)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
val control = open(XrealProtocol.CONTROL_PORT)
|
||||
val reportSocket = try { open(XrealProtocol.REPORT_PORT) } catch (e: Exception) {
|
||||
release(control)
|
||||
throw e
|
||||
}
|
||||
return object : XrealChannels {
|
||||
override val controlInput = control.getInputStream()
|
||||
override val controlOutput = control.getOutputStream()
|
||||
override val reports = reportSocket.getInputStream()
|
||||
override fun close() { release(control); release(reportSocket) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun release(socket: Socket) = synchronized(lock) {
|
||||
runCatching { socket.close() }
|
||||
sockets.remove(socket)
|
||||
Unit
|
||||
}
|
||||
|
||||
override fun close() = synchronized(lock) {
|
||||
closed = true
|
||||
sockets.forEach { runCatching { it.close() } }
|
||||
sockets.clear()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/** One connection owns two TCP channels. All control requests are serialized off the UI thread. */
|
||||
internal class XrealLink internal constructor(
|
||||
private val connector: XrealConnector,
|
||||
private val listener: Listener,
|
||||
) : GlassesLink {
|
||||
interface Listener {
|
||||
fun onReady()
|
||||
fun onValue(message: Int, value: Int)
|
||||
fun onPose(raw: ByteArray, pose: FloatArray, timeNs: Long)
|
||||
fun onUnavailable(networkMissing: Boolean)
|
||||
}
|
||||
|
||||
private data class Command(val message: Int, val value: Int)
|
||||
private val commands = ArrayBlockingQueue<Command>(16)
|
||||
private val connection = AtomicReference<XrealChannels?>()
|
||||
@Volatile private var running = true
|
||||
@Volatile private var tracking = false
|
||||
@Volatile override var ready = false
|
||||
private set
|
||||
override val hasImu = true
|
||||
private val worker = Thread(::run, "xreal-control").apply { isDaemon = true; start() }
|
||||
|
||||
companion object {
|
||||
fun open(context: Context, listener: Listener) = XrealLink(AndroidXrealConnector(context), listener)
|
||||
}
|
||||
|
||||
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
||||
if (!running || !ready) return false
|
||||
val value = payload.firstOrNull()?.toInt()?.and(255) ?: -1
|
||||
if (msgId == VitureProtocol.MSG_IMU) {
|
||||
if (value !in 0..1) return false
|
||||
tracking = value == 1
|
||||
return true
|
||||
}
|
||||
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
||||
val valid = when (msgId) {
|
||||
VitureProtocol.MSG_GET_DISPLAY -> true
|
||||
VitureProtocol.MSG_DISPLAY -> value in 2..5 || value == XrealModel.NATIVE_60HZ
|
||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..9
|
||||
VitureProtocol.MSG_FILM -> value in 0..1
|
||||
else -> false // No guessed volume, sensor-rate, or VITURE wire commands.
|
||||
}
|
||||
return valid && commands.offer(Command(msgId, value))
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
var lastError: String? = null
|
||||
while (running) {
|
||||
var channels: XrealChannels? = null
|
||||
var reports: Thread? = null
|
||||
val failure = AtomicReference<Exception?>()
|
||||
try {
|
||||
channels = connector.connect()
|
||||
connection.set(channels)
|
||||
if (!running) break
|
||||
val control = XrealControl(channels)
|
||||
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
||||
val current = channels
|
||||
reports = Thread({
|
||||
try {
|
||||
var filter = XrealOrientationFilter()
|
||||
var wasTracking = false
|
||||
var lastSensor = System.nanoTime()
|
||||
while (running && connection.get() === current) {
|
||||
val frame = XrealProtocol.read(current.reports)
|
||||
val sample = XrealProtocol.sample(frame)
|
||||
if (sample != null) {
|
||||
lastSensor = System.nanoTime()
|
||||
val enabled = tracking
|
||||
if (enabled && !wasTracking) filter = XrealOrientationFilter()
|
||||
wasTracking = enabled
|
||||
if (enabled) filter.update(sample)?.let {
|
||||
if (running && ready && tracking && connection.get() === current)
|
||||
listener.onPose(frame.body, it, System.nanoTime())
|
||||
}
|
||||
} else if (System.nanoTime() - lastSensor > 3_000_000_000L) {
|
||||
throw IOException("No valid XREAL IMU reports")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
failure.set(e)
|
||||
current.close() // Wake a control read immediately.
|
||||
}
|
||||
}, "xreal-reports").apply { isDaemon = true; start() }
|
||||
ready = true
|
||||
lastError = null
|
||||
listener.onReady()
|
||||
var heartbeat = System.nanoTime()
|
||||
while (running && failure.get() == null) {
|
||||
val command = commands.poll(250, TimeUnit.MILLISECONDS)
|
||||
if (command != null) {
|
||||
when (command.message) {
|
||||
VitureProtocol.MSG_GET_DISPLAY ->
|
||||
listener.onValue(command.message, control.display())
|
||||
VitureProtocol.MSG_DISPLAY -> {
|
||||
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.changeDisplay(command.value))
|
||||
}
|
||||
VitureProtocol.MSG_BRIGHTNESS -> {
|
||||
control.set(XrealProtocol.SET_BRIGHTNESS, command.value)
|
||||
listener.onValue(command.message, command.value)
|
||||
}
|
||||
VitureProtocol.MSG_FILM -> {
|
||||
control.set(XrealProtocol.SET_DIMMER, if (command.value == 1) 2 else 0)
|
||||
listener.onValue(command.message, command.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (System.nanoTime() - heartbeat > 5_000_000_000L) {
|
||||
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
||||
heartbeat = System.nanoTime()
|
||||
}
|
||||
}
|
||||
failure.get()?.let { throw it }
|
||||
} catch (e: Exception) {
|
||||
ready = false
|
||||
if (running && lastError != e.message) {
|
||||
lastError = e.message
|
||||
Log.w("XrealLink", "Connection unavailable: ${e.message}")
|
||||
listener.onUnavailable(e is XrealNetworkMissing)
|
||||
}
|
||||
} finally {
|
||||
ready = false
|
||||
tracking = false
|
||||
commands.clear()
|
||||
connection.compareAndSet(channels, null)
|
||||
channels?.close()
|
||||
try { reports?.join(2500) } catch (_: InterruptedException) { }
|
||||
}
|
||||
if (running) try { Thread.sleep(2000) } catch (_: InterruptedException) { }
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
running = false
|
||||
ready = false
|
||||
tracking = false
|
||||
commands.clear()
|
||||
connection.getAndSet(null)?.close()
|
||||
connector.close() // Includes sockets still inside connect().
|
||||
worker.interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
/** Kept independent of Android so the real framing/acknowledgement path is testable. */
|
||||
internal class XrealControl(private val channels: XrealChannels, private val settleDelayMs: Long = 150) {
|
||||
private var transaction = 0
|
||||
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
||||
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
|
||||
channels.controlOutput.write(XrealProtocol.request(command, transaction, value))
|
||||
channels.controlOutput.flush()
|
||||
val deadline = System.nanoTime() + 3_000_000_000L
|
||||
repeat(32) { // Bound unsolicited button/status packets and stale responses.
|
||||
if (System.nanoTime() > deadline) throw IOException("XREAL control timed out")
|
||||
XrealProtocol.response(XrealProtocol.read(channels.controlInput), command, transaction)?.let { return it }
|
||||
}
|
||||
throw IOException("XREAL control response was not received")
|
||||
}
|
||||
fun display(): Int {
|
||||
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
||||
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
|
||||
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
|
||||
}
|
||||
fun changeDisplay(mode: Int): Int {
|
||||
val stereo = mode == 5
|
||||
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
||||
// On 1S, SET_INPUT itself changes EDID. Sending SET_DISPLAY immediately
|
||||
// receives error 5001 while that change is pending. GET_DISPLAY returns
|
||||
// an empty property during the transition; wait for a real mode report.
|
||||
val current = awaitDisplay { (it == 5) == stereo }
|
||||
if (current == mode) return current
|
||||
set(XrealProtocol.SET_DISPLAY, mode)
|
||||
return awaitDisplay { it == mode }
|
||||
}
|
||||
private fun awaitDisplay(matches: (Int) -> Boolean): Int {
|
||||
val deadline = System.nanoTime() + 8_000_000_000L
|
||||
repeat(40) {
|
||||
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
||||
val value = XrealProtocol.numeric(reply)
|
||||
if (value != null && matches(value)) return value
|
||||
if (value == null && !XrealProtocol.acknowledged(reply))
|
||||
throw IOException("Invalid XREAL display transition response")
|
||||
if (System.nanoTime() > deadline) throw IOException("XREAL display transition timed out")
|
||||
Thread.sleep(settleDelayMs)
|
||||
}
|
||||
throw IOException("XREAL display transition did not complete")
|
||||
}
|
||||
fun set(command: Int, value: Int) {
|
||||
val reply = exchange(command, value)
|
||||
if (!XrealProtocol.acknowledged(reply)) throw IOException("XREAL command %04x was not acknowledged: %s".format(
|
||||
command, reply.take(32).joinToString("") { "%02x".format(it) }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
/** First One-family target. Recovery and Air USB products must not use this transport. */
|
||||
object XrealModel : GlassesModel {
|
||||
const val VENDOR_ID = 0x3318
|
||||
const val PRODUCT_1S = 0x043e
|
||||
const val NATIVE_60HZ = 29 // Captured on 1S: 1920 x 1200 at 60 Hz.
|
||||
override val name = "XREAL 1S"
|
||||
override val controllable = true
|
||||
override val brightnessMax = 9
|
||||
override val volumeMax = 0
|
||||
override val hasSunblock = true
|
||||
override val diagonalFovDeg = 52f
|
||||
override val sbs90 = false
|
||||
|
||||
fun matches(vid: Int, pid: Int) = vid == VENDOR_ID && pid == PRODUCT_1S
|
||||
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
|
||||
|
||||
// One-family EDID configuration values, not VITURE's display mode IDs.
|
||||
override fun mode(hz: Int, sbs: Boolean) = when {
|
||||
sbs -> 5
|
||||
hz >= 120 -> 4
|
||||
hz >= 90 -> 3
|
||||
else -> NATIVE_60HZ
|
||||
}
|
||||
override fun modeForStep(step: Int): Int? = null
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
/** 1S radians/sec and device nanoseconds, mapped using directed hardware captures. */
|
||||
internal class XrealOrientationFilter {
|
||||
private var previous = 0L
|
||||
private var rotation = Quaternion.IDENTITY
|
||||
private var initialized = false
|
||||
private var bias = Vec3(0f, 0f, 0f)
|
||||
|
||||
fun update(sample: XrealProtocol.Sample): FloatArray? {
|
||||
if (sample.timeNs <= previous) return null
|
||||
val dt = if (previous == 0L) 0f else (sample.timeNs - previous) * 1e-9f
|
||||
previous = sample.timeNs
|
||||
// 1S reports right/down/forward. Rotate 180 degrees about X into the
|
||||
// shared right/up/back basis before either gravity alignment or fusion.
|
||||
// Captures: level gravity -Y; looking left -gyroY; up +gyroX; right tilt +gyroZ.
|
||||
val accel = Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z)
|
||||
val gyro = Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z)
|
||||
val norm = accel.length()
|
||||
val gravityValid = abs(norm - 9.81f) < 1.5f
|
||||
if (dt > 0.25f) initialized = false // Never integrate a reconnect/stall as motion.
|
||||
if (!initialized) {
|
||||
if (!gravityValid) return null
|
||||
val up = accel.normalized()
|
||||
val axis = up.cross(Vec3(0f, 1f, 0f))
|
||||
rotation = if (up.y < -0.9999f) Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.PI.toFloat())
|
||||
else Quaternion(1f + up.y, axis.x, axis.y, axis.z).normalized()
|
||||
initialized = true
|
||||
} else if (dt in 0.0001f..0.05f) {
|
||||
if (gravityValid && gyro.length() < 0.04f) {
|
||||
val alpha = (dt * 0.5f).coerceAtMost(1f)
|
||||
bias = bias * (1f - alpha) + gyro * alpha
|
||||
}
|
||||
var rate = gyro - bias
|
||||
if (gravityValid) {
|
||||
val predictedUp = rotation.conjugate().rotate(Vec3(0f, 1f, 0f))
|
||||
rate += accel.normalized().cross(predictedUp) * 1.5f
|
||||
}
|
||||
rotation = rotation.integrateBodyRate(rate, dt).normalized()
|
||||
}
|
||||
// Same right/up/back -> shared glasses basis used by the RayNeo adapter.
|
||||
return RayNeoOrientationFilter.glassesPose(floatArrayOf(rotation.w, rotation.x, rotation.y, rotation.z))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.droiddeck.launcher.glasses
|
||||
|
||||
import java.io.EOFException
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Independent implementation of the One-family wire format; see xreal-investigation.md. */
|
||||
internal object XrealProtocol {
|
||||
const val HOST = "169.254.2.1"
|
||||
const val REPORT_PORT = 52998
|
||||
const val CONTROL_PORT = 52999
|
||||
const val REPORT = 0x2836
|
||||
const val GET_DISPLAY = 0x275e
|
||||
const val SET_DISPLAY = 0x275f
|
||||
const val SET_INPUT = 0x2822
|
||||
const val SET_BRIGHTNESS = 0x271c
|
||||
const val SET_DIMMER = 0x2727
|
||||
const val MAX_BODY = 64 * 1024
|
||||
|
||||
data class Frame(val command: Int, val body: ByteArray)
|
||||
data class Sample(val timeNs: Long, val gyro: Vec3, val accel: Vec3)
|
||||
|
||||
fun read(input: InputStream): Frame {
|
||||
val deadline = System.nanoTime() + 3_000_000_000L
|
||||
val header = ByteArray(6)
|
||||
input.readFully(header, deadline)
|
||||
val size = ByteBuffer.wrap(header, 2, 4).int
|
||||
if (size !in 0..MAX_BODY) throw IOException("Invalid XREAL frame length: $size")
|
||||
return Frame(((header[0].toInt() and 255) shl 8) or (header[1].toInt() and 255),
|
||||
ByteArray(size).also { input.readFully(it, deadline) })
|
||||
}
|
||||
|
||||
private fun InputStream.readFully(bytes: ByteArray, deadline: Long) {
|
||||
var at = 0
|
||||
while (at < bytes.size) {
|
||||
if (System.nanoTime() > deadline) throw IOException("XREAL frame timed out")
|
||||
val count = read(bytes, at, bytes.size - at)
|
||||
if (count < 0) throw EOFException("XREAL stream closed mid-frame")
|
||||
if (count == 0) throw IOException("XREAL stream made no progress")
|
||||
at += count
|
||||
}
|
||||
}
|
||||
|
||||
fun sample(frame: Frame): Sample? {
|
||||
if (frame.command != REPORT || frame.body.size != 128) return null
|
||||
val b = ByteBuffer.wrap(frame.body).order(ByteOrder.LITTLE_ENDIAN)
|
||||
if (b.getInt(24) != 11) return null // Magnetometer reports are a different type.
|
||||
val time = b.getLong(8)
|
||||
val gyro = Vec3(b.getFloat(28), b.getFloat(32), b.getFloat(36))
|
||||
val accel = Vec3(b.getFloat(40), b.getFloat(44), b.getFloat(48))
|
||||
if (time <= 0 || !gyro.valid(100f) || !accel.valid(200f)) return null
|
||||
return Sample(time, gyro, accel)
|
||||
}
|
||||
|
||||
private fun Vec3.valid(limit: Float) = listOf(x, y, z).all { it.isFinite() && kotlin.math.abs(it) <= limit }
|
||||
|
||||
fun request(command: Int, transaction: Int, value: Int? = null): ByteArray {
|
||||
require(transaction > 0)
|
||||
require(value == null || value in 0..127)
|
||||
val payload = if (value == null) byteArrayOf(0x18, 0) else byteArrayOf(0x1a, 2, 8, value.toByte())
|
||||
return ByteBuffer.allocate(10 + payload.size).putShort(command.toShort())
|
||||
.putInt(4 + payload.size).putInt(transaction or Int.MIN_VALUE).put(payload).array()
|
||||
}
|
||||
|
||||
/** No acknowledgement is inferred from a write; match both command and transaction. */
|
||||
fun response(frame: Frame, command: Int, transaction: Int): ByteArray? {
|
||||
if (frame.command != command || frame.body.size < 4 ||
|
||||
ByteBuffer.wrap(frame.body).int != transaction) return null
|
||||
return frame.body.copyOfRange(4, frame.body.size)
|
||||
}
|
||||
|
||||
fun acknowledged(payload: ByteArray) = payload.contentEquals(byteArrayOf(0x22, 0))
|
||||
fun numeric(payload: ByteArray): Int? = if (payload.size == 4 &&
|
||||
payload[0] == 0x22.toByte() && payload[1] == 2.toByte() && payload[2] == 0x10.toByte() &&
|
||||
payload[3].toInt() in 0..127) payload[3].toInt() else null
|
||||
}
|
||||
Reference in new issue
Block a user