mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-06 00:32:35 -08:00
Nuke Protobuf and Windows named pipes
Tests are broken, will fix later..
This commit is contained in:
21 files changed
+62
-993
No files matched your search
@@ -13,46 +13,12 @@ const val DRIVER_SOCKET_NAME = "SlimeVRDriver"
|
||||
const val FEEDER_SOCKET_NAME = "SlimeVRInput"
|
||||
const val SOLARXR_SOCKET_NAME = "SlimeVRRpc"
|
||||
|
||||
const val DRIVER_PIPE = "\\\\.\\pipe\\SlimeVRDriver"
|
||||
const val FEEDER_PIPE = "\\\\.\\pipe\\SlimeVRInput"
|
||||
const val SOLARXR_PIPE = "\\\\.\\pipe\\SlimeVRRpc"
|
||||
|
||||
// Frames larger than this are refused: nothing in either protocol comes close
|
||||
internal const val MAX_FRAME_SIZE = 256 * 1024
|
||||
|
||||
suspend fun createIpcServers(appContext: AppContextProvider) = coroutineScope {
|
||||
if (appContext.featureFlags.supportsDriver) {
|
||||
launch { createDriverServers(appContext) }
|
||||
}
|
||||
|
||||
when (CURRENT_PLATFORM) {
|
||||
Platform.LINUX, Platform.OSX -> launch { createUnixSolarXRSocket(appContext) }
|
||||
Platform.WINDOWS -> launch { createWindowsSolarXRPipe(appContext) }
|
||||
Platform.LINUX, Platform.WINDOWS, Platform.OSX -> launch { createUnixSolarXRSocket(appContext) }
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun createDriverServers(appContext: AppContextProvider) {
|
||||
appContext.config.settings.context.state
|
||||
.map { it.data.driverConfig.enabled }
|
||||
.distinctUntilChanged()
|
||||
.collectLatest { enabled ->
|
||||
if (!enabled) return@collectLatest
|
||||
|
||||
coroutineScope {
|
||||
when (CURRENT_PLATFORM) {
|
||||
Platform.LINUX, Platform.OSX -> {
|
||||
launch { createUnixDriverSocket(appContext) }
|
||||
launch { createUnixFeederSocket(appContext) }
|
||||
}
|
||||
|
||||
Platform.WINDOWS -> {
|
||||
launch { createWindowsDriverPipe(appContext) }
|
||||
launch { createWindowsFeederPipe(appContext) }
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
package dev.slimevr.desktop.ipc
|
||||
|
||||
import com.sun.jna.Memory
|
||||
import com.sun.jna.Native
|
||||
import com.sun.jna.Pointer
|
||||
import com.sun.jna.platform.win32.Kernel32
|
||||
import com.sun.jna.platform.win32.WinBase
|
||||
import com.sun.jna.platform.win32.WinError
|
||||
import com.sun.jna.platform.win32.WinNT
|
||||
import com.sun.jna.win32.StdCallLibrary
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
import java.io.IOException
|
||||
|
||||
private val k32 = Kernel32.INSTANCE
|
||||
|
||||
private const val HEADER_SIZE = 4
|
||||
|
||||
private const val WAIT_SLICE_MILLIS = 200
|
||||
private const val WAIT_TIMEOUT = 0x102
|
||||
|
||||
@Suppress("FunctionName")
|
||||
private object Kernel32IO : StdCallLibrary {
|
||||
init {
|
||||
Native.register(Kernel32IO::class.java, "kernel32")
|
||||
}
|
||||
|
||||
external fun ReadFile(handle: Pointer, buffer: Pointer, len: Int, read: Pointer?, overlapped: Pointer): Boolean
|
||||
|
||||
external fun WriteFile(handle: Pointer, buffer: Pointer, len: Int, written: Pointer?, overlapped: Pointer): Boolean
|
||||
|
||||
external fun GetOverlappedResult(handle: Pointer, overlapped: Pointer, moved: Pointer, wait: Boolean): Boolean
|
||||
|
||||
external fun WaitForSingleObject(handle: Pointer, millis: Int): Int
|
||||
|
||||
external fun CancelIoEx(handle: Pointer, overlapped: Pointer?): Boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* One slot of overlapped I/O on a Windows pipe handle: an event, an [WinBase.OVERLAPPED] and a pinned
|
||||
* buffer.
|
||||
*/
|
||||
internal class PipeSlot(private val handle: WinNT.HANDLE) : AutoCloseable {
|
||||
private val event = checkNotNull(k32.CreateEvent(null, true, false, null)) {
|
||||
"CreateEvent failed: ${Native.getLastError()}"
|
||||
}
|
||||
|
||||
private val overlapped = WinBase.OVERLAPPED().apply {
|
||||
hEvent = event
|
||||
write()
|
||||
setAutoSynch(false)
|
||||
}
|
||||
|
||||
private val buffer = Memory(MAX_FRAME_SIZE.toLong())
|
||||
|
||||
// Staging area between the pinned native buffer and okio, reused so a frame costs no allocation
|
||||
private val scratch = ByteArray(MAX_FRAME_SIZE)
|
||||
|
||||
// Resolved once. The wrappers have to stay referenced to keep the native memory alive anyway, so
|
||||
// unwrapping them per call would only re-do work. `transferred` replaces an IntByReference that
|
||||
// was allocated on every completion.
|
||||
private val handlePointer = handle.pointer
|
||||
private val eventPointer = event.pointer
|
||||
private val overlappedPointer = overlapped.pointer
|
||||
private val transferred = Memory(4)
|
||||
|
||||
suspend fun awaitClient(): Boolean {
|
||||
// On an overlapped handle ConnectNamedPipe returns straight away, so we do the waiting
|
||||
val connected = k32.ConnectNamedPipe(handle, overlapped)
|
||||
val err = Native.getLastError()
|
||||
return when {
|
||||
// ERROR_PIPE_CONNECTED means the client got in before we asked
|
||||
connected || err == WinError.ERROR_PIPE_CONNECTED -> true
|
||||
|
||||
err == WinError.ERROR_IO_PENDING -> awaitCompletion() >= 0
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
// Returns false once the peer closed. The overlapped wait blocks the thread it runs on, so both
|
||||
// sides of the pipe stay on Dispatchers.IO
|
||||
suspend fun readFrameInto(out: Buffer): Boolean = withContext(Dispatchers.IO) {
|
||||
if (!readInto(0, HEADER_SIZE)) return@withContext false
|
||||
val total = buffer.getInt(0)
|
||||
if (total !in HEADER_SIZE..MAX_FRAME_SIZE) throw IOException("Frame length out of range: $total")
|
||||
if (!readInto(HEADER_SIZE, total - HEADER_SIZE)) return@withContext false
|
||||
|
||||
val payload = total - HEADER_SIZE
|
||||
buffer.read(HEADER_SIZE.toLong(), scratch, 0, payload)
|
||||
out.write(scratch, 0, payload)
|
||||
true
|
||||
}
|
||||
|
||||
suspend fun writeFrame(payload: Buffer) {
|
||||
val size = payload.size.toInt()
|
||||
val total = size + HEADER_SIZE
|
||||
if (total > MAX_FRAME_SIZE) throw IOException("Frame too large to send: $total bytes")
|
||||
payload.read(scratch, 0, size)
|
||||
buffer.setInt(0, total)
|
||||
buffer.write(HEADER_SIZE.toLong(), scratch, 0, size)
|
||||
|
||||
val written = withContext(Dispatchers.IO) {
|
||||
transfer { Kernel32IO.WriteFile(handlePointer, buffer, total, null, overlappedPointer) }
|
||||
}
|
||||
if (written != total) throw IOException("Pipe write incomplete: $written of $total bytes")
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
buffer.close()
|
||||
transferred.close()
|
||||
k32.CloseHandle(event)
|
||||
}
|
||||
|
||||
private suspend fun readInto(at: Int, len: Int): Boolean {
|
||||
var done = 0
|
||||
while (done < len) {
|
||||
val remaining = len - done
|
||||
val moved = transfer {
|
||||
Kernel32IO.ReadFile(handlePointer, buffer.share((at + done).toLong(), remaining.toLong()), remaining, null, overlappedPointer)
|
||||
}
|
||||
if (moved <= 0) return false
|
||||
done += moved
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private suspend inline fun transfer(issue: () -> Boolean): Int {
|
||||
if (!issue()) {
|
||||
// Read the code as the very next thing: k32.GetLastError() is itself a JNA call, and the
|
||||
// marshalling on the way into it can overwrite the value we wanted. Mistaking a pending
|
||||
// operation for a failed one frees buffer while the kernel is still reading out of it
|
||||
val err = Native.getLastError()
|
||||
if (err != WinError.ERROR_IO_PENDING) {
|
||||
// A broken pipe is just the client leaving, which the caller turns into a reconnect
|
||||
if (err != WinError.ERROR_BROKEN_PIPE) AppLogger.ipc.warn("Pipe operation failed: $err")
|
||||
return -1
|
||||
}
|
||||
}
|
||||
return awaitCompletion()
|
||||
}
|
||||
|
||||
private suspend fun awaitCompletion(): Int {
|
||||
while (Kernel32IO.WaitForSingleObject(eventPointer, WAIT_SLICE_MILLIS) == WAIT_TIMEOUT) {
|
||||
if (currentCoroutineContext().isActive) continue
|
||||
|
||||
Kernel32IO.CancelIoEx(handlePointer, overlappedPointer)
|
||||
Kernel32IO.GetOverlappedResult(handlePointer, overlappedPointer, transferred, true)
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
if (!Kernel32IO.GetOverlappedResult(handlePointer, overlappedPointer, transferred, true)) return -1
|
||||
return transferred.getInt(0)
|
||||
}
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
package dev.slimevr.desktop.ipc
|
||||
|
||||
import com.squareup.wire.ProtoWriter
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.desktop.platform.Battery
|
||||
import dev.slimevr.desktop.platform.Position
|
||||
import dev.slimevr.desktop.platform.ProtobufMessage
|
||||
import dev.slimevr.desktop.platform.TrackerAdded
|
||||
import dev.slimevr.desktop.platform.TrackerStatus
|
||||
import dev.slimevr.desktop.platform.Version
|
||||
import dev.slimevr.desktop.startBindingsProvider
|
||||
import dev.slimevr.driver.DriverBridge
|
||||
import dev.slimevr.driver.DriverBridgeInbound
|
||||
import dev.slimevr.driver.DriverBridgeOutbound
|
||||
import dev.slimevr.driver.DriverBridgeSource
|
||||
import dev.slimevr.driver.TrackerRole
|
||||
import dev.slimevr.driver.bodyPartToRole
|
||||
import dev.slimevr.driver.roleToBodyPart
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import kotlinx.coroutines.cancelChildren
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okio.Buffer
|
||||
|
||||
val solarxrToProtoStatus = mapOf(
|
||||
solarxr_protocol.datatypes.TrackerStatus.OK to TrackerStatus.Status.OK,
|
||||
solarxr_protocol.datatypes.TrackerStatus.SLEEPING to TrackerStatus.Status.OK,
|
||||
solarxr_protocol.datatypes.TrackerStatus.TIMED_OUT to TrackerStatus.Status.OK,
|
||||
solarxr_protocol.datatypes.TrackerStatus.ERROR to TrackerStatus.Status.ERROR,
|
||||
solarxr_protocol.datatypes.TrackerStatus.OCCLUDED to TrackerStatus.Status.OCCLUDED,
|
||||
solarxr_protocol.datatypes.TrackerStatus.DISCONNECTED to TrackerStatus.Status.DISCONNECTED,
|
||||
solarxr_protocol.datatypes.TrackerStatus.BUSY to TrackerStatus.Status.BUSY,
|
||||
)
|
||||
val protoToSolarxrStatus = mapOf(
|
||||
TrackerStatus.Status.OK to solarxr_protocol.datatypes.TrackerStatus.OK,
|
||||
TrackerStatus.Status.ERROR to solarxr_protocol.datatypes.TrackerStatus.ERROR,
|
||||
TrackerStatus.Status.OCCLUDED to solarxr_protocol.datatypes.TrackerStatus.OCCLUDED,
|
||||
TrackerStatus.Status.DISCONNECTED to solarxr_protocol.datatypes.TrackerStatus.DISCONNECTED,
|
||||
TrackerStatus.Status.BUSY to solarxr_protocol.datatypes.TrackerStatus.BUSY,
|
||||
)
|
||||
|
||||
const val PROTOCOL_VERSION = 2
|
||||
|
||||
suspend fun handleDriverConnection(
|
||||
appContext: AppContextProvider,
|
||||
source: DriverBridgeSource,
|
||||
messages: Flow<Buffer>,
|
||||
send: suspend (Buffer) -> Unit,
|
||||
) = coroutineScope {
|
||||
val sendMutex = Mutex()
|
||||
|
||||
val encodeBuffer = Buffer()
|
||||
val encodeWriter = ProtoWriter(encodeBuffer)
|
||||
|
||||
suspend fun sendMsg(msg: ProtobufMessage) = sendMutex.withLock {
|
||||
ProtobufMessage.ADAPTER.encode(encodeWriter, msg)
|
||||
send(encodeBuffer)
|
||||
}
|
||||
|
||||
val bridge = DriverBridge.create(
|
||||
id = appContext.server.nextHandle(),
|
||||
source = source,
|
||||
appContext = appContext,
|
||||
scope = this,
|
||||
)
|
||||
|
||||
bridge.outbound.on<DriverBridgeOutbound.TrackerAdded> { event ->
|
||||
val trackerRole = bodyPartToRole.getOrDefault(event.part, TrackerRole.NONE)
|
||||
sendMsg(
|
||||
ProtobufMessage(
|
||||
tracker_added = TrackerAdded(
|
||||
tracker_id = event.trackerId,
|
||||
tracker_serial = "human://$trackerRole",
|
||||
tracker_name = "SlimeVR $trackerRole Virtual Tracker",
|
||||
tracker_role = trackerRole.value.toInt(),
|
||||
manufacturer = "SlimeVR",
|
||||
),
|
||||
),
|
||||
)
|
||||
}.launchIn(this)
|
||||
|
||||
bridge.outbound.on<DriverBridgeOutbound.TrackerPosition> { event ->
|
||||
sendMsg(
|
||||
ProtobufMessage(
|
||||
position = Position(
|
||||
tracker_id = event.trackerId,
|
||||
qx = event.rotation.x,
|
||||
qy = event.rotation.y,
|
||||
qz = event.rotation.z,
|
||||
qw = event.rotation.w,
|
||||
x = event.position?.x,
|
||||
y = event.position?.y,
|
||||
z = event.position?.z,
|
||||
),
|
||||
),
|
||||
)
|
||||
}.launchIn(this)
|
||||
|
||||
bridge.outbound.on<DriverBridgeOutbound.TrackerStatus> { event ->
|
||||
sendMsg(
|
||||
ProtobufMessage(
|
||||
tracker_status = TrackerStatus(
|
||||
tracker_id = event.trackerId,
|
||||
status = solarxrToProtoStatus.getOrDefault(event.status, TrackerStatus.Status.ERROR),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
sendMsg(
|
||||
ProtobufMessage(
|
||||
battery = Battery(
|
||||
tracker_id = event.trackerId,
|
||||
battery_level = event.battery ?: 0f,
|
||||
is_charging = event.charging,
|
||||
),
|
||||
),
|
||||
)
|
||||
}.launchIn(this)
|
||||
|
||||
sendMsg(ProtobufMessage(version = Version(protocol_version = PROTOCOL_VERSION)))
|
||||
|
||||
try {
|
||||
messages.collect { bytes ->
|
||||
val msg = ProtobufMessage.ADAPTER.decode(bytes)
|
||||
msg.version?.let { ver ->
|
||||
bridge.inbound.emit(DriverBridgeInbound.Version(ver.protocol_version))
|
||||
if (ver.protocol_version >= 2) {
|
||||
// FIXME: multiple launch could be created here bc nothing prevent protocol from changing or getting called again during runtime
|
||||
// causing a memory leak
|
||||
this@coroutineScope.launch {
|
||||
startBindingsProvider()
|
||||
}
|
||||
}
|
||||
}
|
||||
msg.tracker_added?.let { ta ->
|
||||
bridge.inbound.emit(
|
||||
DriverBridgeInbound.TrackerAdded(
|
||||
id = ta.tracker_id,
|
||||
name = ta.tracker_name,
|
||||
manufacturer = ta.manufacturer.ifEmpty { "OpenVR" },
|
||||
serial = ta.tracker_serial,
|
||||
bodyPart = TrackerRole.fromValue(ta.tracker_role.toUByte())?.let { role -> roleToBodyPart[role] },
|
||||
),
|
||||
)
|
||||
}
|
||||
msg.tracker_status?.let { status ->
|
||||
bridge.inbound.emit(DriverBridgeInbound.TrackerStatus(id = status.tracker_id, status = protoToSolarxrStatus.getOrDefault(status.status, solarxr_protocol.datatypes.TrackerStatus.ERROR)))
|
||||
}
|
||||
msg.battery?.let { bat ->
|
||||
bridge.inbound.emit(
|
||||
DriverBridgeInbound.TrackerBattery(
|
||||
id = bat.tracker_id,
|
||||
batteryLevel = bat.battery_level,
|
||||
charging = bat.is_charging,
|
||||
),
|
||||
)
|
||||
}
|
||||
msg.position?.let { pos ->
|
||||
bridge.inbound.emit(
|
||||
DriverBridgeInbound.TrackerPosition(
|
||||
id = pos.tracker_id,
|
||||
rotation = Quaternion(
|
||||
w = pos.qw,
|
||||
x = pos.qx,
|
||||
y = pos.qy,
|
||||
z = pos.qz,
|
||||
),
|
||||
position = if (pos.x != null && pos.y != null && pos.z != null) {
|
||||
Vector3(
|
||||
pos.x,
|
||||
pos.y,
|
||||
pos.z,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
bridge.disconnect()
|
||||
// The outbound listeners are launched into this scope and never complete on their own
|
||||
// (they observe a SharedFlow), so coroutineScope would wait on them forever and the
|
||||
// connection would never be released for the next client -- e.g. a SteamVR restart
|
||||
coroutineContext.cancelChildren()
|
||||
}
|
||||
}
|
||||
-21
@@ -1,7 +1,6 @@
|
||||
package dev.slimevr.desktop.ipc
|
||||
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.driver.DriverBridgeSource
|
||||
import dev.slimevr.getSocketDirectory
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -24,26 +23,6 @@ import java.nio.channels.ServerSocketChannel
|
||||
import java.nio.channels.SocketChannel
|
||||
import kotlin.io.path.Path
|
||||
|
||||
suspend fun createUnixDriverSocket(appContext: AppContextProvider) = acceptUnixClients(DRIVER_SOCKET_NAME) { channel ->
|
||||
val writer = FramedWriter(channel)
|
||||
handleDriverConnection(
|
||||
appContext = appContext,
|
||||
source = DriverBridgeSource.DRIVER,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { frame -> writer.write(frame) },
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun createUnixFeederSocket(appContext: AppContextProvider) = acceptUnixClients(FEEDER_SOCKET_NAME) { channel ->
|
||||
val writer = FramedWriter(channel)
|
||||
handleDriverConnection(
|
||||
appContext = appContext,
|
||||
source = DriverBridgeSource.FEEDER,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { frame -> writer.write(frame) },
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun createUnixSolarXRSocket(appContext: AppContextProvider) = acceptUnixClients(SOLARXR_SOCKET_NAME) { channel ->
|
||||
val writer = FramedWriter(channel)
|
||||
handleSolarXRBridge(
|
||||
@@ -1,115 +0,0 @@
|
||||
package dev.slimevr.desktop.ipc
|
||||
|
||||
import com.sun.jna.Native
|
||||
import com.sun.jna.platform.win32.Advapi32
|
||||
import com.sun.jna.platform.win32.Kernel32
|
||||
import com.sun.jna.platform.win32.WinBase
|
||||
import com.sun.jna.platform.win32.WinNT
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.driver.DriverBridgeSource
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.supervisorScope
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
|
||||
private val k32 = Kernel32.INSTANCE
|
||||
private val adv32 = Advapi32.INSTANCE
|
||||
|
||||
private const val PIPE_BUFFER_SIZE = 64 * 1024
|
||||
|
||||
private typealias ConnectionHandler = suspend (pipe: WinNT.HANDLE, writer: PipeSlot) -> Unit
|
||||
|
||||
suspend fun createWindowsDriverPipe(appContext: AppContextProvider) = acceptWindowsClients(DRIVER_PIPE) { pipe, writer ->
|
||||
handleDriverConnection(appContext, DriverBridgeSource.DRIVER, readFrames(pipe)) { frame -> writer.writeFrame(frame) }
|
||||
}
|
||||
|
||||
suspend fun createWindowsFeederPipe(appContext: AppContextProvider) = acceptWindowsClients(FEEDER_PIPE) { pipe, writer ->
|
||||
handleDriverConnection(appContext, DriverBridgeSource.FEEDER, readFrames(pipe)) { frame -> writer.writeFrame(frame) }
|
||||
}
|
||||
|
||||
suspend fun createWindowsSolarXRPipe(appContext: AppContextProvider) = acceptWindowsClients(SOLARXR_PIPE) { pipe, writer ->
|
||||
handleSolarXRBridge(appContext, readFrames(pipe)) { frame -> writer.writeFrame(frame) }
|
||||
}
|
||||
|
||||
private fun readFrames(handle: WinNT.HANDLE) = flow {
|
||||
PipeSlot(handle).use { reader ->
|
||||
val frame = Buffer()
|
||||
while (true) {
|
||||
frame.clear()
|
||||
if (!reader.readFrameInto(frame)) break
|
||||
emit(frame)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createSecurePipe(pipeName: String): WinNT.HANDLE {
|
||||
val descriptor = WinNT.SECURITY_DESCRIPTOR(64 * 1024)
|
||||
adv32.InitializeSecurityDescriptor(descriptor, WinNT.SECURITY_DESCRIPTOR_REVISION)
|
||||
adv32.SetSecurityDescriptorDacl(descriptor, true, null, false)
|
||||
|
||||
val attributes = WinBase.SECURITY_ATTRIBUTES()
|
||||
attributes.lpSecurityDescriptor = descriptor.pointer
|
||||
attributes.bInheritHandle = false
|
||||
|
||||
val pipe = k32.CreateNamedPipe(
|
||||
pipeName,
|
||||
WinBase.PIPE_ACCESS_DUPLEX or WinNT.FILE_FLAG_OVERLAPPED,
|
||||
WinBase.PIPE_TYPE_BYTE or WinBase.PIPE_READMODE_BYTE or WinBase.PIPE_WAIT,
|
||||
WinBase.PIPE_UNLIMITED_INSTANCES,
|
||||
PIPE_BUFFER_SIZE,
|
||||
PIPE_BUFFER_SIZE,
|
||||
0,
|
||||
attributes,
|
||||
)
|
||||
check(pipe != WinNT.INVALID_HANDLE_VALUE) {
|
||||
"CreateNamedPipe failed for $pipeName: ${Native.getLastError()}"
|
||||
}
|
||||
return pipe
|
||||
}
|
||||
|
||||
private suspend fun acceptWindowsClients(
|
||||
pipeName: String,
|
||||
handle: ConnectionHandler,
|
||||
) = withContext(Dispatchers.IO) {
|
||||
supervisorScope {
|
||||
while (isActive) {
|
||||
val pipe = createSecurePipe(pipeName)
|
||||
val writer = PipeSlot(pipe)
|
||||
val connected = try {
|
||||
writer.awaitClient()
|
||||
} catch (e: CancellationException) {
|
||||
// The pipe goes down with the driver output, so the one waiting for a client has to
|
||||
// be released here: no handler owns it yet
|
||||
writer.close()
|
||||
k32.CloseHandle(pipe)
|
||||
throw e
|
||||
}
|
||||
if (!connected) {
|
||||
writer.close()
|
||||
k32.CloseHandle(pipe)
|
||||
continue
|
||||
}
|
||||
AppLogger.ipc.info("$pipeName client connected")
|
||||
|
||||
launch(Dispatchers.Default) {
|
||||
try {
|
||||
handle(pipe, writer)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
AppLogger.ipc.error(e, "Error while handling $pipeName client, dropping connection")
|
||||
} finally {
|
||||
AppLogger.ipc.info("$pipeName client disconnected")
|
||||
writer.close()
|
||||
k32.DisconnectNamedPipe(pipe)
|
||||
k32.CloseHandle(pipe)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,32 +12,23 @@ import dev.slimevr.VRServer
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.desktop.Driver
|
||||
import dev.slimevr.desktop.getSteamVRDriversList
|
||||
import dev.slimevr.driver.DriverBridgeSource
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.trackingchecklist.TrackingChecklist
|
||||
import dev.slimevr.trackingchecklist.TrackingChecklistActions
|
||||
import dev.slimevr.trackingchecklist.TrackingChecklistBehaviourType
|
||||
import dev.slimevr.util.timeSource
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.utils.io.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.emptyFlow
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.last
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.mapLatest
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import solarxr_protocol.rpc.TrackingChecklistSteamVRDisconnected
|
||||
import solarxr_protocol.rpc.TrackingChecklistStep
|
||||
@@ -46,7 +37,6 @@ import solarxr_protocol.rpc.TrackingChecklistStepVisibility
|
||||
import java.io.IOException
|
||||
import java.net.ConnectException
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeMark
|
||||
|
||||
data class Process(val pid: ULong, val name: String)
|
||||
|
||||
@@ -127,6 +117,7 @@ class SteamVRCheckBehaviour(private val server: VRServer, private val settings:
|
||||
@JvmInline
|
||||
private value class SteamVRState(val running: Boolean, val drivers: List<Driver>?)
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override fun observe(receiver: TrackingChecklist) {
|
||||
settings.context.state.map { it.data.driverConfig.enabled }.flatMapLatest { enabled ->
|
||||
if (!enabled) {
|
||||
@@ -161,22 +152,17 @@ class SteamVRCheckBehaviour(private val server: VRServer, private val settings:
|
||||
return@map SteamVRState(true, drivers)
|
||||
}
|
||||
|
||||
val protoDriverActiveFlow = server.context.state.map { state ->
|
||||
state.drivers.values.any { it.source == DriverBridgeSource.DRIVER }
|
||||
}
|
||||
val solarXRDriverActiveFlow = server.context.state.flatMapLatest { state ->
|
||||
combine(state.solarxr.values.map { it.context.state }) { states ->
|
||||
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(protoDriverActiveFlow, solarXRDriverActiveFlow, steamVRState) { protoDriverActive, (anySolarXRDriverActive, steamVRSolarXRDriverActive), steamVRState ->
|
||||
combine(solarXRDriverActiveFlow, steamVRState) { (anyDriverActive, steamVRDriverActive), steamVRState ->
|
||||
// if a non-SteamVR driver is connected, we shouldn't try to fetch the drivers list
|
||||
if (anySolarXRDriverActive && !steamVRSolarXRDriverActive) {
|
||||
if (anyDriverActive && !steamVRDriverActive) {
|
||||
return@combine buildSteamVRDriverStep(connected = true) to buildStandableStep(supported = false)
|
||||
}
|
||||
// for output state
|
||||
val anyDriverActive = protoDriverActive || anySolarXRDriverActive
|
||||
|
||||
if (steamVRState.drivers == null) {
|
||||
return@combine buildSteamVRDriverStep(connected = anyDriverActive) to buildStandableStep()
|
||||
|
||||
Reference in new issue
Block a user