diff --git a/server/README.md b/server/README.md index 0b2554697..1bdfdd204 100644 --- a/server/README.md +++ b/server/README.md @@ -343,16 +343,14 @@ The server exposes four connection points: | Transport | Client | Protocol | |---|---|---| -| Unix socket / named pipe `SlimeVRDriver` | OpenVR driver | Protobuf (Wire) | -| Unix socket / named pipe `SlimeVRInput` | External feeder | Protobuf (Wire) | -| Unix socket / named pipe `SlimeVRRpc` | SolarXR (IPC path) | FlatBuffers | +| Unix socket `SlimeVRRpc` | SolarXR (IPC path) | FlatBuffers | | WebSocket port 21110 | GUI / third-party (SolarXR) | FlatBuffers | **Why separate transport from protocol?** -Platform files (`linux.kt`, `windows.kt`) own reading frames off a socket and produce a `Flow` + a `send` function. Protocol handlers (`protocol.kt`, `ipc.kt`) are plain `suspend fun`s that take those two things and know nothing about Unix sockets or named pipes. +Platform files (e.g. `unix.kt`) own reading frames off a socket and produce a `Flow` + a `send` function. Protocol handlers (`protocol.kt`, `ipc.kt`) are plain `suspend fun`s that take those two things and know nothing about the specific transport being used. -The same `handleSolarXRBridge` function runs on Linux sockets, Windows pipes, and WebSocket. The WebSocket adapter in `ws-server.kt` converts Ktor frames to the same `Flow` + `send` abstraction. The handler never changes. +The same `handleSolarXRBridge` function runs on Unix domain sockets, and WebSocket. The WebSocket adapter in `ws-server.kt` converts Ktor frames to the same `Flow` + `send` abstraction. The handler never changes. **Why events for IPC message routing?** diff --git a/server/core/src/main/java/dev/slimevr/driver/behaviours.kt b/server/core/src/main/java/dev/slimevr/driver/behaviours.kt deleted file mode 100644 index 69b258e45..000000000 --- a/server/core/src/main/java/dev/slimevr/driver/behaviours.kt +++ /dev/null @@ -1,221 +0,0 @@ -package dev.slimevr.driver - -import dev.slimevr.VRServerActions -import dev.slimevr.device.Device -import dev.slimevr.device.DeviceActions -import dev.slimevr.skeleton.BodyPartMap -import dev.slimevr.skeleton.bodyPartMap -import dev.slimevr.skeleton.forEachBone -import dev.slimevr.tracker.Tracker -import dev.slimevr.tracker.TrackerActions -import dev.slimevr.tracker.TrackerState -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.onEach -import solarxr_protocol.datatypes.BodyPart -import solarxr_protocol.datatypes.DeviceOrigin -import solarxr_protocol.datatypes.TrackerStatus -import solarxr_protocol.rpc.RoutingOutput - -class DriverOutgoingTrackersBehaviour : DriverBridgeBehaviour { - // Fallback chain per bone, used to attribute battery and status to the nearest - // physical tracker. Bones without an entry just report no battery. - val bodyPartToNearest: BodyPartMap> = BodyPartMap( - mapOf( - BodyPart.UPPER_CHEST to setOf(BodyPart.UPPER_CHEST, BodyPart.CHEST), - BodyPart.HIP to setOf(BodyPart.HIP, BodyPart.WAIST, BodyPart.CHEST, BodyPart.UPPER_CHEST), - BodyPart.LEFT_UPPER_LEG to setOf(BodyPart.LEFT_UPPER_LEG), - BodyPart.RIGHT_UPPER_LEG to setOf(BodyPart.RIGHT_UPPER_LEG), - BodyPart.LEFT_FOOT to setOf(BodyPart.LEFT_FOOT, BodyPart.LEFT_LOWER_LEG), - BodyPart.RIGHT_FOOT to setOf(BodyPart.RIGHT_FOOT, BodyPart.RIGHT_LOWER_LEG), - BodyPart.LEFT_UPPER_ARM to setOf(BodyPart.LEFT_UPPER_ARM, BodyPart.LEFT_LOWER_ARM), - BodyPart.RIGHT_UPPER_ARM to setOf(BodyPart.RIGHT_UPPER_ARM, BodyPart.RIGHT_LOWER_ARM), - BodyPart.LEFT_HAND to setOf(BodyPart.LEFT_HAND, BodyPart.LEFT_LOWER_ARM), - BodyPart.RIGHT_HAND to setOf(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LOWER_ARM), - ), - ) - - override fun observe(receiver: DriverBridge) { - // Should be safe: StateFlow never delivers two emissions concurrently to the same collector. - val subscribedTrackers = mutableSetOf() - - // Status and battery are rebuilt every frame but only change every few seconds, so the driver - // was being sent the same values at skeleton rate. Keep the last one per body part and only - // send on a real change, the same way subscribedTrackers already gates TrackerAdded. - val lastStatus = mutableMapOf() - - combine( - receiver.appContext.skeleton.computed, - receiver.appContext.boneRouting.context.state - .map { state -> state.routes.filterValues { RoutingOutput.DRIVER in it }.keys } - .distinctUntilChanged(), - ::Pair, - ) - .distinctUntilChanged() - .onEach { (computedSkeleton, enabledBodyParts) -> - val serverState = receiver.appContext.server.context.state.value - - // Map the nearest trackers to their body parts - val trackerStateByBodyPart = bodyPartMap() - for (tracker in serverState.trackers.values) { - val trackerState = tracker.context.state.value - if (trackerState.origin == DeviceOrigin.DRIVER) continue - val bodyPart = trackerState.bodyPart ?: continue - trackerStateByBodyPart.putIfAbsent(bodyPart, trackerState) - } - - computedSkeleton.forEachBone { part, state -> - if (enabledBodyParts.contains(part)) { - val closestTracker = bodyPartToNearest[part].orEmpty() - .firstNotNullOfOrNull { fallbackPart -> trackerStateByBodyPart[fallbackPart] } - val closestDevice = serverState.devices[closestTracker?.deviceId]?.context?.state?.value - - val newTracker = subscribedTrackers.add(part.value) - if (newTracker) { - // FIXME : sometimes doesn't work when launching SteamVR after SlimeVR - receiver.outbound.emit( - DriverBridgeOutbound.TrackerAdded( - trackerId = part.value.toInt(), - part = part, - ), - ) - } - - receiver.outbound.emit( - DriverBridgeOutbound.TrackerPosition( - trackerId = part.value.toInt(), - rotation = state.rotation, - position = state.tailPosition, - ), - ) - - val status = DriverBridgeOutbound.TrackerStatus( - trackerId = part.value.toInt(), - battery = closestDevice?.batteryLevel ?: 1f, - charging = closestDevice?.batteryVoltage != null && closestDevice.batteryVoltage >= 4.3f, - status = closestTracker?.status ?: TrackerStatus.OK, - ) - if (lastStatus.put(part.value, status) != status) receiver.outbound.emit(status) - } else { - val status = DriverBridgeOutbound.TrackerStatus( - trackerId = part.value.toInt(), - battery = null, - charging = false, - status = TrackerStatus.DISCONNECTED, - ) - if (lastStatus.put(part.value, status) != status) receiver.outbound.emit(status) - } - } - }.launchIn(receiver.context.scope) - } -} - -class DriverIncomingTrackersBehaviour : DriverBridgeBehaviour { - override fun observe(receiver: DriverBridge) { - receiver.inbound.on { event -> - receiver.context.dispatch(DriverBridgeActions.UpdateProtocolVersion(event.protocolVersion)) - }.launchIn(receiver.context.scope) - - receiver.inbound.on { event -> - handleTrackerAdded( - receiver, - event.id, - event.name, - event.manufacturer, - event.serial, - event.bodyPart, - ) - }.launchIn(receiver.context.scope) - - receiver.inbound.on { event -> - val trackerId = receiver.context.state.value.trackers[event.id] ?: return@on - receiver.appContext.server.getTracker(trackerId)?.context?.dispatch( - TrackerActions.SetStatus(status = event.status), - ) - }.launchIn(receiver.context.scope) - - receiver.inbound.on { event -> - val trackerId = receiver.context.state.value.trackers[event.id] ?: return@on - receiver.appContext.server.getTracker(trackerId)?.setRotation(rotation = event.rotation, position = event.position) - }.launchIn(receiver.context.scope) - - receiver.inbound.on { event -> - val trackerId = receiver.context.state.value.trackers[event.id] ?: return@on - receiver.appContext.server.getTracker(trackerId)?.let { tracker -> - val device = - tracker.appContext.server.getDevice(tracker.context.state.value.deviceId) - ?: error("could not find device") - device.context.dispatch( - DeviceActions.Update { - copy( - batteryLevel = event.batteryLevel / 100f, - batteryVoltage = if (event.charging) 4.3f else 3.7f, - ) - }, - ) - } - }.launchIn(receiver.context.scope) - } - - private fun handleTrackerAdded( - receiver: DriverBridge, - id: Int, - name: String, - manufacturer: String, - serial: String, - bodyPart: BodyPart?, - ) { - val server = receiver.appContext.server - val scope = server.context.scope - val existingTracker = server.context.state.value.trackers.values - .find { tracker -> tracker.context.state.value.hardwareId == serial } - - val (device, tracker) = if (existingTracker != null) { - val device = server.getDevice(existingTracker.context.state.value.deviceId) - ?: error("could not find existing device for serial $serial") - existingTracker.context.dispatch(TrackerActions.Update { copy(intendedBodyPart = bodyPart) }) - Pair(device, existingTracker) - } else { - val deviceId = server.nextHandle() - val newDevice = Device.create( - scope = scope, - appContext = receiver.appContext, - id = deviceId, - name = name, - manufacturer = manufacturer, - address = serial, - macAddress = serial, - origin = DeviceOrigin.DRIVER, - protocolVersion = 0, - ) - server.context.dispatch(VRServerActions.NewDevice(deviceId, newDevice)) - - val trackerId = server.nextHandle() - val tracker = Tracker.create( - scope = scope, - id = trackerId, - name = name, - bodyPart = bodyPart, - intendedBodyPart = bodyPart, - deviceId = deviceId, - hardwareId = serial, - origin = DeviceOrigin.DRIVER, - appContext = receiver.appContext, - ) - server.context.dispatch(VRServerActions.NewTracker(trackerId, tracker)) - - Pair(newDevice, tracker) - } - - receiver.context.dispatch( - DriverBridgeActions.AddTracker( - id, - tracker.context.state.value.id, - ), - ) - tracker.context.dispatch(TrackerActions.SetStatus(TrackerStatus.OK)) - device.context.dispatch(DeviceActions.Update { copy(protocolVersion = 0) }) - } -} diff --git a/server/core/src/main/java/dev/slimevr/driver/module.kt b/server/core/src/main/java/dev/slimevr/driver/module.kt deleted file mode 100644 index ca17dbc3c..000000000 --- a/server/core/src/main/java/dev/slimevr/driver/module.kt +++ /dev/null @@ -1,92 +0,0 @@ -package dev.slimevr.driver - -import dev.slimevr.AppContextProvider -import dev.slimevr.EventDispatcher -import dev.slimevr.VRServerActions -import dev.slimevr.context.Behaviour -import dev.slimevr.context.Context -import dev.slimevr.context.ManagedContext -import dev.slimevr.tracker.TrackerActions -import io.github.axisangles.ktmath.Quaternion -import io.github.axisangles.ktmath.Vector3 -import kotlinx.coroutines.CoroutineScope -import solarxr_protocol.datatypes.BodyPart -import solarxr_protocol.datatypes.TrackerStatus - -data class DriverBridgeState( - val protocolVersion: Int, - // SteamVR device index -> Tracker ID - val trackers: Map, -) - -sealed interface DriverBridgeActions { - data class AddTracker(val id: Int, val trackerId: Int) : DriverBridgeActions - data class UpdateProtocolVersion(val version: Int) : DriverBridgeActions -} - -sealed interface DriverBridgeInbound { - data class Version(val protocolVersion: Int) : DriverBridgeInbound - data class TrackerAdded(val id: Int, val name: String, val manufacturer: String, val serial: String, val bodyPart: BodyPart?) : DriverBridgeInbound - data class TrackerStatus(val id: Int, val status: solarxr_protocol.datatypes.TrackerStatus) : DriverBridgeInbound - data class TrackerPosition(val id: Int, val rotation: Quaternion, val position: Vector3?) : DriverBridgeInbound - data class TrackerBattery(val id: Int, val batteryLevel: Float, val charging: Boolean) : DriverBridgeInbound -} - -sealed interface DriverBridgeOutbound { - data class TrackerAdded(val trackerId: Int, val part: BodyPart) : DriverBridgeOutbound - data class TrackerStatus(val trackerId: Int, val status: solarxr_protocol.datatypes.TrackerStatus, val battery: Float?, val charging: Boolean) : DriverBridgeOutbound - data class TrackerPosition(val trackerId: Int, val rotation: Quaternion, val position: Vector3?) : DriverBridgeOutbound -} - -typealias DriverBridgeContext = Context -typealias DriverBridgeBehaviour = Behaviour - -enum class DriverBridgeSource { - DRIVER, - FEEDER, -} - -class DriverBridge( - val id: Int, - val source: DriverBridgeSource, - val context: DriverBridgeContext, - val appContext: AppContextProvider, - val inbound: EventDispatcher = EventDispatcher("Driver.inbound", context.scope, capacity = 128, verboseMetrics = false), - val outbound: EventDispatcher = EventDispatcher("Driver.outbound", context.scope, capacity = 512), - private val managedContext: ManagedContext? = null, -) { - fun dispose() = managedContext?.dispose() - - fun startObserving() = context.observeAll(this) - - fun disconnect() { - dispose() - appContext.server.context.dispatch(VRServerActions.DriverDisconnected(id)) - context.state.value.trackers.forEach { (_, id) -> - appContext.server.getTracker(id)?.context?.dispatch(TrackerActions.SetStatus(TrackerStatus.DISCONNECTED)) - } - } - - companion object { - fun create(id: Int, source: DriverBridgeSource, appContext: AppContextProvider, scope: CoroutineScope): DriverBridge { - val behaviours = listOf(DriverOutgoingTrackersBehaviour(), DriverIncomingTrackersBehaviour()) - - val managedContext = ManagedContext.create( - initialState = DriverBridgeState( - protocolVersion = 0, - trackers = emptyMap(), - ), - scope = scope, - reducer = ::reduce, - behaviours = behaviours, - name = "Driver[$id]", - ) - - val bridge = DriverBridge(id = id, source = source, context = managedContext.context, appContext = appContext, managedContext = managedContext) - bridge.startObserving() - appContext.server.context.dispatch(VRServerActions.DriverConnected(bridge)) - - return bridge - } - } -} diff --git a/server/core/src/main/java/dev/slimevr/driver/reducer.kt b/server/core/src/main/java/dev/slimevr/driver/reducer.kt deleted file mode 100644 index e25fee915..000000000 --- a/server/core/src/main/java/dev/slimevr/driver/reducer.kt +++ /dev/null @@ -1,9 +0,0 @@ -package dev.slimevr.driver - -fun reduce( - state: DriverBridgeState, - action: DriverBridgeActions, -): DriverBridgeState = when (action) { - is DriverBridgeActions.AddTracker -> state.copy(trackers = state.trackers + (action.id to action.trackerId)) - is DriverBridgeActions.UpdateProtocolVersion -> state.copy(protocolVersion = action.version) -} diff --git a/server/core/src/main/java/dev/slimevr/driver/roles.kt b/server/core/src/main/java/dev/slimevr/driver/roles.kt deleted file mode 100644 index 2fdf93279..000000000 --- a/server/core/src/main/java/dev/slimevr/driver/roles.kt +++ /dev/null @@ -1,66 +0,0 @@ -package dev.slimevr.driver - -import dev.slimevr.skeleton.BodyPartMap -import solarxr_protocol.datatypes.BodyPart - -/** - * Tracker roles the driver understands, SteamVR or Monado alike. - * The values are the wire numbers used by the driver IPC protobuf. - */ -enum class TrackerRole( - val value: UByte, -) { - NONE(0.toUByte()), - WAIST(1.toUByte()), - LEFT_FOOT(2.toUByte()), - RIGHT_FOOT(3.toUByte()), - CHEST(4.toUByte()), - LEFT_KNEE(5.toUByte()), - RIGHT_KNEE(6.toUByte()), - LEFT_ELBOW(7.toUByte()), - RIGHT_ELBOW(8.toUByte()), - LEFT_SHOULDER(9.toUByte()), - RIGHT_SHOULDER(10.toUByte()), - LEFT_HAND(11.toUByte()), - RIGHT_HAND(12.toUByte()), - LEFT_CONTROLLER(13.toUByte()), - RIGHT_CONTROLLER(14.toUByte()), - HEAD(15.toUByte()), - NECK(16.toUByte()), - CAMERA(17.toUByte()), - KEYBOARD(18.toUByte()), - HMD(19.toUByte()), - BEACON(20.toUByte()), - GENERIC_CONTROLLER(21.toUByte()), - ; - - companion object { - fun fromValue(value: UByte): TrackerRole? = entries.firstOrNull { it.value == value } - } -} - -val bodyPartToRole: BodyPartMap = BodyPartMap( - mapOf( - BodyPart.HEAD to TrackerRole.HMD, - BodyPart.UPPER_CHEST to TrackerRole.CHEST, - BodyPart.LEFT_UPPER_ARM to TrackerRole.LEFT_ELBOW, - BodyPart.RIGHT_UPPER_ARM to TrackerRole.RIGHT_ELBOW, - BodyPart.HIP to TrackerRole.WAIST, - BodyPart.LEFT_UPPER_LEG to TrackerRole.LEFT_KNEE, - BodyPart.RIGHT_UPPER_LEG to TrackerRole.RIGHT_KNEE, - BodyPart.LEFT_FOOT to TrackerRole.LEFT_FOOT, - BodyPart.RIGHT_FOOT to TrackerRole.RIGHT_FOOT, - BodyPart.LEFT_SHOULDER to TrackerRole.LEFT_SHOULDER, - BodyPart.RIGHT_SHOULDER to TrackerRole.RIGHT_SHOULDER, - BodyPart.LEFT_HAND to TrackerRole.LEFT_HAND, - BodyPart.RIGHT_HAND to TrackerRole.RIGHT_HAND, - ), -) - -val roleToBodyPart = bodyPartToRole.entries.associate { (k, v) -> v to k } - -/** - * Bones the driver output can accept. Used by the routing module. - * HEAD is the HMD coming in, we never send it. - */ -val DRIVER_SUPPORTED_BONES: Set = bodyPartToRole.keys - BodyPart.HEAD diff --git a/server/core/src/main/java/dev/slimevr/reducer.kt b/server/core/src/main/java/dev/slimevr/reducer.kt index 00f977e35..3faf00c44 100644 --- a/server/core/src/main/java/dev/slimevr/reducer.kt +++ b/server/core/src/main/java/dev/slimevr/reducer.kt @@ -3,8 +3,6 @@ package dev.slimevr fun reduce(state: VRServerState, action: VRServerActions): VRServerState = when (action) { is VRServerActions.NewTracker -> state.copy(trackers = state.trackers + (action.trackerId to action.context)) is VRServerActions.NewDevice -> state.copy(devices = state.devices + (action.deviceId to action.context)) - is VRServerActions.DriverConnected -> state.copy(drivers = state.drivers + (action.bridge.id to action.bridge)) - is VRServerActions.DriverDisconnected -> state.copy(drivers = state.drivers - action.bridgeId) is VRServerActions.SolarXRConnected -> state.copy(solarxr = state.solarxr + (action.connection.id to action.connection)) is VRServerActions.SolarXRDisconnected -> state.copy(solarxr = state.solarxr - action.connectionId) is VRServerActions.NewDongle -> state.copy(dongles = state.dongles + (action.dongleId to action.context)) diff --git a/server/core/src/main/java/dev/slimevr/routing/routing.kt b/server/core/src/main/java/dev/slimevr/routing/routing.kt index b8df600e2..2540acb49 100644 --- a/server/core/src/main/java/dev/slimevr/routing/routing.kt +++ b/server/core/src/main/java/dev/slimevr/routing/routing.kt @@ -2,8 +2,7 @@ package dev.slimevr.routing import dev.slimevr.AppContextProvider import dev.slimevr.config.BoneRoutingConfig -import dev.slimevr.driver.DRIVER_SUPPORTED_BONES -import dev.slimevr.driver.DriverBridgeSource +import dev.slimevr.solarxr.driver.DRIVER_SUPPORTED_BONES import dev.slimevr.tracker.TrackerState import dev.slimevr.util.isActive import dev.slimevr.vmc.VMC_SUPPORTED_BONES @@ -62,19 +61,16 @@ fun isActive(states: OutputStates, output: RoutingOutput): Boolean = states[outp @OptIn(ExperimentalCoroutinesApi::class) fun driverStateFlow(appContext: AppContextProvider): Flow = combine( appContext.config.settings.context.state.map { it.data.driverConfig.enabled }, - appContext.server.context.state.map { state -> - state.drivers.values.any { it.source == DriverBridgeSource.DRIVER } - }, - appContext.server.context.state.flatMapLatest { state -> - combine(state.solarxr.values.map { it.context.state }) { states -> + appContext.server.context.state.map { it.solarxr }.distinctUntilChanged().flatMapLatest { solarXRBridges -> + combine(solarXRBridges.values.map { it.context.state }) { states -> states.any { it.driverName != null } } }, -) { enabled, driverConnected, solarXRDriverConnected -> +) { enabled, solarXRDriverConnected -> when { !appContext.featureFlags.supportsDriver -> RoutingOutputState.UNSUPPORTED !enabled -> RoutingOutputState.INACTIVE - driverConnected || solarXRDriverConnected -> RoutingOutputState.ACTIVE + solarXRDriverConnected -> RoutingOutputState.ACTIVE else -> RoutingOutputState.ENABLED } }.distinctUntilChanged() diff --git a/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt b/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt index 6bd05d1aa..4536c328c 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/driver/outgoing.kt @@ -21,6 +21,21 @@ import solarxr_protocol.datatypes.DeviceOrigin import solarxr_protocol.driver_protocol.BoneBatteryUpdate import solarxr_protocol.driver_protocol.SkeletonUpdate +val DRIVER_SUPPORTED_BONES = setOf( + BodyPart.UPPER_CHEST, + BodyPart.LEFT_UPPER_ARM, + BodyPart.RIGHT_UPPER_ARM, + BodyPart.HIP, + BodyPart.LEFT_UPPER_LEG, + BodyPart.RIGHT_UPPER_LEG, + BodyPart.LEFT_FOOT, + BodyPart.RIGHT_FOOT, + BodyPart.LEFT_SHOULDER, + BodyPart.RIGHT_SHOULDER, + BodyPart.LEFT_HAND, + BodyPart.RIGHT_HAND, +) + class DriverOutgoingTrackersBehaviour( private val appContext: AppContextProvider, ) : SolarXRBridgeBehaviour { diff --git a/server/core/src/main/java/dev/slimevr/solarxr/module.kt b/server/core/src/main/java/dev/slimevr/solarxr/module.kt index c1f716b5f..fa06f8632 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/module.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/module.kt @@ -56,7 +56,7 @@ import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds data class SolarXRBridgeState( - val dataFeedConfigs: List, + val dataFeedConfigs: List = emptyList(), val driverName: String? = null, val boneMask: BoneMask? = null, ) @@ -217,7 +217,7 @@ class SolarXRBridge( extraBehaviours: (AppContextProvider) -> List = { emptyList() }, ): SolarXRBridge { val managedContext = ManagedContext.create( - initialState = SolarXRBridgeState(dataFeedConfigs = listOf()), + initialState = SolarXRBridgeState(), scope = scope, reducer = ::reduce, behaviours = buildBehaviours(appContext) + extraBehaviours(appContext), diff --git a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt index 8fd03e6be..5bcf7f335 100644 --- a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt @@ -6,7 +6,6 @@ import dev.slimevr.VRServer import dev.slimevr.VRServerState import dev.slimevr.config.Settings import dev.slimevr.device.DeviceState -import dev.slimevr.driver.DriverBridgeSource import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.resets.ResetBodyParts import dev.slimevr.resets.ResetsManager @@ -218,9 +217,11 @@ class SteamVRHandsCheckBehaviour( combine( trackerStates, boneRouting.context.state.map { state -> state.routes }, - server.context.state - .map { state -> state.drivers.values.any { it.source == DriverBridgeSource.DRIVER } } - .distinctUntilChanged(), + server.context.state.map { it.solarxr }.distinctUntilChanged().flatMapLatest { solarXRBridges -> + combine(solarXRBridges.values.map { it.context.state }) { states -> + states.any { it.driverName != null } + } + }, ::computeStep, ) .distinctUntilChanged() diff --git a/server/core/src/main/java/dev/slimevr/vrserver.kt b/server/core/src/main/java/dev/slimevr/vrserver.kt index 8048fdee4..185c7a92e 100644 --- a/server/core/src/main/java/dev/slimevr/vrserver.kt +++ b/server/core/src/main/java/dev/slimevr/vrserver.kt @@ -3,7 +3,6 @@ package dev.slimevr import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import dev.slimevr.device.Device -import dev.slimevr.driver.DriverBridge import dev.slimevr.hid.HIDReceiver import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.tracker.Tracker @@ -17,15 +16,12 @@ data class VRServerState( val trackers: Map, val devices: Map, val dongles: Map, - val drivers: Map, val solarxr: Map, ) sealed interface VRServerActions { data class NewTracker(val trackerId: Int, val context: Tracker) : VRServerActions data class NewDevice(val deviceId: Int, val context: Device) : VRServerActions - data class DriverConnected(val bridge: DriverBridge) : VRServerActions - data class DriverDisconnected(val bridgeId: Int) : VRServerActions data class SolarXRConnected(val connection: SolarXRBridge) : VRServerActions data class SolarXRDisconnected(val connectionId: Int) : VRServerActions data class NewDongle(val dongleId: Int, val context: HIDReceiver) : VRServerActions @@ -59,7 +55,6 @@ class VRServer( initialState = VRServerState( trackers = emptyMap(), devices = emptyMap(), - drivers = emptyMap(), solarxr = emptyMap(), dongles = emptyMap(), ), diff --git a/server/core/src/test/java/dev/slimevr/TestServer.kt b/server/core/src/test/java/dev/slimevr/TestServer.kt index fcc513d2a..9bf0ac972 100644 --- a/server/core/src/test/java/dev/slimevr/TestServer.kt +++ b/server/core/src/test/java/dev/slimevr/TestServer.kt @@ -13,10 +13,6 @@ import dev.slimevr.config.UserConfig import dev.slimevr.config.UserConfigData import dev.slimevr.config.UserConfigState import dev.slimevr.context.Context -import dev.slimevr.driver.DriverBridge -import dev.slimevr.driver.DriverBridgeActions -import dev.slimevr.driver.DriverBridgeSource -import dev.slimevr.driver.DriverBridgeState import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationActions import dev.slimevr.heightcalibration.HeightCalibrationManager @@ -36,6 +32,9 @@ import dev.slimevr.skeleton.DEFAULT_SKELETON_STATE import dev.slimevr.skeleton.ProportionsBehaviour import dev.slimevr.skeleton.Skeleton import dev.slimevr.skeleton.buildBones +import dev.slimevr.solarxr.SolarXRBridge +import dev.slimevr.solarxr.SolarXRBridgeState +import dev.slimevr.solarxr.driver.DriverHandshakeBehaviour import dev.slimevr.solarxr.rpc.ServerInfos import dev.slimevr.tapdetection.TapDetectionManager import dev.slimevr.tracker.Motion @@ -60,12 +59,12 @@ import solarxr_protocol.datatypes.TrackerStatus import solarxr_protocol.datatypes.hardware_info.ImuType import solarxr_protocol.rpc.UserHeightCalibrationStatus import dev.slimevr.config.reduce as reduceConfig -import dev.slimevr.driver.reduce as reduceDriverBridge import dev.slimevr.heightcalibration.reduce as reduceHeightCalibration import dev.slimevr.resets.reduce as reduceResets import dev.slimevr.skeleton.reduce as reduceSkeleton import dev.slimevr.tracker.reduce as reduceTracker import dev.slimevr.udp.reduce as reduceUdpServer +import dev.slimevr.solarxr.reduce as reduceSolarXR fun buildTestSerialServer(scope: CoroutineScope) = SerialServer.create( openPort = { loc, _, _ -> SerialPortHandle(loc, "Fake $loc", {}, {}) }, @@ -198,15 +197,15 @@ fun buildTestSettings(scope: CoroutineScope): Settings { return Settings(context, scope, NoopConfigStorage, "settings") } -fun buildTestDriverBridge(server: VRServer, appContext: AppContextProvider, id: Int): DriverBridge { - val context = Context.create( - initialState = DriverBridgeState(protocolVersion = 0, trackers = emptyMap()), - scope = server.context.scope, - reducer = ::reduceDriverBridge, - behaviours = emptyList(), - name = "TestDriver[$id]", +fun buildTestSolarXR(scope: CoroutineScope, appContext: AppContextProvider): SolarXRBridge { + val context = Context.create( + initialState = SolarXRBridgeState(), + scope = scope, + reducer = ::reduceSolarXR, + behaviours = listOf(DriverHandshakeBehaviour(appContext)), + name = "SolarXR[test]", ) - return DriverBridge(id = id, source = DriverBridgeSource.DRIVER, context = context, appContext = appContext) + return SolarXRBridge(id = 0, context = context, appContext = appContext) } fun buildTestHeightCalibration(server: VRServer, userConfig: UserConfig, scope: CoroutineScope): HeightCalibrationManager { diff --git a/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt b/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt index 6edb97d5b..88e96c3e1 100644 --- a/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt +++ b/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt @@ -1,6 +1,6 @@ package dev.slimevr.routing -import dev.slimevr.driver.DRIVER_SUPPORTED_BONES +import dev.slimevr.solarxr.driver.DRIVER_SUPPORTED_BONES import dev.slimevr.vmc.VMC_SUPPORTED_BONES import dev.slimevr.vrcosc.VRC_OSC_SUPPORTED_BONES import solarxr_protocol.datatypes.BodyPart diff --git a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt index f351edd38..991d8e39d 100644 --- a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt +++ b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt @@ -3,9 +3,9 @@ package dev.slimevr.trackingchecklist import dev.slimevr.TestAppContext import dev.slimevr.VRServer import dev.slimevr.VRServerActions -import dev.slimevr.buildTestDriverBridge import dev.slimevr.buildTestResetsManager import dev.slimevr.buildTestSettings +import dev.slimevr.buildTestSolarXR import dev.slimevr.buildTestTracker import dev.slimevr.buildTestVrServer import dev.slimevr.config.Settings @@ -18,6 +18,7 @@ import dev.slimevr.resets.ResetsActions import dev.slimevr.resets.ResetsManager import dev.slimevr.routing.BoneRoutingActions import dev.slimevr.routing.BoneRoutingManager +import dev.slimevr.solarxr.onSolarXRMessage import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import io.github.axisangles.ktmath.Vector3 @@ -27,10 +28,13 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest +import solarxr_protocol.MessageBundle import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.DeviceOrigin import solarxr_protocol.datatypes.TrackerStatus import solarxr_protocol.datatypes.hardware_info.ImuType +import solarxr_protocol.driver_protocol.DriverMessageHeader +import solarxr_protocol.driver_protocol.HandshakeRequest import solarxr_protocol.rpc.ResetType import solarxr_protocol.rpc.RoutingOutput import solarxr_protocol.rpc.TrackingChecklistStep @@ -74,9 +78,11 @@ class TrackingChecklistTest { checklist.context.observeAll(checklist) } - fun connectDriver() { - val bridge = buildTestDriverBridge(server, appContext, id = nextId++) - server.context.dispatch(VRServerActions.DriverConnected(bridge)) + suspend fun connectDriver() { + val bridge = buildTestSolarXR(server.context.scope, appContext) + server.context.dispatch(VRServerActions.SolarXRConnected(bridge)) + + onSolarXRMessage(MessageBundle(driverMsgs = listOf(DriverMessageHeader(message = HandshakeRequest(driverName = "TestDriver")))), bridge) } fun routeToDriver(vararg bones: BodyPart) { diff --git a/server/desktop/build.gradle.kts b/server/desktop/build.gradle.kts index a77c69637..2a5a23828 100644 --- a/server/desktop/build.gradle.kts +++ b/server/desktop/build.gradle.kts @@ -15,7 +15,6 @@ plugins { application id("com.gradleup.shadow") id("com.github.gmazzo.buildconfig") - id("com.squareup.wire") } kotlin { @@ -56,27 +55,12 @@ allprojects { } } -val downloadDriverProto = tasks.register("downloadDriverProto") { - val protoFile = layout.buildDirectory.file("proto/ProtobufMessages.proto") - outputs.file(protoFile) - doLast { - val url = "https://raw.githubusercontent.com/SlimeVR/SlimeVR-OpenVR-Driver/main/src/bridge/ProtobufMessages.proto" - protoFile.get().asFile.parentFile.mkdirs() - URI(url).toURL().openStream().use { it.copyTo(protoFile.get().asFile.outputStream()) } - } -} - -wire { - sourcePath { - srcDir(downloadDriverProto.map { layout.buildDirectory.dir("proto") }) - } - kotlin { } -} - dependencies { implementation(project(":server:core")) implementation(project(":solarxr-protocol:generated")) implementation("com.google.flatbuffers:flatbuffers-java:22.10.26") + implementation("com.squareup.okio:okio:3.18.1") + implementation("com.github.loucass003:EspflashKotlin:v0.11.0") implementation("net.java.dev.jna:jna:5.+") diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt index a455a8fb2..b470c8859 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt @@ -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 - } - } - } -} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/pipe-slot.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/pipe-slot.kt deleted file mode 100644 index 7f5ed2f35..000000000 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/pipe-slot.kt +++ /dev/null @@ -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) - } -} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/protocol.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/protocol.kt deleted file mode 100644 index 6641ccf26..000000000 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/protocol.kt +++ /dev/null @@ -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, - 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 { 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 { 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 { 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() - } -} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/linux.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/unix.kt similarity index 85% rename from server/desktop/src/main/java/dev/slimevr/desktop/ipc/linux.kt rename to server/desktop/src/main/java/dev/slimevr/desktop/ipc/unix.kt index e5e89625b..8b443eae6 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/linux.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/unix.kt @@ -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( diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/windows.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/windows.kt deleted file mode 100644 index 46eda50f2..000000000 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/windows.kt +++ /dev/null @@ -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) - } - } - } - } -} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt b/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt index 9b3f273b0..269ec1d9a 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/trackingchecklist/behaviours.kt @@ -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?) + @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()