From be34dc981cb6120d8b08e8d707ebf2500c49ba36 Mon Sep 17 00:00:00 2001 From: loucass003 Date: Tue, 5 May 2026 07:35:27 +0200 Subject: [PATCH] Better context management for dispose (allow for unit tests to work) + OSC basics + formating --- .../main/java/dev/slimevr/context/context.kt | 35 ++- .../context/debug/LoggingMiddleware.kt | 3 +- .../main/java/dev/slimevr/driver/module.kt | 8 +- .../main/java/dev/slimevr/feeder/module.kt | 8 +- .../java/dev/slimevr/networkprofile/module.kt | 30 ++- .../src/main/java/dev/slimevr/osc/codec.kt | 197 +++++++++++++++ .../src/main/java/dev/slimevr/osc/receiver.kt | 99 ++++++++ .../src/main/java/dev/slimevr/osc/sender.kt | 44 ++++ .../src/main/java/dev/slimevr/osc/types.kt | 41 +++ .../java/dev/slimevr/skeleton/behaviours.kt | 2 + .../main/java/dev/slimevr/skeleton/module.kt | 8 +- .../main/java/dev/slimevr/solarxr/module.kt | 9 +- .../src/test/java/dev/slimevr/TestServer.kt | 26 ++ .../dev/slimevr/firmware/DoSerialFlashTest.kt | 52 ++-- .../test/java/dev/slimevr/osc/CodecTest.kt | 237 ++++++++++++++++++ .../provisioning/ProvisioningManagerTest.kt | 3 +- .../src/main/java/dev/slimevr/desktop/Main.kt | 2 +- 17 files changed, 750 insertions(+), 54 deletions(-) create mode 100644 server/core/src/main/java/dev/slimevr/osc/codec.kt create mode 100644 server/core/src/main/java/dev/slimevr/osc/receiver.kt create mode 100644 server/core/src/main/java/dev/slimevr/osc/sender.kt create mode 100644 server/core/src/main/java/dev/slimevr/osc/types.kt create mode 100644 server/core/src/test/java/dev/slimevr/osc/CodecTest.kt diff --git a/server/core/src/main/java/dev/slimevr/context/context.kt b/server/core/src/main/java/dev/slimevr/context/context.kt index b71b0ea4a..a725d6d44 100644 --- a/server/core/src/main/java/dev/slimevr/context/context.kt +++ b/server/core/src/main/java/dev/slimevr/context/context.kt @@ -5,7 +5,6 @@ import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -17,22 +16,37 @@ interface Behaviour { fun observe(receiver: C) {} } +class ManagedContext( + val context: Context, + private val supervisorJob: Job, +) { + fun dispose() = supervisorJob.cancel() + + companion object { + fun create( + initialState: S, + scope: CoroutineScope, + behaviours: List>, + debugMiddleware: DebugMiddleware? = null, + name: String, + ): ManagedContext { + val job = SupervisorJob(scope.coroutineContext[Job]) + val scopeWithJob = CoroutineScope(scope.coroutineContext + job) + val context = Context.create(initialState, scopeWithJob, behaviours, debugMiddleware, name) + return ManagedContext(context, job) + } + } +} + class Context( private val mutableStateFlow: MutableStateFlow, val reducer: (S, A) -> S, - private val parentScope: CoroutineScope, + val scope: CoroutineScope, val behaviours: CopyOnWriteArrayList>, private val debugMiddleware: DebugMiddleware? = null, - val name: String, ) { - private val job = SupervisorJob(parentScope.coroutineContext[Job]) - val scope = CoroutineScope(parentScope.coroutineContext + job + CoroutineName(name)) val state: StateFlow = mutableStateFlow.asStateFlow() - fun dispose() { - job.cancel() - } - fun dispatch(action: A) { if (debugMiddleware == null) { mutableStateFlow.update { currentState -> reducer(currentState, action) } @@ -86,8 +100,9 @@ class Context( val reducer: (S, A) -> S = { currentState, action -> behaviours.fold(currentState) { s, b -> b.reduce(s, action) } } + val scopeWithName = CoroutineScope(scope.coroutineContext + CoroutineName(name)) val middlewareToUse = if (debugEnabled) debugMiddleware else null - val context = Context(mutableStateFlow, reducer, scope, CopyOnWriteArrayList(behaviours), middlewareToUse, name) + val context = Context(mutableStateFlow, reducer, scopeWithName, CopyOnWriteArrayList(behaviours), middlewareToUse) middlewareToUse?.init(context) return context } diff --git a/server/core/src/main/java/dev/slimevr/context/debug/LoggingMiddleware.kt b/server/core/src/main/java/dev/slimevr/context/debug/LoggingMiddleware.kt index f95c28177..68c96778f 100644 --- a/server/core/src/main/java/dev/slimevr/context/debug/LoggingMiddleware.kt +++ b/server/core/src/main/java/dev/slimevr/context/debug/LoggingMiddleware.kt @@ -1,6 +1,7 @@ package dev.slimevr.context.debug import dev.slimevr.context.Context +import kotlinx.coroutines.CoroutineName import kotlin.reflect.KClass private object Ansi { @@ -26,7 +27,7 @@ class LoggingMiddleware( private val tag get() = "${Ansi.CYAN}[$contextName]${Ansi.RESET}" override fun init(context: Context) { - contextName = context.name + contextName = context.scope.coroutineContext[CoroutineName]?.name ?: "Unknown" } private fun isAllowed(action: A): Boolean { diff --git a/server/core/src/main/java/dev/slimevr/driver/module.kt b/server/core/src/main/java/dev/slimevr/driver/module.kt index abe220318..943ec3128 100644 --- a/server/core/src/main/java/dev/slimevr/driver/module.kt +++ b/server/core/src/main/java/dev/slimevr/driver/module.kt @@ -5,6 +5,7 @@ import dev.slimevr.EventDispatcher import dev.slimevr.VRServerActions import dev.slimevr.context.Behaviour import dev.slimevr.context.Context +import dev.slimevr.context.ManagedContext import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.CoroutineScope @@ -36,8 +37,9 @@ class DriverBridge( val appContext: AppContextProvider, val inbound: EventDispatcher = EventDispatcher(), val outbound: EventDispatcher = EventDispatcher(), + private val managedContext: ManagedContext? = null, ) { - fun dispose() = context.dispose() + fun dispose() = managedContext?.dispose() fun startObserving() = context.observeAll(this) @@ -50,14 +52,14 @@ class DriverBridge( fun create(id: Int, appContext: AppContextProvider, scope: CoroutineScope): DriverBridge { val behaviours = listOf(DriverBaseBehaviour) - val context = Context.create( + val managedContext = ManagedContext.create( initialState = DriverBridgeState(protocolVersion = 0), scope = scope, behaviours = behaviours, name = "Driver[$id]", ) - val bridge = DriverBridge(id = id, context = context, appContext = appContext) + val bridge = DriverBridge(id = id, context = managedContext.context, appContext = appContext, managedContext = managedContext) bridge.startObserving() appContext.server.context.dispatch(VRServerActions.DriverConnected(bridge)) diff --git a/server/core/src/main/java/dev/slimevr/feeder/module.kt b/server/core/src/main/java/dev/slimevr/feeder/module.kt index 35782a0df..3551fee38 100644 --- a/server/core/src/main/java/dev/slimevr/feeder/module.kt +++ b/server/core/src/main/java/dev/slimevr/feeder/module.kt @@ -5,6 +5,7 @@ import dev.slimevr.EventDispatcher import dev.slimevr.VRServerActions import dev.slimevr.context.Behaviour import dev.slimevr.context.Context +import dev.slimevr.context.ManagedContext import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 import kotlinx.coroutines.CoroutineScope @@ -32,8 +33,9 @@ class FeederBridge( val context: FeederBridgeContext, val appContext: AppContextProvider, val inbound: EventDispatcher = EventDispatcher(), + private val managedContext: ManagedContext? = null, ) { - fun dispose() = context.dispose() + fun dispose() = managedContext?.dispose() fun startObserving() = context.observeAll(this) @@ -46,14 +48,14 @@ class FeederBridge( fun create(id: Int, appContext: AppContextProvider, scope: CoroutineScope): FeederBridge { val behaviours = listOf(FeederBaseBehaviour) - val context = Context.create( + val managedContext = ManagedContext.create( initialState = FeederBridgeState(protocolVersion = 0, firmware = null), scope = scope, behaviours = behaviours, name = "Feeder[$id]", ) - val bridge = FeederBridge(id = id, context = context, appContext = appContext) + val bridge = FeederBridge(id = id, context = managedContext.context, appContext = appContext, managedContext = managedContext) bridge.startObserving() appContext.server.context.dispatch(VRServerActions.FeederConnected(bridge)) diff --git a/server/core/src/main/java/dev/slimevr/networkprofile/module.kt b/server/core/src/main/java/dev/slimevr/networkprofile/module.kt index 38a9e26e3..cc1231cc8 100644 --- a/server/core/src/main/java/dev/slimevr/networkprofile/module.kt +++ b/server/core/src/main/java/dev/slimevr/networkprofile/module.kt @@ -13,18 +13,34 @@ data class NetworkInfo( ) enum class NetworkCategory(val value: Int) { - PUBLIC(0), PRIVATE(1), DOMAIN_AUTHENTICATED(2); - companion object { fun fromInt(value: Int) = entries.find { it.value == value } } + PUBLIC(0), + PRIVATE(1), + DOMAIN_AUTHENTICATED(2), + ; + + companion object { + fun fromInt(value: Int) = entries.find { it.value == value } + } } enum class ConnectivityFlags(val value: Int) { DISCONNECTED(0), - IPV4_NOTRAFFIC(0x1), IPV6_NOTRAFFIC(0x2), - IPV4_SUBNET(0x10), IPV4_LOCALNETWORK(0x20), IPV4_INTERNET(0x40), - IPV6_SUBNET(0x100), IPV6_LOCALNETWORK(0x200), IPV6_INTERNET(0x400); + IPV4_NOTRAFFIC(0x1), + IPV6_NOTRAFFIC(0x2), + IPV4_SUBNET(0x10), + IPV4_LOCALNETWORK(0x20), + IPV4_INTERNET(0x40), + IPV6_SUBNET(0x100), + IPV6_LOCALNETWORK(0x200), + IPV6_INTERNET(0x400), + ; + companion object { - fun fromInt(value: Int): Set = if (value == 0) setOf(DISCONNECTED) - else entries.filter { it != DISCONNECTED && (value and it.value) != 0 }.toSet() + fun fromInt(value: Int): Set = if (value == 0) { + setOf(DISCONNECTED) + } else { + entries.filter { it != DISCONNECTED && (value and it.value) != 0 }.toSet() + } } } diff --git a/server/core/src/main/java/dev/slimevr/osc/codec.kt b/server/core/src/main/java/dev/slimevr/osc/codec.kt new file mode 100644 index 000000000..2199bd96c --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/osc/codec.kt @@ -0,0 +1,197 @@ +package dev.slimevr.osc + +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets + +private const val BUNDLE_PREFIX = "#bundle " + +fun encodeMessage(msg: OscMessage): ByteArray { + val buf = ByteBuffer.allocate(65536) // max UDP packet + buf.order(java.nio.ByteOrder.BIG_ENDIAN) + + // Address + null terminator + val addressBytes = msg.address.toByteArray(StandardCharsets.US_ASCII) + buf.put(addressBytes) + buf.put(0.toByte()) // null terminator + val addressPadded = padToMultiple(addressBytes.size + 1, 4) + buf.put(ByteArray(addressPadded - addressBytes.size - 1)) + + // Type tag string + val typeTag = "," + msg.args.joinToString("") { it.typeTag.toString() } + val typeTagBytes = typeTag.toByteArray(StandardCharsets.US_ASCII) + buf.put(typeTagBytes) + buf.put(0.toByte()) + val typeTagPadded = padToMultiple(typeTagBytes.size + 1, 4) + buf.put(ByteArray(typeTagPadded - typeTagBytes.size - 1)) + + // Arguments + for (arg in msg.args) { + when (arg) { + is OscArg.Int -> buf.putInt(arg.value) + + is OscArg.Long -> buf.putLong(arg.value) + + is OscArg.Float -> buf.putFloat(arg.value) + + is OscArg.Double -> buf.putDouble(arg.value) + + is OscArg.String -> { + val strBytes = arg.value.toByteArray(StandardCharsets.US_ASCII) + buf.put(strBytes) + buf.put(0.toByte()) + val strPadded = padToMultiple(strBytes.size + 1, 4) + buf.put(ByteArray(strPadded - strBytes.size - 1)) + } + + is OscArg.Blob -> { + buf.putInt(arg.value.size) + buf.put(arg.value) + val blobPadded = padToMultiple(arg.value.size, 4) + buf.put(ByteArray(blobPadded - arg.value.size)) + } + + else -> {} // Impulse, Null, True, False have no arguments + } + } + + return buf.array().sliceArray(0 until buf.position()) +} + +fun decodeMessage(bytes: ByteArray, offset: Int = 0): Pair { + var pos = offset + val buf = ByteBuffer.wrap(bytes, offset, bytes.size - offset) + buf.order(java.nio.ByteOrder.BIG_ENDIAN) + + // Parse address + val addressStart = pos + while (pos < bytes.size && bytes[pos] != 0.toByte()) pos++ + val address = bytes.sliceArray(addressStart until pos).toString(StandardCharsets.US_ASCII) + pos++ // skip null terminator + pos = alignToMultiple(pos, 4) + + // Parse type tag + val typeTagStart = pos + while (pos < bytes.size && bytes[pos] != 0.toByte()) pos++ + val typeTag = bytes.sliceArray(typeTagStart until pos).toString(StandardCharsets.US_ASCII) + pos++ // skip null terminator + pos = alignToMultiple(pos, 4) + + // Parse arguments + val args = mutableListOf() + if (typeTag.startsWith(",")) { + buf.position(pos - offset) + for (i in 1 until typeTag.length) { + when (typeTag[i]) { + 'i' -> args.add(OscArg.Int(buf.int)) + + 'h' -> args.add(OscArg.Long(buf.long)) + + 'f' -> args.add(OscArg.Float(buf.float)) + + 'd' -> args.add(OscArg.Double(buf.double)) + + 's' -> { + val strStart = buf.position() + while (buf.position() < bytes.size && bytes[offset + buf.position()] != 0.toByte()) { + buf.position(buf.position() + 1) + } + val str = bytes.sliceArray(strStart + offset until offset + buf.position()).toString(StandardCharsets.US_ASCII) + args.add(OscArg.String(str)) + buf.position(buf.position() + 1) // skip null + val strPadding = padToMultiple(str.length + 1, 4) + buf.position(buf.position() + strPadding - str.length - 1) + } + + 'b' -> { + val size = buf.int + val blob = ByteArray(size) + buf.get(blob) + args.add(OscArg.Blob(blob)) + val blobPadding = padToMultiple(size, 4) + buf.position(buf.position() + blobPadding - size) + } + + 'I' -> args.add(OscArg.Impulse) + + 'N' -> args.add(OscArg.Null) + + 'T' -> args.add(OscArg.True) + + 'F' -> args.add(OscArg.False) + } + } + pos = offset + buf.position() + } + + return OscMessage(address, args) to pos +} + +fun encodeBundle(bundle: OscBundle): ByteArray { + val buf = ByteBuffer.allocate(65536) + buf.order(java.nio.ByteOrder.BIG_ENDIAN) + + // Bundle prefix + val prefixBytes = BUNDLE_PREFIX.toByteArray(StandardCharsets.US_ASCII) + buf.put(prefixBytes) + + // Timetag (8 bytes, NTP format) + buf.putLong(bundle.timetag) + + // Contents + for (content in bundle.contents) { + val contentBytes = when (content) { + is OscContent.Message -> encodeMessage(content.msg) + is OscContent.Bundle -> encodeBundle(content.bundle) + } + buf.putInt(contentBytes.size) + buf.put(contentBytes) + } + + return buf.array().sliceArray(0 until buf.position()) +} + +fun decodeBundle(bytes: ByteArray, offset: Int = 0): Pair { + val prefixBytes = BUNDLE_PREFIX.toByteArray(StandardCharsets.US_ASCII) + if (!bytes.sliceArray(offset until minOf(offset + 8, bytes.size)).contentEquals(prefixBytes)) { + throw IllegalArgumentException("Invalid bundle prefix") + } + + var pos = offset + 8 + val buf = ByteBuffer.wrap(bytes, pos, bytes.size - pos) + buf.order(java.nio.ByteOrder.BIG_ENDIAN) + + val timetag = buf.long + pos += 8 + + val contents = mutableListOf() + while (pos < bytes.size) { + buf.position(pos - offset - 8) + val elementSize = buf.int + pos += 4 + + if (elementSize <= 0 || pos + elementSize > bytes.size) break + + val element = bytes.sliceArray(pos until pos + elementSize) + try { + if (element.size >= 8 && element.sliceArray(0..7).contentEquals(prefixBytes)) { + val (bundle, _) = decodeBundle(bytes, pos) + contents.add(OscContent.Bundle(bundle)) + } else { + val (msg, _) = decodeMessage(bytes, pos) + contents.add(OscContent.Message(msg)) + } + } catch (e: Exception) { + break + } + pos += elementSize + } + + return OscBundle(timetag, contents) to pos +} + +private fun padToMultiple(value: Int, alignment: Int): Int { + val remainder = value % alignment + return if (remainder == 0) value else value + (alignment - remainder) +} + +private fun alignToMultiple(value: Int, alignment: Int): Int = padToMultiple(value, alignment) diff --git a/server/core/src/main/java/dev/slimevr/osc/receiver.kt b/server/core/src/main/java/dev/slimevr/osc/receiver.kt new file mode 100644 index 000000000..a098b50dc --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/osc/receiver.kt @@ -0,0 +1,99 @@ +package dev.slimevr.osc + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.cancel +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.net.DatagramPacket +import java.net.DatagramSocket + +class OscReceiver(private val port: Int) { + private var socket: DatagramSocket? = null + private var listenerScope: CoroutineScope? = null + + suspend fun listen(onMessage: (OscMessage) -> Unit) { + if (socket == null) { + socket = withContext(Dispatchers.IO) { + DatagramSocket(port) + } + } + val s = socket ?: return + + val scope = CoroutineScope(Dispatchers.IO) + listenerScope = scope + + scope.launch { + while (isActive) { + try { + val buffer = ByteArray(65536) + val packet = DatagramPacket(buffer, buffer.size) + s.receive(packet) + val bytes = packet.data.sliceArray(0 until packet.length) + + try { + val (msg, _) = decodeMessage(bytes) + onMessage(msg) + } catch (e: Exception) { + // Ignore malformed packets + } + } catch (e: Exception) { + if (isActive) { + // Socket closed or error + break + } + } + } + } + } + + suspend fun listenBundles(onBundle: (OscBundle) -> Unit) { + if (socket == null) { + socket = withContext(Dispatchers.IO) { + DatagramSocket(port) + } + } + val s = socket ?: return + + val scope = CoroutineScope(Dispatchers.IO) + listenerScope = scope + + scope.launch { + while (isActive) { + try { + val buffer = ByteArray(65536) + val packet = DatagramPacket(buffer, buffer.size) + s.receive(packet) + val bytes = packet.data.sliceArray(0 until packet.length) + + try { + // Try bundle first, fall back to message + val bundle = if (bytes.size >= 8 && bytes.sliceArray(0..7).contentEquals("#bundle ".toByteArray())) { + val (b, _) = decodeBundle(bytes) + b + } else { + // Wrap message in a bundle + val (msg, _) = decodeMessage(bytes) + OscBundle(1, listOf(OscContent.Message(msg))) + } + onBundle(bundle) + } catch (e: Exception) { + // Ignore malformed packets + } + } catch (e: Exception) { + if (isActive) { + break + } + } + } + } + } + + fun close() { + listenerScope?.cancel() + listenerScope = null + socket?.close() + socket = null + } +} diff --git a/server/core/src/main/java/dev/slimevr/osc/sender.kt b/server/core/src/main/java/dev/slimevr/osc/sender.kt new file mode 100644 index 000000000..8b7c25c7d --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/osc/sender.kt @@ -0,0 +1,44 @@ +package dev.slimevr.osc + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress + +class OscSender(private val address: String, private val port: Int) { + private var socket: DatagramSocket? = null + + private suspend fun ensureSocket() { + if (socket == null) { + socket = withContext(Dispatchers.IO) { + DatagramSocket() + } + } + } + + suspend fun send(message: OscMessage) { + val bytes = encodeMessage(message) + ensureSocket() + sendBytes(bytes) + } + + suspend fun send(bundle: OscBundle) { + val bytes = encodeBundle(bundle) + ensureSocket() + sendBytes(bytes) + } + + private suspend fun sendBytes(bytes: ByteArray) { + val s = socket ?: return + withContext(Dispatchers.IO) { + val packet = DatagramPacket(bytes, bytes.size, InetAddress.getByName(address), port) + s.send(packet) + } + } + + fun close() { + socket?.close() + socket = null + } +} diff --git a/server/core/src/main/java/dev/slimevr/osc/types.kt b/server/core/src/main/java/dev/slimevr/osc/types.kt new file mode 100644 index 000000000..80277a910 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/osc/types.kt @@ -0,0 +1,41 @@ +package dev.slimevr.osc + +sealed class OscArg { + data class Int(val value: kotlin.Int) : OscArg() + data class Long(val value: kotlin.Long) : OscArg() + data class Float(val value: kotlin.Float) : OscArg() + data class Double(val value: kotlin.Double) : OscArg() + data class String(val value: kotlin.String) : OscArg() + data class Blob(val value: ByteArray) : OscArg() { + override fun equals(other: Any?) = this === other || other is Blob && value.contentEquals(other.value) + override fun hashCode() = value.contentHashCode() + } + + data object Impulse : OscArg() + data object Null : OscArg() + data object True : OscArg() + data object False : OscArg() + + val typeTag: Char + get() = when (this) { + is Int -> 'i' + is Long -> 'h' + is Float -> 'f' + is Double -> 'd' + is String -> 's' + is Blob -> 'b' + Impulse -> 'I' + Null -> 'N' + True -> 'T' + False -> 'F' + } +} + +data class OscMessage(val address: String, val args: List = emptyList()) + +data class OscBundle(val timetag: Long, val contents: List = emptyList()) + +sealed interface OscContent { + data class Message(val msg: OscMessage) : OscContent + data class Bundle(val bundle: OscBundle) : OscContent +} diff --git a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt index fcab4875a..74640127c 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt @@ -21,12 +21,14 @@ class BoneTransformBehaviour : SkeletonBehaviour { bones[action.bodyPart] = bone.copy(rawRotation = action.rotation) state.copy(rawBones = bones) } + is SkeletonActions.SetBonePosition -> { val bones = state.rawBones.toMutableMap() val bone = bones[action.bodyPart] ?: return state bones[action.bodyPart] = bone.copy(rawPosition = action.position) state.copy(rawBones = bones) } + else -> state } } diff --git a/server/core/src/main/java/dev/slimevr/skeleton/module.kt b/server/core/src/main/java/dev/slimevr/skeleton/module.kt index 434ea4941..eca94ad0c 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/module.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/module.kt @@ -14,7 +14,7 @@ data class RawBone( val bodyPart: BodyPart, val length: Float, val rawRotation: Quaternion, - val rawPosition: Vector3 + val rawPosition: Vector3, ) data class BoneState( @@ -29,8 +29,8 @@ data class BoneState( get() = parentBone?.let { it.rotation.inv() * rotation } ?: rotation val localHeadPosition: Vector3 get() = parentBone?.let { headPosition - it.tailPosition } ?: headPosition -// val localTailPosition: Vector3 -// get() = tailPosition - headPosition +// val localTailPosition: Vector3 +// get() = tailPosition - headPosition } data class SkeletonState(val rawBones: Map, val userHeight: Double) @@ -43,7 +43,7 @@ val DEFAULT_SKELETON_STATE: SkeletonState = run { } bodyPart to BoneState(bodyPart = bodyPart, length = tailOffset.len(), rotation = restRotation) } - SkeletonState(rawBones = bones.mapValues { (_, bone) -> RawBone(rawRotation = bone.rotation, bodyPart = bone.bodyPart, length = bone.length, rawPosition = Vector3.NULL) }, userHeight = computeUserHeight(bones.mapValues { (_, bone) -> bone.length })) + SkeletonState(rawBones = bones.mapValues { (_, bone) -> RawBone(rawRotation = bone.rotation, bodyPart = bone.bodyPart, length = bone.length, rawPosition = Vector3.NULL) }, userHeight = computeUserHeight(bones.mapValues { (_, bone) -> bone.length })) } fun buildBones(state: SkeletonState, rootHead: Vector3 = Vector3.NULL): Map { 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 7aad018df..3d74099fd 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/module.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/module.kt @@ -5,6 +5,7 @@ import dev.slimevr.EventDispatcher import dev.slimevr.VRServerActions import dev.slimevr.context.Behaviour import dev.slimevr.context.Context +import dev.slimevr.context.ManagedContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import solarxr_protocol.MessageBundle @@ -48,8 +49,9 @@ class SolarXRBridge( val dataFeedDispatcher: EventDispatcher, val rpcDispatcher: EventDispatcher, val outbound: EventDispatcher = EventDispatcher(), + private val managedContext: ManagedContext? = null, ) { - fun dispose() = context.dispose() + fun dispose() = managedContext?.dispose() suspend fun sendRpc(message: RpcMessage) = outbound.emit(MessageBundle(rpcMsgs = listOf(RpcMessageHeader(message = message)))) @@ -85,7 +87,7 @@ class SolarXRBridge( appContext: AppContextProvider, scope: CoroutineScope, ): SolarXRBridge { - val context = Context.create( + val managedContext = ManagedContext.create( initialState = SolarXRBridgeState(dataFeedConfigs = listOf(), datafeedTimers = listOf()), scope = scope, behaviours = buildBehaviours(appContext), @@ -94,10 +96,11 @@ class SolarXRBridge( val bridge = SolarXRBridge( id = id, - context = context, + context = managedContext.context, appContext = appContext, dataFeedDispatcher = EventDispatcher(), rpcDispatcher = EventDispatcher(), + managedContext = managedContext, ) bridge.startObserving() return bridge diff --git a/server/core/src/test/java/dev/slimevr/TestServer.kt b/server/core/src/test/java/dev/slimevr/TestServer.kt index f43ebbcc3..1bec70a21 100644 --- a/server/core/src/test/java/dev/slimevr/TestServer.kt +++ b/server/core/src/test/java/dev/slimevr/TestServer.kt @@ -1,14 +1,19 @@ package dev.slimevr import dev.llelievr.espflashkotlin.FlasherSerialInterface +import dev.slimevr.bvh.BVHManager import dev.slimevr.config.AppConfig import dev.slimevr.config.DefaultUserBehaviour +import dev.slimevr.config.Settings +import dev.slimevr.config.SettingsConfigState +import dev.slimevr.config.SettingsState import dev.slimevr.config.UserConfig import dev.slimevr.config.UserConfigData import dev.slimevr.config.UserConfigState import dev.slimevr.context.Context import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager +import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.serial.SerialPortHandle import dev.slimevr.serial.SerialServer @@ -44,6 +49,12 @@ fun buildTestSerialServer(scope: CoroutineScope) = SerialServer.create( fun buildTestVrServer(scope: CoroutineScope): VRServer = VRServer.create(scope) +fun buildTestVrServerStub(scope: CoroutineScope): VRServer { + val vrServer = VRServer.create(scope) + // Don't call startObserving() to avoid starting infinite flow observers + return vrServer +} + fun buildTestUserConfig(scope: CoroutineScope): UserConfig { val tempDir = Files.createTempDirectory("slimevr-test").toFile() tempDir.deleteOnExit() @@ -70,6 +81,19 @@ fun buildTestSkeleton(scope: CoroutineScope): Skeleton { return skeleton } +fun buildTestSettings(scope: CoroutineScope): Settings { + val initialState = SettingsState(data = SettingsConfigState(), name = "test") + val context = Context.create( + initialState = initialState, + scope = scope, + behaviours = emptyList(), + name = "Settings[test]", + ) + // Use a path in /tmp that won't actually be written to in tests + val fakeDir = java.io.File("/tmp/slimevr-test-${System.nanoTime()}") + return Settings(context, scope, fakeDir) +} + abstract class TestAppContext : AppContextProvider { override val config: AppConfig get() = error("not used in test") override val serialServer: SerialServer get() = error("not used in test") @@ -79,5 +103,7 @@ abstract class TestAppContext : AppContextProvider { override val heightCalibrationManager: HeightCalibrationManager get() = error("not used in test") override val trackingChecklist: TrackingChecklist get() = error("not used in test") override val udpServer: UdpServer get() = error("not used in test") + override val networkProfileManager: NetworkProfileManager? = null + override val bvhManager: BVHManager get() = error("not used in test") override fun startObserving() {} } diff --git a/server/core/src/test/java/dev/slimevr/firmware/DoSerialFlashTest.kt b/server/core/src/test/java/dev/slimevr/firmware/DoSerialFlashTest.kt index faaaa95c8..2e6b1b322 100644 --- a/server/core/src/test/java/dev/slimevr/firmware/DoSerialFlashTest.kt +++ b/server/core/src/test/java/dev/slimevr/firmware/DoSerialFlashTest.kt @@ -3,21 +3,21 @@ package dev.slimevr.firmware import dev.llelievr.espflashkotlin.FlasherSerialInterface import dev.slimevr.VRServer import dev.slimevr.VRServerActions +import dev.slimevr.buildTestSettings +import dev.slimevr.buildTestVrServerStub import dev.slimevr.device.Device import dev.slimevr.device.DeviceActions import dev.slimevr.device.DeviceOrigin import dev.slimevr.serial.SerialPortHandle import dev.slimevr.serial.SerialPortInfo import dev.slimevr.serial.SerialServer +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy -import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import solarxr_protocol.datatypes.TrackerStatus -import solarxr_protocol.datatypes.hardware_info.BoardType -import solarxr_protocol.datatypes.hardware_info.McuType import solarxr_protocol.rpc.FirmwareUpdateStatus import kotlin.test.Test import kotlin.test.assertEquals @@ -58,7 +58,7 @@ private fun buildSerialServer( // backgroundScope lets those run on the test scheduler but doesn't cause // UncompletedCoroutinesError when the test ends. private fun buildVrServer( - backgroundScope: kotlinx.coroutines.CoroutineScope, + backgroundScope: CoroutineScope, ): VRServer = VRServer.create(backgroundScope) class DoSerialFlashTest { @@ -66,6 +66,7 @@ class DoSerialFlashTest { @Test fun `emits ERROR_DEVICE_NOT_FOUND when port is not available`() = runTest { val server = buildSerialServer(this) + val vrServer = buildTestVrServerStub(backgroundScope) val statuses = mutableListOf() doSerialFlash( @@ -75,7 +76,8 @@ class DoSerialFlashTest { ssid = null, password = null, serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = vrServer, onStatus = { s, _ -> statuses += s }, scope = this, ) @@ -97,7 +99,8 @@ class DoSerialFlashTest { ssid = null, password = null, serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = buildTestVrServerStub(backgroundScope), onStatus = { s, _ -> statuses += s }, scope = this, ) @@ -118,7 +121,8 @@ class DoSerialFlashTest { ssid = null, password = null, serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = buildTestVrServerStub(backgroundScope), onStatus = { s, _ -> statuses += s }, scope = this, ) @@ -139,7 +143,8 @@ class DoSerialFlashTest { ssid = "wifi", password = "pass", serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = buildTestVrServerStub(backgroundScope), onStatus = { s, _ -> statuses += s }, ) @@ -161,7 +166,8 @@ class DoSerialFlashTest { ssid = "wifi", password = "pass", serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = buildTestVrServerStub(backgroundScope), onStatus = { s, _ -> statuses += s }, ) } @@ -180,24 +186,25 @@ class DoSerialFlashTest { server.openConnection("COM1") val statuses = mutableListOf() - launch { + backgroundScope.launch { doSerialFlashPostFlash( portLocation = "COM1", needManualReboot = false, ssid = null, password = null, serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = buildTestVrServerStub(backgroundScope), onStatus = { s, _ -> statuses += s }, ) } - launch { + backgroundScope.launch { delay(100) server.onDataReceived("COM1", "mac: AA:BB:CC:DD:EE:FF") } - advanceUntilIdle() + advanceTimeBy(500) assertEquals(FirmwareUpdateStatus.ERROR_PROVISIONING_FAILED, statuses.last()) } @@ -217,12 +224,13 @@ class DoSerialFlashTest { ssid = "wifi", password = "pass", serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = buildTestVrServerStub(backgroundScope), onStatus = { s, _ -> statuses += s }, ) } - launch { + backgroundScope.launch { delay(100) server.onDataReceived("COM1", "mac: AA:BB:CC:DD:EE:FF") } @@ -249,12 +257,13 @@ class DoSerialFlashTest { ssid = "wifi", password = "pass", serialServer = server, - server = buildVrServer(backgroundScope), + settings = buildTestSettings(backgroundScope), + server = buildTestVrServerStub(backgroundScope), onStatus = { s, _ -> statuses += s }, ) } - launch { + backgroundScope.launch { delay(100) server.onDataReceived("COM1", "mac: AA:BB:CC:DD:EE:FF") delay(200) @@ -274,22 +283,23 @@ class DoSerialFlashTest { val server = buildSerialServer(this) server.onPortDetected(fakePort()) server.openConnection("COM1") - val vrServer = buildVrServer(backgroundScope) + val vrServer = buildTestVrServerStub(backgroundScope) val statuses = mutableListOf() - launch { + backgroundScope.launch { doSerialFlashPostFlash( portLocation = "COM1", needManualReboot = false, ssid = "wifi", password = "pass", serialServer = server, + settings = buildTestSettings(backgroundScope), server = vrServer, onStatus = { s, _ -> statuses += s }, ) } - launch { + backgroundScope.launch { delay(100) server.onDataReceived("COM1", "mac: AA:BB:CC:DD:EE:FF") delay(200) @@ -307,7 +317,7 @@ class DoSerialFlashTest { device.context.dispatch(DeviceActions.Update { copy(status = TrackerStatus.OK) }) } - advanceUntilIdle() + advanceTimeBy(1000) assertEquals(FirmwareUpdateStatus.DONE, statuses.last()) } diff --git a/server/core/src/test/java/dev/slimevr/osc/CodecTest.kt b/server/core/src/test/java/dev/slimevr/osc/CodecTest.kt new file mode 100644 index 000000000..9cdb66196 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/osc/CodecTest.kt @@ -0,0 +1,237 @@ +package dev.slimevr.osc + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class CodecTest { + @Test + fun testEncodeDecodeIntMessage() { + val msg = OscMessage("/test", listOf(OscArg.Int(42))) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/test", decoded.address) + assertEquals(1, decoded.args.size) + assertEquals(42, (decoded.args[0] as OscArg.Int).value) + } + + @Test + fun testEncodeDecodeFloatMessage() { + val msg = OscMessage("/test/float", listOf(OscArg.Float(3.14f))) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/test/float", decoded.address) + assertEquals(1, decoded.args.size) + val float = (decoded.args[0] as OscArg.Float).value + assertTrue((float - 3.14f) < 0.001f) + } + + @Test + fun testEncodeDecodeStringMessage() { + val msg = OscMessage("/address", listOf(OscArg.String("hello"))) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/address", decoded.address) + assertEquals(1, decoded.args.size) + assertEquals("hello", (decoded.args[0] as OscArg.String).value) + } + + @Test + fun testEncodeDecodeBlobMessage() { + val blobData = byteArrayOf(1, 2, 3, 4, 5) + val msg = OscMessage("/blob", listOf(OscArg.Blob(blobData))) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/blob", decoded.address) + assertEquals(1, decoded.args.size) + val decodedBlob = (decoded.args[0] as OscArg.Blob).value + assertTrue(decodedBlob.contentEquals(blobData)) + } + + @Test + fun testEncodeDecodeLongMessage() { + val msg = OscMessage("/long", listOf(OscArg.Long(9876543210L))) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/long", decoded.address) + assertEquals(1, decoded.args.size) + assertEquals(9876543210L, (decoded.args[0] as OscArg.Long).value) + } + + @Test + fun testEncodeDecodeDoubleMessage() { + val msg = OscMessage("/double", listOf(OscArg.Double(2.718281828))) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/double", decoded.address) + assertEquals(1, decoded.args.size) + val double = (decoded.args[0] as OscArg.Double).value + assertTrue((double - 2.718281828) < 0.000001) + } + + @Test + fun testEncodeDecode() { + val msg = OscMessage( + "/VMC/Ext/Bone/Pos", + listOf( + OscArg.String("Hips"), + OscArg.Float(1.0f), + OscArg.Float(2.0f), + OscArg.Float(3.0f), + OscArg.Float(0.0f), + OscArg.Float(0.0f), + OscArg.Float(0.707f), + OscArg.Float(0.707f), + ), + ) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/VMC/Ext/Bone/Pos", decoded.address) + assertEquals(8, decoded.args.size) + assertEquals("Hips", (decoded.args[0] as OscArg.String).value) + assertEquals(1.0f, (decoded.args[1] as OscArg.Float).value) + } + + @Test + fun testMultipleArgs() { + val msg = OscMessage( + "/test", + listOf( + OscArg.Int(1), + OscArg.String("two"), + OscArg.Float(3.0f), + OscArg.Long(4L), + ), + ) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals(4, decoded.args.size) + assertEquals(1, (decoded.args[0] as OscArg.Int).value) + assertEquals("two", (decoded.args[1] as OscArg.String).value) + assertEquals(3.0f, (decoded.args[2] as OscArg.Float).value) + assertEquals(4L, (decoded.args[3] as OscArg.Long).value) + } + + @Test + fun testEncodeDecodeBundle() { + val bundle = OscBundle( + 1, + listOf( + OscContent.Message(OscMessage("/msg1", listOf(OscArg.Int(42)))), + OscContent.Message(OscMessage("/msg2", listOf(OscArg.String("hello")))), + ), + ) + val encoded = encodeBundle(bundle) + val (decoded, _) = decodeBundle(encoded) + + assertEquals(1, decoded.timetag) + assertEquals(2, decoded.contents.size) + + val msg1 = (decoded.contents[0] as OscContent.Message).msg + assertEquals("/msg1", msg1.address) + assertEquals(42, (msg1.args[0] as OscArg.Int).value) + + val msg2 = (decoded.contents[1] as OscContent.Message).msg + assertEquals("/msg2", msg2.address) + assertEquals("hello", (msg2.args[0] as OscArg.String).value) + } + + @Test + fun testNestedBundles() { + val innerBundle = OscBundle( + 2, + listOf(OscContent.Message(OscMessage("/inner", listOf(OscArg.Int(99))))), + ) + val outerBundle = OscBundle( + 1, + listOf( + OscContent.Message(OscMessage("/outer", listOf(OscArg.Int(1)))), + OscContent.Bundle(innerBundle), + ), + ) + + val encoded = encodeBundle(outerBundle) + val (decoded, _) = decodeBundle(encoded) + + assertEquals(1, decoded.timetag) + assertEquals(2, decoded.contents.size) + + val outerMsg = (decoded.contents[0] as OscContent.Message).msg + assertEquals("/outer", outerMsg.address) + + val decodedInner = (decoded.contents[1] as OscContent.Bundle).bundle + assertEquals(2, decodedInner.timetag) + val innerMsg = (decodedInner.contents[0] as OscContent.Message).msg + assertEquals("/inner", innerMsg.address) + assertEquals(99, (innerMsg.args[0] as OscArg.Int).value) + } + + @Test + fun testEmptyMessage() { + val msg = OscMessage("/empty") + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals("/empty", decoded.address) + assertEquals(0, decoded.args.size) + } + + @Test + fun testSpecialArgs() { + val msg = OscMessage( + "/special", + listOf(OscArg.True, OscArg.False, OscArg.Null, OscArg.Impulse), + ) + val encoded = encodeMessage(msg) + val (decoded, _) = decodeMessage(encoded) + + assertEquals(4, decoded.args.size) + assertEquals(OscArg.True, decoded.args[0]) + assertEquals(OscArg.False, decoded.args[1]) + assertEquals(OscArg.Null, decoded.args[2]) + assertEquals(OscArg.Impulse, decoded.args[3]) + } + + @Test + fun testAlignment() { + // Messages with different address lengths should be properly aligned + val short = OscMessage("/a", listOf(OscArg.Int(1))) + val long = OscMessage("/this/is/a/very/long/address", listOf(OscArg.Int(1))) + + val encodedShort = encodeMessage(short) + val encodedLong = encodeMessage(long) + + // Both should encode/decode correctly regardless of alignment + val (decodedShort, _) = decodeMessage(encodedShort) + val (decodedLong, _) = decodeMessage(encodedLong) + + assertEquals("/a", decodedShort.address) + assertEquals("/this/is/a/very/long/address", decodedLong.address) + } + + @Test + fun testOffsetParsing() { + val msg1 = OscMessage("/first", listOf(OscArg.Int(1))) + val msg2 = OscMessage("/second", listOf(OscArg.Int(2))) + + val encoded1 = encodeMessage(msg1) + val encoded2 = encodeMessage(msg2) + val combined = encoded1 + encoded2 + + // Parse first message from combined + val (decoded1, offset) = decodeMessage(combined, 0) + assertEquals("/first", decoded1.address) + + // Parse second message from offset + val (decoded2, _) = decodeMessage(combined, offset) + assertEquals("/second", decoded2.address) + } +} diff --git a/server/core/src/test/java/dev/slimevr/provisioning/ProvisioningManagerTest.kt b/server/core/src/test/java/dev/slimevr/provisioning/ProvisioningManagerTest.kt index db94b3c97..c890e70e8 100644 --- a/server/core/src/test/java/dev/slimevr/provisioning/ProvisioningManagerTest.kt +++ b/server/core/src/test/java/dev/slimevr/provisioning/ProvisioningManagerTest.kt @@ -3,6 +3,7 @@ package dev.slimevr.provisioning import dev.slimevr.VRServer import dev.slimevr.VRServerActions import dev.slimevr.buildTestSerialServer +import dev.slimevr.buildTestSettings import dev.slimevr.buildTestVrServer import dev.slimevr.context.Context import dev.slimevr.device.Device @@ -30,7 +31,7 @@ private fun buildManager(serialServer: dev.slimevr.serial.SerialServer, scope: C behaviours = listOf(ProvisioningManagerBaseBehaviour), name = "ProvisioningManagerTest", ) - return ProvisioningManager(context = context, serialServer = serialServer, scope = scope).also { it.startObserving() } + return ProvisioningManager(context = context, serialServer = serialServer, settings = buildTestSettings(scope), scope = scope).also { it.startObserving() } } // Injects a fully connected device into the VRServer, simulating a tracker appearing on the network. diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt index 2cdad2829..19c319a6b 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -7,7 +7,6 @@ import dev.slimevr.Phase1Context import dev.slimevr.VRServer import dev.slimevr.bvh.BVHManager import dev.slimevr.config.AppConfig -import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.desktop.hid.createDesktopHIDManager import dev.slimevr.desktop.ipc.createIpcServers import dev.slimevr.desktop.ipc.createSolarXRWebsocketServer @@ -16,6 +15,7 @@ import dev.slimevr.desktop.serial.createDesktopSerialServer import dev.slimevr.desktop.vrchat.createDesktopVRCConfigManager import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager +import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resolveConfigDirectory import dev.slimevr.skeleton.Skeleton