mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-24 11:01:20 -08:00
Better steamvr detection that does not race or crash
This commit is contained in:
1 parent
baea5d3227
commit
e53fcf294b
2 files changed
+77
-106
No files matched your search
@@ -37,9 +37,7 @@ class EnableSteamVRDriverBehaviour : SolarXRBridgeBehaviour {
|
||||
override fun observe(receiver: SolarXRBridge) {
|
||||
receiver.rpcDispatcher.on<EnableSteamVRDriverRequest> {
|
||||
receiver.context.scope.launch {
|
||||
val client = HttpClient(CIO)
|
||||
unblockSteamVRDriver(client, "slimevr")
|
||||
client.close()
|
||||
HttpClient(CIO).use { client -> unblockSteamVRDriver(client, "slimevr") }
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
package dev.slimevr.desktop.trackingchecklist
|
||||
|
||||
import com.sun.jna.Native
|
||||
import com.sun.jna.platform.win32.Kernel32
|
||||
import com.sun.jna.platform.win32.Kernel32Util
|
||||
import com.sun.jna.platform.win32.Tlhelp32
|
||||
import com.sun.jna.platform.win32.WinBase
|
||||
import com.sun.jna.platform.win32.WinDef
|
||||
import dev.slimevr.CURRENT_PLATFORM
|
||||
import dev.slimevr.Platform
|
||||
import dev.slimevr.VRServer
|
||||
@@ -21,70 +15,61 @@ import io.ktor.client.engine.cio.CIO
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.emitAll
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onCompletion
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.flow.retryWhen
|
||||
import kotlinx.coroutines.flow.transformLatest
|
||||
import solarxr_protocol.rpc.TrackingChecklistSteamVRDisconnected
|
||||
import solarxr_protocol.rpc.TrackingChecklistStep
|
||||
import solarxr_protocol.rpc.TrackingChecklistStepId
|
||||
import solarxr_protocol.rpc.TrackingChecklistStepVisibility
|
||||
import java.io.IOException
|
||||
import java.net.ConnectException
|
||||
import java.io.File
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
data class Process(val pid: ULong, val name: String)
|
||||
private val PROCESS_POLL_INTERVAL = 3.seconds
|
||||
|
||||
private suspend fun getRunningProcesses(): List<Process> = withContext(Dispatchers.IO) {
|
||||
when (CURRENT_PLATFORM) {
|
||||
Platform.LINUX -> buildList {
|
||||
val psProc = try {
|
||||
ProcessBuilder("ps", "-eo", "pid,comm").redirectErrorStream(true).start()
|
||||
} catch (_: IOException) {
|
||||
return@buildList
|
||||
}
|
||||
// SteamVR's web server comes up some time after vrserver starts
|
||||
private val STEAMVR_WEB_SERVER_STARTUP = 5.seconds
|
||||
|
||||
val lines = psProc.inputStream.bufferedReader().readLines()
|
||||
// skip the header
|
||||
for (line in lines.slice(1 until lines.size)) {
|
||||
val data = line.trimStart().split(' ')
|
||||
add(Process(data[0].toULong(), data[1]))
|
||||
}
|
||||
}
|
||||
// Retry delay doubles from 1s up to 2^step seconds (16s)
|
||||
private const val DRIVERS_RETRY_MAX_BACKOFF_STEP = 4L
|
||||
|
||||
Platform.WINDOWS -> buildList {
|
||||
val k32 = Kernel32.INSTANCE
|
||||
val snapshot = k32.CreateToolhelp32Snapshot(
|
||||
Tlhelp32.TH32CS_SNAPPROCESS,
|
||||
WinDef.DWORD(0),
|
||||
)
|
||||
if (WinBase.INVALID_HANDLE_VALUE.equals(snapshot)) {
|
||||
return@buildList
|
||||
}
|
||||
private fun isProcessRunning(name: String): Boolean = ProcessHandle.allProcesses().anyMatch { proc ->
|
||||
proc.info().command().orElse(null)?.substringAfterLast(File.separatorChar) == name
|
||||
}
|
||||
|
||||
try {
|
||||
val entry = Tlhelp32.PROCESSENTRY32()
|
||||
if (!k32.Process32First(snapshot, entry)) {
|
||||
val err = k32.GetLastError()
|
||||
AppLogger.checklist.warn("Failed to retrieve process information: ${Kernel32Util.formatMessage(err)} (code $err)")
|
||||
return@buildList
|
||||
}
|
||||
|
||||
do {
|
||||
add(Process(entry.th32ProcessID.toLong().toULong(), Native.toString(entry.szExeFile)))
|
||||
} while (k32.Process32Next(snapshot, entry))
|
||||
} finally {
|
||||
k32.CloseHandle(snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
else -> emptyList()
|
||||
// No OS event for process start/exit, so this polls
|
||||
private fun processRunningFlow(name: String): Flow<Boolean> = flow {
|
||||
while (true) {
|
||||
emit(isProcessRunning(name))
|
||||
delay(PROCESS_POLL_INTERVAL)
|
||||
}
|
||||
}.flowOn(Dispatchers.IO).distinctUntilChanged()
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
private fun steamVRReadyFlow(procName: String): Flow<Boolean> = processRunningFlow(procName).transformLatest { running ->
|
||||
if (running) delay(STEAMVR_WEB_SERVER_STARTUP)
|
||||
emit(running)
|
||||
}
|
||||
|
||||
private fun steamVRDriversFlow(client: HttpClient): Flow<List<Driver>> = flow {
|
||||
emit(getSteamVRDriversList(client))
|
||||
}.retryWhen { cause, attempt ->
|
||||
if (cause is CancellationException) return@retryWhen false
|
||||
AppLogger.checklist.warn(cause, "Failed to get SteamVR drivers list, retrying")
|
||||
delay(1.seconds * (1 shl attempt.coerceAtMost(DRIVERS_RETRY_MAX_BACKOFF_STEP).toInt()))
|
||||
true
|
||||
}
|
||||
|
||||
private fun buildSteamVRDriverStep(driverEnabled: Boolean = true, connected: Boolean = false, installed: Boolean = true, blocked: Boolean = false, enabledInSteamVR: Boolean = true) = TrackingChecklistStep(
|
||||
@@ -108,75 +93,62 @@ private fun buildStandableStep(supported: Boolean = true, installed: Boolean = f
|
||||
visibility = TrackingChecklistStepVisibility.WHEN_INVALID,
|
||||
)
|
||||
|
||||
private fun buildSteamVRSteps(driverConnected: Boolean, drivers: List<Driver>?): Pair<TrackingChecklistStep, TrackingChecklistStep> {
|
||||
if (drivers == null) {
|
||||
return buildSteamVRDriverStep(connected = driverConnected) to buildStandableStep()
|
||||
}
|
||||
|
||||
val driver = drivers.firstOrNull { it.manifest.name == "slimevr" }
|
||||
val standableDriver = drivers.firstOrNull { it.manifest.name == "standable" }
|
||||
|
||||
return buildSteamVRDriverStep(
|
||||
connected = driverConnected,
|
||||
installed = driver != null,
|
||||
blocked = driver?.blockedBySafeMode ?: false,
|
||||
enabledInSteamVR = driver?.enabled ?: true,
|
||||
) to buildStandableStep(installed = standableDriver != null)
|
||||
}
|
||||
|
||||
class SteamVRCheckBehaviour(private val server: VRServer, private val settings: Settings) : TrackingChecklistBehaviourType {
|
||||
private val client = HttpClient(CIO)
|
||||
private val steamVRProcName = when (CURRENT_PLATFORM) {
|
||||
Platform.WINDOWS -> "vrserver.exe"
|
||||
else -> "vrserver"
|
||||
}
|
||||
|
||||
@JvmInline
|
||||
private value class SteamVRState(val running: Boolean, val drivers: List<Driver>?)
|
||||
private data class DriverActivity(val anyDriver: Boolean, val steamVRDriver: Boolean)
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override fun observe(receiver: TrackingChecklist) {
|
||||
settings.context.state.map { it.data.driverConfig.enabled }.flatMapLatest { enabled ->
|
||||
val client = HttpClient(CIO)
|
||||
|
||||
val driverActivity = server.context.state.map { it.solarxr }.distinctUntilChanged().flatMapLatest { solarXRBridges ->
|
||||
if (solarXRBridges.isEmpty()) {
|
||||
return@flatMapLatest flowOf(DriverActivity(anyDriver = false, steamVRDriver = false))
|
||||
}
|
||||
combine(solarXRBridges.values.map { it.context.state }) { states ->
|
||||
DriverActivity(
|
||||
anyDriver = states.any { it.driverName != null },
|
||||
steamVRDriver = states.any { it.driverName == "SteamVR" },
|
||||
)
|
||||
}
|
||||
}.distinctUntilChanged()
|
||||
|
||||
settings.context.state.map { it.data.driverConfig.enabled }.distinctUntilChanged().flatMapLatest { enabled ->
|
||||
if (!enabled) {
|
||||
return@flatMapLatest flowOf(buildSteamVRDriverStep(driverEnabled = false) to buildStandableStep(supported = false))
|
||||
}
|
||||
|
||||
val steamVRRunning = flow {
|
||||
while (true) {
|
||||
val running = getRunningProcesses().any { proc ->
|
||||
proc.name == steamVRProcName
|
||||
}
|
||||
emit(running)
|
||||
delay(3000)
|
||||
}
|
||||
}
|
||||
val steamVRState = steamVRRunning.distinctUntilChanged().map { running ->
|
||||
if (!running) {
|
||||
return@map SteamVRState(false, null)
|
||||
}
|
||||
|
||||
delay(500)
|
||||
val drivers = try {
|
||||
getSteamVRDriversList(client)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.checklist.warn(
|
||||
e,
|
||||
"Failed to get SteamVR drivers list",
|
||||
)
|
||||
null
|
||||
}
|
||||
|
||||
return@map SteamVRState(true, drivers)
|
||||
}
|
||||
|
||||
val solarXRDriverActiveFlow = server.context.state.map { it.solarxr }.distinctUntilChanged().flatMapLatest { solarXRBridges ->
|
||||
combine(solarXRBridges.values.map { it.context.state }) { states ->
|
||||
states.any { it.driverName != null } to states.any { it.driverName == "SteamVR" }
|
||||
}
|
||||
}
|
||||
|
||||
combine(solarXRDriverActiveFlow, steamVRState) { (anyDriverActive, steamVRDriverActive), steamVRState ->
|
||||
combine(driverActivity, steamVRReadyFlow(steamVRProcName), ::Pair).transformLatest { (activity, steamVRReady) ->
|
||||
// if a non-SteamVR driver is connected, we shouldn't try to fetch the drivers list
|
||||
if (anyDriverActive && !steamVRDriverActive) {
|
||||
return@combine buildSteamVRDriverStep(connected = true) to buildStandableStep(supported = false)
|
||||
if (activity.anyDriver && !activity.steamVRDriver) {
|
||||
emit(buildSteamVRDriverStep(connected = true) to buildStandableStep(supported = false))
|
||||
return@transformLatest
|
||||
}
|
||||
|
||||
if (steamVRState.drivers == null) {
|
||||
return@combine buildSteamVRDriverStep(connected = anyDriverActive) to buildStandableStep()
|
||||
emit(buildSteamVRSteps(activity.anyDriver, drivers = null))
|
||||
if (steamVRReady) {
|
||||
emitAll(steamVRDriversFlow(client).map { buildSteamVRSteps(activity.anyDriver, it) })
|
||||
}
|
||||
|
||||
val driver = steamVRState.drivers.firstOrNull {
|
||||
it.manifest.name == "slimevr"
|
||||
}
|
||||
val standableDriver = steamVRState.drivers.firstOrNull {
|
||||
it.manifest.name == "standable"
|
||||
}
|
||||
|
||||
buildSteamVRDriverStep(connected = anyDriverActive, installed = !steamVRState.running || driver != null, blocked = driver?.blockedBySafeMode ?: false, enabledInSteamVR = driver?.enabled ?: true) to buildStandableStep(installed = standableDriver != null)
|
||||
}
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
@@ -188,6 +160,7 @@ class SteamVRCheckBehaviour(private val server: VRServer, private val settings:
|
||||
),
|
||||
)
|
||||
}
|
||||
.onCompletion { client.close() }
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user