Forget tracker + better unknown device handling

This commit is contained in:
loucass003 committed 2026-10-15 07:15:06 +02:00
1 parent b8a4be7c36
commit 4e49f3aea2
31 files changed
+925 -193

No files matched your search

@@ -2,8 +2,17 @@ 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.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))
is VRServerActions.DeviceRemoved -> state.copy(
devices = state.devices - action.deviceId,
trackers = state.trackers - action.trackerIds.toSet(),
)
}
@@ -16,7 +16,7 @@ import dev.slimevr.solarxr.toQuat
import dev.slimevr.solarxr.toVec3f
import dev.slimevr.tracker.Motion
import dev.slimevr.tracker.TrackerState
import dev.slimevr.util.stripIpAddressPort
import dev.slimevr.util.ipv4AddressFromString
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
@@ -47,15 +47,6 @@ import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.TimeSource
private fun ipv4AddressFromString(address: String): UInt {
val parts = stripIpAddressPort(address).split('.')
if (parts.size != 4) return 0u
return parts.fold(0u) { acc, part ->
val value = part.toUIntOrNull()?.takeIf { it <= 255u } ?: return 0u
(acc shl 8) or value
}
}
private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMask: TrackerDataMask): TrackerData = TrackerData(
deviceId = device.id.toUShort(),
trackerId = tracker.id.toUShort(),
@@ -200,7 +200,7 @@ class SolarXRBridge(
add(HIDSettingsBehaviour(appContext.config.settings))
add(ErrorReportingSettingsBehaviour(appContext.config.globalConfig, appContext.errorReporting))
add(ProfilesBehaviour(appContext.config))
add(SettingsResetBehaviour(appContext.config))
add(SettingsResetBehaviour(appContext))
add(SettingsDefaultsBehaviour())
add(SkeletonSettingsBehaviour(appContext.config.settings))
add(SkeletonProportionsBehaviour(appContext.config.userConfig, appContext.skeleton, appContext.errorReporting))
@@ -214,7 +214,7 @@ class SolarXRBridge(
add(DriverIncomingTrackersBehaviour(appContext))
add(MagBehaviour(appContext))
add(TimeoutSettingsBehaviour(appContext.config.settings))
add(KnownTrackersBehaviour(appContext.config.settings))
add(KnownTrackersBehaviour(appContext))
add(BvhBehaviour(appContext.bvhManager))
add(InstalledInfoBehaviour())
add(ServerInfosBehaviour(appContext.serverInfos))
@@ -1,24 +1,63 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.config.Settings
import dev.slimevr.AppContextProvider
import dev.slimevr.config.SettingsActions
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import dev.slimevr.udp.UdpServerActions
import dev.slimevr.udp.UnknownDeviceState
import dev.slimevr.udp.forgetUdpDevice
import dev.slimevr.util.ipv4AddressFromString
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.rpc.AddUnknownDeviceRequest
import solarxr_protocol.rpc.ForgetDeviceRequest
import solarxr_protocol.rpc.IgnoreUnknownDeviceRequest
import solarxr_protocol.rpc.UnknownDevice
import solarxr_protocol.rpc.UnknownDeviceStatus
import solarxr_protocol.rpc.UnknownDevicesResponse
internal fun createUnknownDevice(device: UnknownDeviceState, allowedMacs: Set<String>) = UnknownDevice(
macAddress = device.macAddress,
ipAddress = ipv4AddressFromString(device.address),
boardType = device.boardType,
mcuType = device.mcuType,
firmwareVersion = device.firmwareVersion,
status = if (device.macAddress in allowedMacs) UnknownDeviceStatus.ADDING else UnknownDeviceStatus.WAITING,
)
class KnownTrackersBehaviour(
private val settings: Settings,
private val appContext: AppContextProvider,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
val udpServer = appContext.udpServer
receiver.rpcDispatcher.on<AddUnknownDeviceRequest> { req ->
val mac = req.macAddress ?: return@on
settings.context.dispatch(SettingsActions.AddAllowedUdpDevice(mac))
appContext.config.settings.context.dispatch(SettingsActions.AddAllowedUdpDevice(mac))
}.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<IgnoreUnknownDeviceRequest> { req ->
val mac = req.macAddress ?: return@on
udpServer.context.dispatch(UdpServerActions.IgnoreUnknownDevice(mac))
}.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<ForgetDeviceRequest> { req ->
val mac = req.macAddress ?: return@on
settings.context.dispatch(SettingsActions.RemoveAllowedUdpDevice(mac))
forgetUdpDevice(appContext, mac)
}.launchIn(receiver.context.scope)
combine(
udpServer.context.state.map { it.unknownDevices },
appContext.config.settings.context.state.map { it.data.allowedUdpDevices },
) { unknownDevices, allowedMacs ->
unknownDevices.values.map { createUnknownDevice(it, allowedMacs) }
}
.distinctUntilChanged()
.onEach { devices -> receiver.sendRpc(UnknownDevicesResponse(devices = devices)) }
.launchIn(receiver.context.scope)
}
}
@@ -1,14 +1,18 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.config.AppConfig
import dev.slimevr.AppContextProvider
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import dev.slimevr.udp.forgetAllUdpDevices
import solarxr_protocol.rpc.SettingsResetRequest
class SettingsResetBehaviour(
private val config: AppConfig,
private val appContext: AppContextProvider,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
receiver.rpcDispatcher.on<SettingsResetRequest> { config.reset() }.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<SettingsResetRequest> {
forgetAllUdpDevices(appContext)
appContext.config.reset()
}.launchIn(receiver.context.scope)
}
}
@@ -18,7 +18,6 @@ import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.MagnetometerStatus
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
import solarxr_protocol.rpc.UnknownDeviceHandshakeNotification
import kotlin.random.Random
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
@@ -188,15 +187,25 @@ class HandshakeBehaviour : UDPConnectionBehaviour {
if (mac != null) {
val settings = receiver.appContext.config.settings.context.state.value.data
val udpServer = receiver.appContext.udpServer
if (mac !in settings.allowedUdpDevices) {
AppLogger.udp.info("Unknown MAC $mac, notifying solarxr")
receiver.appContext.server.context.scope.launch {
receiver.appContext.server.sendSolarxrRpc(
UnknownDeviceHandshakeNotification(macAddress = mac),
)
}
udpServer.context.dispatch(
UdpServerActions.UnknownDeviceSeen(
UnknownDeviceState(
macAddress = mac,
address = state.address,
boardType = packet.data.boardType,
mcuType = packet.data.mcuType,
firmwareVersion = packet.data.firmware,
lastSeen = udpServer.clock(),
),
),
)
return@onPacket
}
if (mac in udpServer.context.state.value.unknownDevices) {
udpServer.context.dispatch(UdpServerActions.UnknownDeviceRemoved(mac))
}
}
val device = if (state.deviceId == null) {
@@ -0,0 +1,65 @@
package dev.slimevr.udp
import dev.slimevr.AppContextProvider
import dev.slimevr.VRServerActions
import dev.slimevr.config.SettingsActions
import dev.slimevr.device.Device
import dev.slimevr.logging.AppLogger
import dev.slimevr.skeleton.SkeletonActions
import dev.slimevr.util.isActive
import kotlinx.coroutines.cancel
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerStatus
private fun findUdpDevices(appContext: AppContextProvider, predicate: (String) -> Boolean): List<Device> = appContext.server.context.state.value.devices.values.filter { device ->
val state = device.context.state.value
val mac = state.macAddress
state.origin == DeviceOrigin.UDP && mac != null && predicate(mac)
}
/**
* Disconnects a UDP device and removes it, its trackers and their saved config from the server.
* Leaves the allowed list alone.
*/
fun removeUdpDevice(appContext: AppContextProvider, device: Device) {
val server = appContext.server
val deviceId = device.context.state.value.id
appContext.udpServer.findConnectionForDevice(deviceId)?.let { conn ->
appContext.udpServer.removeConnection(conn.context.state.value.address)
}
val deviceTrackers = server.context.state.value.trackers.values
.filter { it.context.state.value.deviceId == deviceId }
val trackerStates = deviceTrackers.map { it.context.state.value }
// The tracker's own skeleton behaviour dies with its scope, so release its bone here
trackerStates
.filter { it.status.isActive() || it.status == TrackerStatus.OCCLUDED }
.mapNotNull { it.bodyPart }
.forEach { bodyPart ->
appContext.skeleton.context.dispatch(SkeletonActions.DisableBone(bodyPart))
}
deviceTrackers.forEach { it.context.scope.cancel() }
device.context.scope.cancel()
server.context.dispatch(VRServerActions.DeviceRemoved(deviceId, trackerStates.map { it.id }))
// After the scopes are cancelled, so the tracker config behaviour can't write it back
val hardwareIds = trackerStates.map { it.hardwareId }.toSet()
appContext.config.settings.context.dispatch(SettingsActions.Update { copy(trackers = trackers - hardwareIds) })
}
/** Drops a MAC from the allowed list and removes its UDP device from the server. */
suspend fun forgetUdpDevice(appContext: AppContextProvider, mac: String) {
// Removed first so a handshake arriving mid-forget gets rejected instead of recreating the device
appContext.config.settings.context.dispatch(SettingsActions.RemoveAllowedUdpDevice(mac))
findUdpDevices(appContext) { it == mac }.forEach { removeUdpDevice(appContext, it) }
AppLogger.udp.info("Forgot device $mac")
}
suspend fun forgetAllUdpDevices(appContext: AppContextProvider) {
findUdpDevices(appContext) { true }
.mapNotNull { it.context.state.value.macAddress }
.forEach { mac -> forgetUdpDevice(appContext, mac) }
}
@@ -2,5 +2,26 @@ package dev.slimevr.udp
fun reduce(state: UdpServerState, action: UdpServerActions): UdpServerState = when (action) {
is UdpServerActions.ConnectionAdded -> state.copy(connections = state.connections + (action.address to action.conn))
is UdpServerActions.ConnectionRemoved -> state.copy(connections = state.connections - action.address)
is UdpServerActions.UnknownDeviceSeen -> {
val mac = action.device.macAddress
if (mac in state.ignoredMacs) {
state
} else {
state.copy(unknownDevices = state.unknownDevices + (mac to action.device))
}
}
is UdpServerActions.UnknownDeviceRemoved -> state.copy(unknownDevices = state.unknownDevices - action.macAddress)
is UdpServerActions.UnknownDevicesExpired -> state.copy(
unknownDevices = state.unknownDevices.filterValues { it.lastSeen > action.cutoff },
)
is UdpServerActions.IgnoreUnknownDevice -> state.copy(
unknownDevices = state.unknownDevices - action.macAddress,
ignoredMacs = state.ignoredMacs + action.macAddress,
)
}
@@ -25,17 +25,28 @@ import kotlin.time.measureTime
data class UdpServerState(
val connections: Map<String, UDPConnection>,
val unknownDevices: Map<String, UnknownDeviceState> = emptyMap(),
val ignoredMacs: Set<String> = emptySet(),
)
sealed interface UdpServerActions {
data class ConnectionAdded(val address: String, val conn: UDPConnection) : UdpServerActions
data class ConnectionRemoved(val address: String) : UdpServerActions
data class UnknownDeviceSeen(val device: UnknownDeviceState) : UdpServerActions
data class UnknownDeviceRemoved(val macAddress: String) : UdpServerActions
data class UnknownDevicesExpired(val cutoff: Long) : UdpServerActions
data class IgnoreUnknownDevice(val macAddress: String) : UdpServerActions
}
typealias UdpServerContext = Context<UdpServerState, UdpServerActions>
typealias UdpServerBehaviour = Behaviour<UdpServer>
class UdpServer(val context: UdpServerContext, private val addressResolver: (InetSocketAddress) -> String) {
class UdpServer(
val context: UdpServerContext,
// Wall-clock ms, replaceable so tests can run on virtual time
val clock: () -> Long = System::currentTimeMillis,
private val addressResolver: (InetSocketAddress) -> String,
) {
private var receiveJob: Job? = null
fun startObserving() = context.observeAll(this)
@@ -145,14 +156,19 @@ class UdpServer(val context: UdpServerContext, private val addressResolver: (Ine
companion object {
val INITIAL_STATE = UdpServerState(connections = emptyMap())
fun create(scope: CoroutineScope, addressResolver: (InetSocketAddress) -> String): UdpServer {
fun create(
scope: CoroutineScope,
clock: () -> Long = System::currentTimeMillis,
addressResolver: (InetSocketAddress) -> String,
): UdpServer {
val context = Context.create(
initialState = INITIAL_STATE,
scope = scope,
reducer = ::reduce,
behaviours = listOf(UnknownDeviceExpiryBehaviour()),
name = "UdpServer",
)
val server = UdpServer(context, addressResolver)
val server = UdpServer(context, clock, addressResolver)
server.startObserving()
return server
}
@@ -0,0 +1,41 @@
package dev.slimevr.udp
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.transformLatest
import solarxr_protocol.datatypes.hardware_info.BoardType
import solarxr_protocol.datatypes.hardware_info.McuType
// Firmware re-handshakes about once a second while it looks for a server
internal const val UNKNOWN_DEVICE_TIMEOUT_MS = 5000L
/** A device handshaking without being on the allowed list. */
data class UnknownDeviceState(
val macAddress: String,
// Same "ip/port" form as UDPConnectionState.address
val address: String,
val boardType: BoardType,
val mcuType: McuType,
val firmwareVersion: String?,
val lastSeen: Long,
)
class UnknownDeviceExpiryBehaviour : UdpServerBehaviour {
@OptIn(ExperimentalCoroutinesApi::class)
override fun observe(receiver: UdpServer) {
receiver.context.state
.map { state -> state.unknownDevices.values.minOfOrNull { it.lastSeen } }
.distinctUntilChanged()
.transformLatest { oldest ->
if (oldest == null) return@transformLatest
delay(oldest + UNKNOWN_DEVICE_TIMEOUT_MS - receiver.clock())
emit(oldest)
}
.onEach { oldest -> receiver.context.dispatch(UdpServerActions.UnknownDevicesExpired(cutoff = oldest)) }
.launchIn(receiver.context.scope)
}
}
@@ -3,3 +3,12 @@ package dev.slimevr.util
fun stripIpAddressPort(string: String) = string.lastIndexOf('/').takeIf { it != -1 }?.let {
string.substring(0, it)
} ?: string
fun ipv4AddressFromString(address: String): UInt {
val parts = stripIpAddressPort(address).split('.')
if (parts.size != 4) return 0u
return parts.fold(0u) { acc, part ->
val value = part.toUIntOrNull()?.takeIf { it <= 255u } ?: return 0u
(acc shl 8) or value
}
}
@@ -25,6 +25,7 @@ sealed interface 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
data class DeviceRemoved(val deviceId: Int, val trackerIds: List<Int>) : VRServerActions
}
typealias VRServerContext = Context<VRServerState, VRServerActions>