Better context management for dispose (allow for unit tests to work) + OSC basics + formating

This commit is contained in:
loucass003 committed 2026-05-05 07:35:27 +02:00
1 parent 6087178ecf
commit be34dc981c
17 files changed
+750 -54

No files matched your search

@@ -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<S, A, C> {
fun observe(receiver: C) {}
}
class ManagedContext<S, A>(
val context: Context<S, A>,
private val supervisorJob: Job,
) {
fun dispose() = supervisorJob.cancel()
companion object {
fun <S, A> create(
initialState: S,
scope: CoroutineScope,
behaviours: List<Behaviour<S, A, *>>,
debugMiddleware: DebugMiddleware<S, A>? = null,
name: String,
): ManagedContext<S, A> {
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<S, A>(
private val mutableStateFlow: MutableStateFlow<S>,
val reducer: (S, A) -> S,
private val parentScope: CoroutineScope,
val scope: CoroutineScope,
val behaviours: CopyOnWriteArrayList<Behaviour<S, A, *>>,
private val debugMiddleware: DebugMiddleware<S, A>? = null,
val name: String,
) {
private val job = SupervisorJob(parentScope.coroutineContext[Job])
val scope = CoroutineScope(parentScope.coroutineContext + job + CoroutineName(name))
val state: StateFlow<S> = 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<S, A>(
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
}
@@ -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<S, A>(
private val tag get() = "${Ansi.CYAN}[$contextName]${Ansi.RESET}"
override fun init(context: Context<S, A>) {
contextName = context.name
contextName = context.scope.coroutineContext[CoroutineName]?.name ?: "Unknown"
}
private fun isAllowed(action: A): Boolean {
@@ -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<DriverBridgeInbound> = EventDispatcher(),
val outbound: EventDispatcher<DriverBridgeOutbound> = EventDispatcher(),
private val managedContext: ManagedContext<DriverBridgeState, DriverBridgeActions>? = 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))
@@ -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<FeederBridgeInbound> = EventDispatcher(),
private val managedContext: ManagedContext<FeederBridgeState, FeederBridgeActions>? = 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))
@@ -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<ConnectivityFlags> = if (value == 0) setOf(DISCONNECTED)
else entries.filter { it != DISCONNECTED && (value and it.value) != 0 }.toSet()
fun fromInt(value: Int): Set<ConnectivityFlags> = if (value == 0) {
setOf(DISCONNECTED)
} else {
entries.filter { it != DISCONNECTED && (value and it.value) != 0 }.toSet()
}
}
}
@@ -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<OscMessage, Int> {
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<OscArg>()
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<OscBundle, Int> {
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<OscContent>()
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)
@@ -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
}
}
@@ -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
}
}
@@ -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<OscArg> = emptyList())
data class OscBundle(val timetag: Long, val contents: List<OscContent> = emptyList())
sealed interface OscContent {
data class Message(val msg: OscMessage) : OscContent
data class Bundle(val bundle: OscBundle) : OscContent
}
@@ -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
}
}
@@ -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<BodyPart, RawBone>, 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<BodyPart, BoneState> {
@@ -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<DataFeedMessage>,
val rpcDispatcher: EventDispatcher<RpcMessage>,
val outbound: EventDispatcher<MessageBundle> = EventDispatcher(),
private val managedContext: ManagedContext<SolarXRBridgeState, SolarXRBridgeActions>? = 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
@@ -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<SettingsState, dev.slimevr.config.SettingsActions>(
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() {}
}
@@ -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<FirmwareUpdateStatus>()
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<FirmwareUpdateStatus>()
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<FirmwareUpdateStatus>()
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())
}
@@ -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)
}
}
@@ -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.
@@ -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