diff --git a/server/README.md b/server/README.md index 647c2566b..4c08ab0cb 100644 --- a/server/README.md +++ b/server/README.md @@ -21,10 +21,10 @@ The `Context` type (`context/context.kt`) is the building block of every m ```kotlin data class Context( - val state: StateFlow, // current state, readable by anyone - val dispatch: suspend (A) -> Unit, - val dispatchAll: suspend (List) -> Unit, - val scope: CoroutineScope, // lifetime of this module + val state: StateFlow, // current state, readable by anyone + val dispatch: suspend (A) -> Unit, + val dispatchAll: suspend (List) -> Unit, + val scope: CoroutineScope, // lifetime of this module ) ``` @@ -43,8 +43,8 @@ A `Behaviour` bundles two optional pieces: ```kotlin data class BasicBehaviour( - val reducer: ((S, A) -> S)? = null, - val observer: ((Context) -> Unit)? = null, + val reducer: ((S, A) -> S)? = null, + val observer: ((Context) -> Unit)? = null, ) ``` @@ -59,9 +59,9 @@ Every module follows the same construction pattern: val behaviours = listOf(BehaviourA, BehaviourB, BehaviourC) val context = createContext( - initialState = ..., - reducers = behaviours.map { it.reducer }, - scope = scope, + initialState = ..., + reducers = behaviours.map { it.reducer }, + scope = scope, ) behaviours.map { it.observer }.forEach { it?.invoke(context) } @@ -122,63 +122,63 @@ Rule of thumb: put data in state if **any other code needs to react to it changi To add a new major section of the server (say, a HID device connection): 1. **Define the state**: - ```kotlin - data class HIDConnectionState( - val deviceId: Int?, - val connected: Boolean, - ) - ``` +```kotlin +data class HIDConnectionState( + val deviceId: Int?, + val connected: Boolean, +) +``` 2. **Define sealed actions**: - ```kotlin - sealed interface HIDConnectionActions { - data class Connected(val deviceId: Int) : HIDConnectionActions - data object Disconnected : HIDConnectionActions - } - ``` +```kotlin +sealed interface HIDConnectionActions { + data class Connected(val deviceId: Int) : HIDConnectionActions + data object Disconnected : HIDConnectionActions +} +``` 3. **Create type aliases** (keeps signatures readable): - ```kotlin - typealias HIDConnectionContext = Context - typealias HIDConnectionBehaviour = CustomBehaviour - ``` +```kotlin +typealias HIDConnectionContext = Context +typealias HIDConnectionBehaviour = CustomBehaviour +``` 4. **Define the module struct** (holds context + extra runtime state): - ```kotlin - data class HIDConnection( - val context: HIDConnectionContext, - val serverContext: VRServer, - val send: suspend (ByteArray) -> Unit, - ) - ``` +```kotlin +data class HIDConnection( + val context: HIDConnectionContext, + val serverContext: VRServer, + val send: suspend (ByteArray) -> Unit, +) +``` 5. **Write behaviours** as top-level `val`s (stateless, reusable): - ```kotlin - val HIDHandshakeBehaviour = HIDConnectionBehaviour( - reducer = { s, a -> when (a) { - is HIDConnectionActions.Connected -> s.copy(deviceId = a.deviceId, connected = true) - is HIDConnectionActions.Disconnected -> s.copy(connected = false) - }}, - observer = { conn -> - // launch coroutines, subscribe to events, etc. - } - ) - ``` +```kotlin +val HIDHandshakeBehaviour = HIDConnectionBehaviour( + reducer = { s, a -> when (a) { + is HIDConnectionActions.Connected -> s.copy(deviceId = a.deviceId, connected = true) + is HIDConnectionActions.Disconnected -> s.copy(connected = false) + }}, + observer = { conn -> + // launch coroutines, subscribe to events, etc. + } +) +``` 6. **Write a factory function**: - ```kotlin - fun createHIDConnection( - serverContext: VRServer, - scope: CoroutineScope, - send: suspend (ByteArray) -> Unit, - ): HIDConnection { - val behaviours = listOf(HIDHandshakeBehaviour, ...) - val context = createContext(initialState = ..., reducers = behaviours.map { it.reducer }, scope = scope) - val conn = HIDConnection(context, serverContext, send) - behaviours.map { it.observer }.forEach { it?.invoke(conn) } - return conn - } - ``` +```kotlin +fun createHIDConnection( + serverContext: VRServer, + scope: CoroutineScope, + send: suspend (ByteArray) -> Unit, +): HIDConnection { + val behaviours = listOf(HIDHandshakeBehaviour, ...) + val context = createContext(initialState = ..., reducers = behaviours.map { it.reducer }, scope = scope) + val conn = HIDConnection(context, serverContext, send) + behaviours.map { it.observer }.forEach { it?.invoke(conn) } + return conn +} +``` --- @@ -194,11 +194,11 @@ Example: adding battery tracking to a HID connection requires only adding a `HID 1. Add the packet class and its `read` function in `tracker/udp/packets.kt` 2. In the relevant behaviour's observer, register a listener: - ```kotlin - connection.packetEvents.on { event -> - // handle it - } - ``` +```kotlin +connection.packetEvents.on { event -> + // handle it +} +``` 3. In `tracker/udp/server.kt`, route the new packet type to `emit`. --- @@ -250,9 +250,10 @@ Each client runs in its own `launch` block. When the socket disconnects, the cor ## Style Conventions +- **Limit OOP to strictly necessary cases.** Prefer plain functions, function types, and data classes. Avoid classes and inheritance unless there is a genuine need for encapsulated mutable state or polymorphism. A single-method interface should almost always be a function type instead (`() -> Unit`, `suspend (String) -> Unit`, etc.). When in doubt, write a function. - **Prefer plain functions over extension functions.** Only use extension functions when the receiver type is genuinely the primary subject and the function would be confusing without it. - Behaviours are top-level `val`s (or `object`s if they have no type parameters), not inner classes. - Factory functions are named `createX`, not `XBuilder` or `X.create` (though `companion object { fun create() }` is acceptable when scoping makes it clearer, as in `VRServer.create`). - State data classes use `copy(...)` inside reducers and `Update { copy(...) }` actions — never expose a `MutableStateFlow` directly. - **Never use `var` in a state data class** — state must be immutable, all fields `val`. Using `var` in any data class is almost certainly a design mistake; if you need mutable fields, prefer a plain class or rethink the structure. -- Use `sealed interface` for action types, not `sealed class`, to avoid the extra constructor overhead. \ No newline at end of file +- Use `sealed interface` for action types, not `sealed class`, to avoid the extra constructor overhead. diff --git a/server/core/build.gradle.kts b/server/core/build.gradle.kts index 8a0578c8a..700aa3ab6 100644 --- a/server/core/build.gradle.kts +++ b/server/core/build.gradle.kts @@ -76,8 +76,6 @@ dependencies { implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktor_version") implementation("io.ktor:ktor-utils:$ktor_version") - - api("com.github.loucass003:EspflashKotlin:v0.11.0") // Allow the use of reflection diff --git a/server/core/src/main/java/dev/slimevr/config/config.kt b/server/core/src/main/java/dev/slimevr/config/config.kt index 5a971cc66..260bf4ea0 100644 --- a/server/core/src/main/java/dev/slimevr/config/config.kt +++ b/server/core/src/main/java/dev/slimevr/config/config.kt @@ -1,11 +1,10 @@ package dev.slimevr.config -import dev.slimevr.context.BasicModule +import dev.slimevr.context.BasicBehaviour import dev.slimevr.context.Context import dev.slimevr.context.createContext import kotlinx.coroutines.CoroutineScope import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.intOrNull @@ -13,7 +12,6 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import java.io.File - private const val GLOBAL_CONFIG_VERSION = 1 @Serializable @@ -29,7 +27,7 @@ sealed interface GlobalConfigActions { } typealias GlobalConfigContext = Context -typealias GlobalConfigModule = BasicModule +typealias GlobalConfigBehaviour = BasicBehaviour private fun migrateGlobalConfig(json: JsonObject): JsonObject { val version = json["version"]?.jsonPrimitive?.intOrNull ?: 0 @@ -44,7 +42,7 @@ private fun parseAndMigrateGlobalConfig(raw: String): GlobalConfigState { return jsonConfig.decodeFromJsonElement(migrateGlobalConfig(json)) } -val DefaultGlobalConfigModule = GlobalConfigModule( +val DefaultGlobalConfigBehaviour = GlobalConfigBehaviour( reducer = { s, a -> when (a) { is GlobalConfigActions.SetUserProfile -> s.copy(selectedUserProfile = a.name) @@ -66,9 +64,11 @@ suspend fun createAppConfig(scope: CoroutineScope, configFolder: File): AppConfi parseAndMigrateGlobalConfig(it) } + val behaviours = listOf(DefaultGlobalConfigBehaviour) + val globalContext = createContext( initialState = initialGlobal, - reducers = listOf(DefaultGlobalConfigModule.reducer), + reducers = behaviours.map { it.reducer }, scope = scope, ) diff --git a/server/core/src/main/java/dev/slimevr/config/configio.kt b/server/core/src/main/java/dev/slimevr/config/configio.kt index f2aba7607..fad652597 100644 --- a/server/core/src/main/java/dev/slimevr/config/configio.kt +++ b/server/core/src/main/java/dev/slimevr/config/configio.kt @@ -32,35 +32,34 @@ suspend fun atomicWriteFile(file: File, content: String) = withContext(Dispatche Unit } -suspend inline fun loadFileWithBackup(file: File, default: T, crossinline deserialize: (String) -> T): T = - withContext(Dispatchers.IO) { - if (!file.exists()) { - atomicWriteFile(file, jsonConfig.encodeToString(default)) - return@withContext default - } - - try { - deserialize(file.readText()) - } catch (e: Exception) { - System.err.println("Failed to load ${file.absolutePath}: ${e.message}") - if (file.exists()) { - try { - val bakTmp = File(file.parent, "${file.name}.bak.tmp") - file.copyTo(bakTmp, overwrite = true) - Files.move( - bakTmp.toPath(), - File(file.parent, "${file.name}.bak").toPath(), - StandardCopyOption.ATOMIC_MOVE, - StandardCopyOption.REPLACE_EXISTING - ) - } catch (e2: Exception) { - System.err.println("Failed to back up corrupted file: ${e2.message}") - } - } - default - } +suspend inline fun loadFileWithBackup(file: File, default: T, crossinline deserialize: (String) -> T): T = withContext(Dispatchers.IO) { + if (!file.exists()) { + atomicWriteFile(file, jsonConfig.encodeToString(default)) + return@withContext default } + try { + deserialize(file.readText()) + } catch (e: Exception) { + System.err.println("Failed to load ${file.absolutePath}: ${e.message}") + if (file.exists()) { + try { + val bakTmp = File(file.parent, "${file.name}.bak.tmp") + file.copyTo(bakTmp, overwrite = true) + Files.move( + bakTmp.toPath(), + File(file.parent, "${file.name}.bak").toPath(), + StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING, + ) + } catch (e2: Exception) { + System.err.println("Failed to back up corrupted file: ${e2.message}") + } + } + default + } +} + /** * Launches a debounced autosave coroutine. Skips the initial state (already on * disk at start time) and any state that was already successfully persisted. diff --git a/server/core/src/main/java/dev/slimevr/config/settings.kt b/server/core/src/main/java/dev/slimevr/config/settings.kt index e20796da9..4a5aeea0f 100644 --- a/server/core/src/main/java/dev/slimevr/config/settings.kt +++ b/server/core/src/main/java/dev/slimevr/config/settings.kt @@ -1,7 +1,7 @@ package dev.slimevr.config import dev.slimevr.context.Context -import dev.slimevr.context.CustomModule +import dev.slimevr.context.CustomBehaviour import dev.slimevr.context.createContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -46,7 +46,7 @@ sealed interface SettingsActions { } typealias SettingsContext = Context -typealias SettingsModule = CustomModule +typealias SettingsBehaviour = CustomBehaviour data class Settings( val context: SettingsContext, @@ -54,7 +54,7 @@ data class Settings( val swap: suspend (String) -> Unit, ) -val DefaultSettingsModule = SettingsModule( +val DefaultSettingsBehaviour = SettingsBehaviour( reducer = { s, a -> when (a) { is SettingsActions.Update -> a.transform(s) @@ -72,11 +72,12 @@ suspend fun createSettings(scope: CoroutineScope, configDir: File, name: String) } val initialState = SettingsState(name = name, data = initialData) - val modules = listOf(DefaultSettingsModule) + val behaviours = listOf(DefaultSettingsBehaviour) + val context = createContext( initialState = initialState, - reducers = modules.map { it.reducer }, - scope = scope + reducers = behaviours.map { it.reducer }, + scope = scope, ) fun startAutosave() = launchAutosave( diff --git a/server/core/src/main/java/dev/slimevr/config/user.kt b/server/core/src/main/java/dev/slimevr/config/user.kt index e9a4c41d9..0d9553c01 100644 --- a/server/core/src/main/java/dev/slimevr/config/user.kt +++ b/server/core/src/main/java/dev/slimevr/config/user.kt @@ -1,9 +1,8 @@ package dev.slimevr.config import dev.slimevr.context.Context -import dev.slimevr.context.CustomModule +import dev.slimevr.context.CustomBehaviour import dev.slimevr.context.createContext -import dev.slimevr.tracker.DeviceActions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin @@ -47,7 +46,7 @@ sealed interface UserConfigActions { } typealias UserConfigContext = Context -typealias UserConfigModule = CustomModule +typealias UserConfigBehaviour = CustomBehaviour data class UserConfig( val context: UserConfigContext, @@ -55,7 +54,7 @@ data class UserConfig( val swap: suspend (String) -> Unit, ) -val DefaultUserModule = UserConfigModule( +val DefaultUserBehaviour = UserConfigBehaviour( reducer = { s, a -> when (a) { is UserConfigActions.Update -> a.transform(s) @@ -73,11 +72,12 @@ suspend fun createUserConfig(scope: CoroutineScope, configDir: File, name: Strin } val initialState = UserConfigState(name = name, data = initialData) - val modules = listOf(DefaultUserModule) + val behaviours = listOf(DefaultUserBehaviour) + val context = createContext( initialState = initialState, - reducers = modules.map { it.reducer }, - scope = scope + reducers = behaviours.map { it.reducer }, + scope = scope, ) fun startAutosave() = launchAutosave( diff --git a/server/core/src/main/java/dev/slimevr/firmware/download.kt b/server/core/src/main/java/dev/slimevr/firmware/download.kt new file mode 100644 index 000000000..ebc27e5ce --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/firmware/download.kt @@ -0,0 +1,48 @@ +package dev.slimevr.firmware + +import java.io.ByteArrayOutputStream +import java.net.URL +import java.security.MessageDigest + +data class DownloadedFirmwarePart( + val data: ByteArray, + val offset: Int, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + other as DownloadedFirmwarePart + if (!data.contentEquals(other.data)) return false + return offset == other.offset + } + + override fun hashCode(): Int { + var result = data.contentHashCode() + result = 31 * result + offset + return result + } +} + +fun downloadFirmware(url: String, digest: String): ByteArray { + val output = ByteArrayOutputStream() + val chunk = ByteArray(4096) + URL(url).openStream().use { stream -> + while (true) { + val read = stream.read(chunk) + if (read <= 0) break + output.write(chunk, 0, read) + } + } + val data = output.toByteArray() + check(verifyChecksum(data, digest)) { "Checksum verification failed for $url" } + return data +} + +fun verifyChecksum(data: ByteArray, expectedDigest: String): Boolean { + val parts = expectedDigest.split(":", limit = 2) + check(parts.size == 2) { "Invalid digest format '$expectedDigest', expected 'algorithm:hash'" } + val algorithm = parts[0].uppercase().replace("-", "") + val expectedHash = parts[1].lowercase() + val actualHash = MessageDigest.getInstance(algorithm).digest(data).joinToString("") { "%02x".format(it) } + return actualHash == expectedHash +} diff --git a/server/core/src/main/java/dev/slimevr/firmware/server.kt b/server/core/src/main/java/dev/slimevr/firmware/server.kt new file mode 100644 index 000000000..bec07afb2 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/firmware/server.kt @@ -0,0 +1,263 @@ +package dev.slimevr.firmware + +import dev.llelievr.espflashkotlin.Flasher +import dev.llelievr.espflashkotlin.FlashingProgressListener +import dev.slimevr.VRServer +import dev.slimevr.context.BasicBehaviour +import dev.slimevr.context.Context +import dev.slimevr.context.createContext +import dev.slimevr.serial.SerialConnection +import dev.slimevr.serial.SerialServer +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.mapNotNull +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import solarxr_protocol.rpc.FirmwarePart +import solarxr_protocol.rpc.FirmwareUpdateStatus + +private val MAC_REGEX = Regex("mac: (([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2})", RegexOption.IGNORE_CASE) + +data class FirmwareJobStatus( + val portLocation: String, + val status: FirmwareUpdateStatus, + val progress: Int = 0, +) + +data class FirmwareManagerState( + val jobs: Map, +) + +sealed interface FirmwareManagerActions { + data class UpdateJob(val portLocation: String, val status: FirmwareUpdateStatus, val progress: Int = 0) : FirmwareManagerActions + + data class RemoveJob(val portLocation: String) : FirmwareManagerActions +} + +typealias FirmwareManagerContext = Context +typealias FirmwareManagerBehaviour = BasicBehaviour + +val FirmwareManagerBaseBehaviour = FirmwareManagerBehaviour( + reducer = { s, a -> + when (a) { + is FirmwareManagerActions.UpdateJob -> s.copy( + jobs = s.jobs + (a.portLocation to FirmwareJobStatus(a.portLocation, a.status, a.progress)), + ) + + is FirmwareManagerActions.RemoveJob -> s.copy(jobs = s.jobs - a.portLocation) + } + }, + observer = null, +) + +data class FirmwareManager( + val context: FirmwareManagerContext, + val flash: suspend (portLocation: String, parts: List, needManualReboot: Boolean, ssid: String?, password: String?, server: VRServer) -> Unit, + val cancelAll: suspend () -> Unit, +) + +@OptIn(ExperimentalCoroutinesApi::class) +suspend fun doSerialFlash( + portLocation: String, + parts: List, + needManualReboot: Boolean, + ssid: String?, + password: String?, + serialServer: SerialServer, + server: VRServer, + onStatus: suspend (FirmwareUpdateStatus, Int) -> Unit, + scope: CoroutineScope, +) { + onStatus(FirmwareUpdateStatus.DOWNLOADING, 0) + + val downloadedParts = try { + withContext(Dispatchers.IO) { + parts.map { part -> + val url = part.url ?: error("missing url") + val digest = part.digest ?: error("missing digest") + DownloadedFirmwarePart( + data = downloadFirmware(url, digest), + offset = part.offset.toInt(), + ) + } + } + } catch (_: Exception) { + onStatus(FirmwareUpdateStatus.ERROR_DOWNLOAD_FAILED, 0) + return + } + + onStatus(FirmwareUpdateStatus.SYNCING_WITH_MCU, 0) + + val handler = serialServer.openForFlashing(portLocation) ?: run { + onStatus(FirmwareUpdateStatus.ERROR_DEVICE_NOT_FOUND, 0) + return + } + + val flasher = Flasher(handler) + for (part in downloadedParts) { + flasher.addBin(part.data, part.offset) + } + flasher.addProgressListener( + object : FlashingProgressListener { + override fun progress(progress: Float) { + scope.launch { onStatus(FirmwareUpdateStatus.UPLOADING, (progress * 100).toInt()) } + } + }, + ) + + val runFlasher = runCatching { + withContext(Dispatchers.IO) { flasher.flash(portLocation) } + } + + if (runFlasher.isFailure) { + onStatus(FirmwareUpdateStatus.ERROR_UPLOAD_FAILED, 0) + return + } + + onStatus( + if (needManualReboot) { + FirmwareUpdateStatus.NEED_MANUAL_REBOOT + } else { + FirmwareUpdateStatus.REBOOTING + }, + 0, + ) + + serialServer.openConnection(portLocation) + val serialConn = serialServer.context.state.value.connections[portLocation] + if (serialConn == null) { + onStatus(FirmwareUpdateStatus.ERROR_DEVICE_NOT_FOUND, 0) + return + } + if (serialConn !is SerialConnection.Console) { + onStatus(FirmwareUpdateStatus.ERROR_UNKNOWN, 0) + return + } + + if (needManualReboot) { + // wait for the device to reboot + val rebooted = withTimeoutOrNull(60_000) { + serialConn.context.state.map { it.logLines } + .filter { logLines -> logLines.any { "starting up" in it.lowercase() } } + .first() + } + + if (rebooted == null) { + onStatus(FirmwareUpdateStatus.ERROR_TIMEOUT, 0) + return + } + } + + // get MAC address by sending GET INFO and parsing the response + serialConn.handle.writeCommand("GET INFO") + + val macAddress = withTimeoutOrNull(10_000) { + serialConn.context.state.map { it.logLines }.mapNotNull { logLines -> + logLines.firstNotNullOfOrNull { line -> + MAC_REGEX.find(line)?.groupValues?.get(1)?.uppercase() + } + }.first() + } + + if (macAddress == null) { + onStatus(FirmwareUpdateStatus.ERROR_PROVISIONING_FAILED, 0) + return + } + + // provision with Wi-Fi credentials + if (ssid == null || password == null) { + onStatus(FirmwareUpdateStatus.ERROR_PROVISIONING_FAILED, 0) + return + } + + onStatus(FirmwareUpdateStatus.PROVISIONING, 0) + serialConn.handle.writeCommand("SET WIFI \"$ssid\" \"$password\"\n") + + // Wait for Wi-Fi to connect ("looking for the server") + val provisioned = withTimeoutOrNull(30_000) { + serialConn.context.state.map { it.logLines }.filter { logLines -> + logLines.any { + "looking for the server" in it.lowercase() || "searching for the server" in it.lowercase() + } + }.first() + } + + if (provisioned == null) { + onStatus(FirmwareUpdateStatus.ERROR_PROVISIONING_FAILED, 0) + return + } + + // wait for the tracker with that MAC to connect to the server via UDP + val connected = withTimeoutOrNull(60_000) { + server.context.state + .map { state -> state.devices.values.any { it.context.state.value.address.uppercase() == macAddress } } + .filter { it } + .first() + } + + if (connected == null) { + onStatus(FirmwareUpdateStatus.ERROR_TIMEOUT, 0) + return + } + + onStatus(FirmwareUpdateStatus.DONE, 0) +} + +fun createFirmwareManager( + serialServer: SerialServer, + scope: CoroutineScope, +): FirmwareManager { + val behaviours = listOf(FirmwareManagerBaseBehaviour) + + val context = createContext( + initialState = FirmwareManagerState(jobs = mapOf()), + reducers = behaviours.map { it.reducer }, + scope = scope, + ) + + val runningJobs = mutableMapOf() + + val flash: suspend (String, List, Boolean, String?, String?, VRServer) -> Unit = { portLocation, parts, needManualReboot, ssid, password, server -> + runningJobs[portLocation]?.cancelAndJoin() + runningJobs[portLocation] = scope.launch { + doSerialFlash( + portLocation = portLocation, + parts = parts, + needManualReboot = needManualReboot, + ssid = ssid, + password = password, + serialServer = serialServer, + server = server, + onStatus = { status, progress -> + context.dispatch(FirmwareManagerActions.UpdateJob(portLocation, status, progress)) + }, + scope = scope, + ) + } + } + + val cancelAll: suspend () -> Unit = { + runningJobs.values.forEach { it.cancelAndJoin() } + runningJobs.clear() + } + + val manager = FirmwareManager( + context = context, + flash = flash, + cancelAll = cancelAll, + ) + + behaviours.map { it.observer }.forEach { it?.invoke(context) } + return manager +} diff --git a/server/core/src/main/java/dev/slimevr/logger.kt b/server/core/src/main/java/dev/slimevr/logger.kt index d2055d42b..aa0042704 100644 --- a/server/core/src/main/java/dev/slimevr/logger.kt +++ b/server/core/src/main/java/dev/slimevr/logger.kt @@ -11,7 +11,7 @@ object AppLogger { val device = logger("Device") val udp = logger("UDPConnection") val solarxr = logger("SolarXR") - + val serial = logger("Serial") init { loggingConfiguration { diff --git a/server/core/src/main/java/dev/slimevr/platform.kt b/server/core/src/main/java/dev/slimevr/platform.kt index b741df356..ffcd82f89 100644 --- a/server/core/src/main/java/dev/slimevr/platform.kt +++ b/server/core/src/main/java/dev/slimevr/platform.kt @@ -8,9 +8,11 @@ import kotlin.io.path.exists const val SLIMEVR_IDENTIFIER = "dev.slimevr.SlimeVR" - enum class Platform { - LINUX, WINDOWS, OSX, UNKNOWN + LINUX, + WINDOWS, + OSX, + UNKNOWN, } val CURRENT_PLATFORM: Platform = detectPlatform() @@ -59,15 +61,22 @@ fun resolveConfigDirectory(): Path? { val appData = System.getenv("AppData") if (appData != null) Path(appData, SLIMEVR_IDENTIFIER) else null } + Platform.LINUX -> { val xdg = System.getenv("XDG_CONFIG_HOME") - if (xdg != null) Path(xdg, SLIMEVR_IDENTIFIER) - else if (home != null) Path(home, ".config", SLIMEVR_IDENTIFIER) - else null + if (xdg != null) { + Path(xdg, SLIMEVR_IDENTIFIER) + } else if (home != null) { + Path(home, ".config", SLIMEVR_IDENTIFIER) + } else { + null + } } + Platform.OSX -> { if (home != null) Path(home, "Library", "Application Support", SLIMEVR_IDENTIFIER) else null } + else -> null } } @@ -78,13 +87,20 @@ fun resolveLogDirectory(): Path? { return when (CURRENT_PLATFORM) { Platform.WINDOWS -> if (appData != null) Path(appData, SLIMEVR_IDENTIFIER, "logs") else null + Platform.OSX -> if (home != null) Path(home, "Library", "Logs", SLIMEVR_IDENTIFIER) else null + Platform.LINUX -> { val xdg = System.getenv("XDG_DATA_HOME") - if (xdg != null) Path(xdg, SLIMEVR_IDENTIFIER, "logs") - else if (home != null) Path(home, ".local", "share", SLIMEVR_IDENTIFIER, "logs") - else null + if (xdg != null) { + Path(xdg, SLIMEVR_IDENTIFIER, "logs") + } else if (home != null) { + Path(home, ".local", "share", SLIMEVR_IDENTIFIER, "logs") + } else { + null + } } + else -> null } } diff --git a/server/core/src/main/java/dev/slimevr/serial/connection.kt b/server/core/src/main/java/dev/slimevr/serial/connection.kt new file mode 100644 index 000000000..31999de3a --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/serial/connection.kt @@ -0,0 +1,76 @@ +package dev.slimevr.serial + +import dev.slimevr.context.Context +import dev.slimevr.context.CustomBehaviour +import dev.slimevr.context.createContext +import kotlinx.coroutines.CoroutineScope + +private const val MAX_LOG_LINES = 500 + +data class SerialPortHandle( + val portLocation: String, + val descriptivePortName: String, + val writeCommand: (String) -> Unit, + val close: () -> Unit, +) + +data class SerialConnectionState( + val portLocation: String, + val descriptivePortName: String, + val connected: Boolean, + val logLines: List, +) + +sealed interface SerialConnectionActions { + data class LogLine(val line: String) : SerialConnectionActions + data object Disconnected : SerialConnectionActions +} + +typealias SerialConnectionContext = Context +typealias SerialConnectionBehaviour = + CustomBehaviour + +sealed interface SerialConnection { + data class Console( + val context: SerialConnectionContext, + val handle: SerialPortHandle, + ) : SerialConnection + + data object Flashing : SerialConnection +} + +val SerialLogBehaviour = SerialConnectionBehaviour( + reducer = { s, a -> + when (a) { + is SerialConnectionActions.LogLine -> { + val lines = if (s.logLines.size >= MAX_LOG_LINES) s.logLines.drop(1) else s.logLines + s.copy(logLines = lines + a.line) + } + + SerialConnectionActions.Disconnected -> s.copy(connected = false) + } + }, + observer = null, +) + +fun createSerialConnection( + handle: SerialPortHandle, + scope: CoroutineScope, +): SerialConnection.Console { + val behaviours = listOf(SerialLogBehaviour) + + val context = createContext( + initialState = SerialConnectionState( + portLocation = handle.portLocation, + descriptivePortName = handle.descriptivePortName, + connected = true, + logLines = listOf(), + ), + reducers = behaviours.map { it.reducer }, + scope = scope, + ) + + val conn = SerialConnection.Console(context = context, handle = handle) + behaviours.map { it.observer }.forEach { it?.invoke(conn) } + return conn +} diff --git a/server/core/src/main/java/dev/slimevr/serial/server.kt b/server/core/src/main/java/dev/slimevr/serial/server.kt new file mode 100644 index 000000000..348061f1c --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/serial/server.kt @@ -0,0 +1,152 @@ +package dev.slimevr.serial + +import dev.llelievr.espflashkotlin.FlasherSerialInterface +import dev.slimevr.context.BasicBehaviour +import dev.slimevr.context.Context +import dev.slimevr.context.createContext +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import solarxr_protocol.rpc.SerialDevice + +typealias FlashingHandler = FlasherSerialInterface + +data class SerialPortInfo( + val portLocation: String, + val descriptivePortName: String, + val vendorId: Int, + val productId: Int, +) { + fun toSerialDevice() = SerialDevice( + port = portLocation, + name = descriptivePortName, + ) +} + +data class SerialServerState( + val availablePorts: Map, + val connections: Map, +) + +sealed interface SerialServerActions { + data class PortDetected(val info: SerialPortInfo) : SerialServerActions + data class PortLost(val portLocation: String) : SerialServerActions + data class RegisterConnection(val portLocation: String, val connection: SerialConnection) : SerialServerActions + data class RemoveConnection(val portLocation: String) : SerialServerActions +} + +typealias SerialServerContext = Context +typealias SerialServerBehaviour = BasicBehaviour + +val SerialServerBaseBehaviour = SerialServerBehaviour( + reducer = { s, a -> + when (a) { + is SerialServerActions.PortDetected -> + s.copy(availablePorts = s.availablePorts + (a.info.portLocation to a.info)) + + is SerialServerActions.PortLost -> + s.copy(availablePorts = s.availablePorts - a.portLocation) + + is SerialServerActions.RegisterConnection -> + s.copy(connections = s.connections + (a.portLocation to a.connection)) + + is SerialServerActions.RemoveConnection -> + s.copy(connections = s.connections - a.portLocation) + } + }, + observer = null, +) + +class SerialServer( + val context: SerialServerContext, + private val scope: CoroutineScope, + private val openPortFactory: ( + portLocation: String, + scope: CoroutineScope, + onDataReceived: suspend (portLocation: String, line: String) -> Unit, + onPortDisconnected: suspend (portLocation: String) -> Unit, + ) -> SerialPortHandle?, + private val openFlashingPortFactory: () -> FlashingHandler, +) { + suspend fun onPortDetected(info: SerialPortInfo) { + context.dispatch(SerialServerActions.PortDetected(info)) + } + + suspend fun onPortLost(portLocation: String) { + val conn = context.state.value.connections[portLocation] + if (conn is SerialConnection.Console) { + conn.handle.close() + } + context.dispatch(SerialServerActions.RemoveConnection(portLocation)) + context.dispatch(SerialServerActions.PortLost(portLocation)) + } + + suspend fun onDataReceived(portLocation: String, line: String) { + val conn = context.state.value.connections[portLocation] + if (conn is SerialConnection.Console) conn.context.dispatch(SerialConnectionActions.LogLine(line)) + } + + suspend fun onPortDisconnected(portLocation: String) { + val conn = context.state.value.connections[portLocation] + if (conn !is SerialConnection.Console) return + conn.context.dispatch(SerialConnectionActions.Disconnected) + conn.handle.close() + context.dispatch(SerialServerActions.RemoveConnection(portLocation)) + } + + suspend fun openConnection(portLocation: String) { + val state = context.state.value + if (!state.availablePorts.containsKey(portLocation) || state.connections.containsKey(portLocation)) return + val handle = openPortFactory(portLocation, scope, ::onDataReceived, ::onPortDisconnected) ?: return + context.dispatch(SerialServerActions.RegisterConnection(portLocation, createSerialConnection(handle, scope))) + } + + suspend fun closeConnection(portLocation: String) { + val conn = context.state.value.connections[portLocation] + if (conn !is SerialConnection.Console) return + conn.context.dispatch(SerialConnectionActions.Disconnected) + conn.handle.close() + context.dispatch(SerialServerActions.RemoveConnection(portLocation)) + } + + suspend fun openForFlashing(portLocation: String): FlashingHandler? { + val state = context.state.value + if (!state.availablePorts.containsKey(portLocation) || state.connections.containsKey(portLocation)) return null + closeConnection(portLocation) + val handler = openFlashingPortFactory() + context.dispatch(SerialServerActions.RegisterConnection(portLocation, SerialConnection.Flashing)) + return object : FlashingHandler by handler { + override fun closeSerial() { + handler.closeSerial() + scope.launch { context.dispatch(SerialServerActions.RemoveConnection(portLocation)) } + } + } + } + + companion object { + fun create( + openPort: ( + portLocation: String, + scope: CoroutineScope, + onDataReceived: suspend (portLocation: String, line: String) -> Unit, + onPortDisconnected: suspend (portLocation: String) -> Unit, + ) -> SerialPortHandle?, + openFlashingPort: () -> FlashingHandler, + scope: CoroutineScope, + ): SerialServer { + val behaviours = listOf(SerialServerBaseBehaviour) + val context = createContext( + initialState = SerialServerState(availablePorts = mapOf(), connections = mapOf()), + reducers = behaviours.map { it.reducer }, + scope = scope, + ) + val server = SerialServer( + context = context, + scope = scope, + openPortFactory = openPort, + openFlashingPortFactory = openFlashingPort, + ) + behaviours.map { it.observer }.forEach { it?.invoke(context) } + return server + } + } +} diff --git a/server/core/src/main/java/dev/slimevr/skeleton/skeleton.kt b/server/core/src/main/java/dev/slimevr/skeleton/skeleton.kt index 5a01f49f6..a318db88d 100644 --- a/server/core/src/main/java/dev/slimevr/skeleton/skeleton.kt +++ b/server/core/src/main/java/dev/slimevr/skeleton/skeleton.kt @@ -3,15 +3,14 @@ package dev.slimevr.skeleton import io.github.axisangles.ktmath.Quaternion import solarxr_protocol.datatypes.BodyPart - data class Bone( val bodyPart: BodyPart, val localRotation: Quaternion, val parentBone: Bone?, - val childBone: List + val childBone: List, ) { val globalRotation: Quaternion - get() = localRotation //FIXME: do maths LMAO + get() = localRotation // FIXME: do maths LMAO } data class SkeletonState( diff --git a/server/core/src/main/java/dev/slimevr/solarxr/datafeed.kt b/server/core/src/main/java/dev/slimevr/solarxr/datafeed.kt index 5b4084f78..914f7155f 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/datafeed.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/datafeed.kt @@ -27,27 +27,30 @@ import solarxr_protocol.datatypes.hardware_info.HardwareStatus import solarxr_protocol.datatypes.math.Quat import kotlin.time.measureTime -private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMask: TrackerDataMask): TrackerData = - TrackerData( - trackerId = TrackerId( - trackerNum = tracker.id.toUByte(), - deviceId = DeviceId(device.id.toUByte()) - ), - status = if (trackerMask.status == true) tracker.status else null, - rotation = if (trackerMask.rotation == true) tracker.rawRotation.let { Quat(it.x, it.y, it.z, it.w) } else null, - info = if (trackerMask.info == true) TrackerInfo( +private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMask: TrackerDataMask): TrackerData = TrackerData( + trackerId = TrackerId( + trackerNum = tracker.id.toUByte(), + deviceId = DeviceId(device.id.toUByte()), + ), + status = if (trackerMask.status == true) tracker.status else null, + rotation = if (trackerMask.rotation == true) tracker.rawRotation.let { Quat(it.x, it.y, it.z, it.w) } else null, + info = if (trackerMask.info == true) { + TrackerInfo( imuType = tracker.sensorType, bodyPart = tracker.bodyPart, displayName = tracker.name, - ) else null - ) + ) + } else { + null + }, +) private fun createDevice( device: DeviceState, trackers: List, - datafeedConfig: DataFeedConfig + datafeedConfig: DataFeedConfig, ): DeviceData { - val trackerMask = datafeedConfig.dataMask?.trackerData; + val trackerMask = datafeedConfig.dataMask?.trackerData return DeviceData( id = DeviceId(device.id.toUByte()), @@ -55,18 +58,20 @@ private fun createDevice( batteryVoltage = device.batteryVoltage, batteryPctEstimate = device.batteryLevel.toUInt() .toUByte(), - ping = device.ping?.toUShort() + ping = device.ping?.toUShort(), ), - trackers = if (trackerMask != null) + trackers = if (trackerMask != null) { trackers.filter { it.deviceId == device.id } .map { tracker -> createTracker(device, tracker, trackerMask) } - else null + } else { + null + }, ) } fun createDatafeedFrame( serverContext: VRServer, - datafeedConfig: DataFeedConfig + datafeedConfig: DataFeedConfig, ): DataFeedMessageHeader { val serverState = serverContext.context.state.value val trackers = @@ -76,12 +81,11 @@ fun createDatafeedFrame( .map { device -> createDevice(device, trackers, datafeedConfig) } return DataFeedMessageHeader( message = DataFeedUpdate( - devices = if (datafeedConfig.dataMask?.deviceData != null) devices else null - ) + devices = if (datafeedConfig.dataMask?.deviceData != null) devices else null, + ), ) } - val DataFeedInitBehaviour = SolarXRConnectionBehaviour( observer = { context -> context.dataFeedDispatcher.on { event -> @@ -104,9 +108,9 @@ val DataFeedInitBehaviour = SolarXRConnectionBehaviour( fbb.finish( MessageBundle( dataFeedMsgs = listOf( - createDatafeedFrame(serverContext = context.serverContext, datafeedConfig = config) - ) - ).encode(fbb) + createDatafeedFrame(serverContext = context.serverContext, datafeedConfig = config), + ), + ).encode(fbb), ) context.send(fbb.dataBuffer().moveToByteArray()) @@ -121,8 +125,8 @@ val DataFeedInitBehaviour = SolarXRConnectionBehaviour( context.context.dispatch( SolarXRConnectionActions.SetConfig( datafeeds, - timers = timers - ) + timers = timers, + ), ) context.context.scope.launch { @@ -137,11 +141,11 @@ val DataFeedInitBehaviour = SolarXRConnectionBehaviour( fbb.finish( MessageBundle( dataFeedMsgs = listOf( - createDatafeedFrame(serverContext = context.serverContext, datafeedConfig = config) - ) - ).encode(fbb) + createDatafeedFrame(serverContext = context.serverContext, datafeedConfig = config), + ), + ).encode(fbb), ) context.send(fbb.dataBuffer().moveToByteArray()) } - } + }, ) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/firmware.kt b/server/core/src/main/java/dev/slimevr/solarxr/firmware.kt new file mode 100644 index 000000000..012c7b890 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/solarxr/firmware.kt @@ -0,0 +1,58 @@ +package dev.slimevr.solarxr + +import dev.slimevr.firmware.FirmwareJobStatus +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import solarxr_protocol.rpc.FirmwareUpdateRequest +import solarxr_protocol.rpc.FirmwareUpdateStatusResponse +import solarxr_protocol.rpc.FirmwareUpdateStopQueuesRequest +import solarxr_protocol.rpc.SerialDevicePort +import solarxr_protocol.rpc.SerialFirmwareUpdate + +val FirmwareBehaviour = SolarXRConnectionBehaviour( + observer = { conn -> + val scope = conn.context.scope + val firmwareManager = conn.serverContext.firmwareManager + + var prevJobs: Map = firmwareManager.context.state.value.jobs + + firmwareManager.context.state + .map { it.jobs } + .distinctUntilChanged() + .onEach { jobs -> + jobs.forEach { (portLocation, jobStatus) -> + if (prevJobs[portLocation] != jobStatus) { + conn.sendRpc( + FirmwareUpdateStatusResponse( + deviceId = SerialDevicePort(port = portLocation), + status = jobStatus.status, + progress = jobStatus.progress.toByte(), + ), + ) + } + } + prevJobs = jobs + } + .launchIn(scope) + + conn.rpcDispatcher.on { req -> + val method = req.method as? SerialFirmwareUpdate ?: return@on + val portLocation = method.deviceId?.port ?: return@on + val parts = method.firmwarePart ?: return@on + firmwareManager.flash( + portLocation, + parts, + method.needmanualreboot, + method.ssid, + method.password, + conn.serverContext + ) + } + + conn.rpcDispatcher.on { + firmwareManager.cancelAll() + } + }, +) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/serial.kt b/server/core/src/main/java/dev/slimevr/solarxr/serial.kt new file mode 100644 index 000000000..4ce356490 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/solarxr/serial.kt @@ -0,0 +1,134 @@ +package dev.slimevr.solarxr + +import dev.slimevr.serial.SerialConnection +import dev.slimevr.serial.SerialPortInfo +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import solarxr_protocol.rpc.CloseSerialRequest +import solarxr_protocol.rpc.NewSerialDeviceResponse +import solarxr_protocol.rpc.OpenSerialRequest +import solarxr_protocol.rpc.SerialDevice +import solarxr_protocol.rpc.SerialDevicesRequest +import solarxr_protocol.rpc.SerialDevicesResponse +import solarxr_protocol.rpc.SerialTrackerCustomCommandRequest +import solarxr_protocol.rpc.SerialTrackerFactoryResetRequest +import solarxr_protocol.rpc.SerialTrackerGetInfoRequest +import solarxr_protocol.rpc.SerialTrackerGetWifiScanRequest +import solarxr_protocol.rpc.SerialTrackerRebootRequest +import solarxr_protocol.rpc.SerialUpdateResponse + + +val SerialConsoleBehaviour = SolarXRConnectionBehaviour( + observer = { conn -> + val scope = conn.context.scope + val serialServer = conn.serverContext.serialServer + + // We assume that you can only subscribe to one serial console + // at a time + var logSubscription: Job? = null + var activePortLocation: String? = null + + // Notify client of new serial devices as they are detected. + // Existing devices at connection time are not sent here. the client + // should send SerialDevicesRequest to get the current list. + var prevPortKeys = serialServer.context.state.value.availablePorts.keys.toSet() + serialServer.context.state + .map { it.availablePorts } + .distinctUntilChanged() + .onEach { ports -> + (ports.keys - prevPortKeys).forEach { key -> + conn.sendRpc(NewSerialDeviceResponse(device = ports[key]!!.toSerialDevice())) + } + prevPortKeys = ports.keys.toSet() + } + .launchIn(scope) + + conn.rpcDispatcher.on { + conn.sendRpc( + SerialDevicesResponse( + devices = serialServer.context.state.value.availablePorts.values + .map { it.toSerialDevice() }, + ), + ) + } + + conn.rpcDispatcher.on { req -> + val portLocation = if (req.auto == true) { + serialServer.context.state.value.availablePorts.keys.firstOrNull() + } else { + req.port + } ?: return@on + + logSubscription?.cancel() + logSubscription = null + activePortLocation = null + + serialServer.openConnection(portLocation) + + val connection = serialServer.context.state.value.connections[portLocation] + if (connection !is SerialConnection.Console) return@on + + activePortLocation = portLocation + var lastSentCount = 0 + + logSubscription = scope.launch { + var disconnected = false + connection.context.state.collect { connState -> + if (disconnected) return@collect + + connState.logLines.drop(lastSentCount).forEach { line -> + conn.sendRpc(SerialUpdateResponse(log = line + "\n")) + } + lastSentCount = connState.logLines.size + + if (!connState.connected) { + disconnected = true + activePortLocation = null + conn.sendRpc(SerialUpdateResponse(closed = true)) + } + } + } + } + + conn.rpcDispatcher.on { + logSubscription?.cancel() + logSubscription = null + activePortLocation = null + } + + conn.rpcDispatcher.on { + val portLocation = activePortLocation ?: return@on + val c = serialServer.context.state.value.connections[portLocation] + if (c is SerialConnection.Console) c.handle.writeCommand("REBOOT") + } + + conn.rpcDispatcher.on { + val portLocation = activePortLocation ?: return@on + val c = serialServer.context.state.value.connections[portLocation] + if (c is SerialConnection.Console) c.handle.writeCommand("GET INFO") + } + + conn.rpcDispatcher.on { + val portLocation = activePortLocation ?: return@on + val c = serialServer.context.state.value.connections[portLocation] + if (c is SerialConnection.Console) c.handle.writeCommand("FRST") + } + + conn.rpcDispatcher.on { + val portLocation = activePortLocation ?: return@on + val c = serialServer.context.state.value.connections[portLocation] + if (c is SerialConnection.Console) c.handle.writeCommand("GET WIFISCAN") + } + + conn.rpcDispatcher.on { req -> + val portLocation = activePortLocation ?: return@on + val command = req.command ?: return@on + val c = serialServer.context.state.value.connections[portLocation] + if (c is SerialConnection.Console) c.handle.writeCommand(command) + } + }, +) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/solarxr.kt b/server/core/src/main/java/dev/slimevr/solarxr/solarxr.kt index b3c8d3b45..497f33084 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/solarxr.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/solarxr.kt @@ -1,16 +1,20 @@ package dev.slimevr.solarxr +import com.google.flatbuffers.FlatBufferBuilder import dev.slimevr.VRServer import dev.slimevr.context.Context import dev.slimevr.context.CustomBehaviour import dev.slimevr.context.createContext +import io.ktor.util.moveToByteArray import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import solarxr_protocol.MessageBundle import solarxr_protocol.data_feed.DataFeedConfig import solarxr_protocol.data_feed.DataFeedMessage import solarxr_protocol.rpc.RpcMessage +import solarxr_protocol.rpc.RpcMessageHeader import kotlin.reflect.KClass data class SolarXRConnectionState( @@ -19,14 +23,12 @@ data class SolarXRConnectionState( ) sealed interface SolarXRConnectionActions { - data class SetConfig(val configs: List, val timers: List) : - SolarXRConnectionActions + data class SetConfig(val configs: List, val timers: List) : SolarXRConnectionActions } typealias SolarXRConnectionContext = Context typealias SolarXRConnectionBehaviour = CustomBehaviour - class PacketDispatcher { val listeners = mutableMapOf, MutableList Unit>>() val globalListeners = mutableListOf Unit>() @@ -59,21 +61,21 @@ data class SolarXRConnection( val serverContext: VRServer, val dataFeedDispatcher: PacketDispatcher, val rpcDispatcher: PacketDispatcher, - val send: suspend (ByteArray) -> Unit + val send: suspend (ByteArray) -> Unit, + val sendRpc: suspend (RpcMessage) -> Unit, ) fun createSolarXRConnection( serverContext: VRServer, onSend: suspend (ByteArray) -> Unit, - scope: CoroutineScope + scope: CoroutineScope, ): SolarXRConnection { - val state = SolarXRConnectionState( dataFeedConfigs = listOf(), - datafeedTimers = listOf() + datafeedTimers = listOf(), ) - val behaviours = listOf(DataFeedInitBehaviour) + val behaviours = listOf(DataFeedInitBehaviour, SerialConsoleBehaviour, FirmwareBehaviour) val context = createContext( initialState = state, @@ -81,12 +83,21 @@ fun createSolarXRConnection( scope = scope, ) + val sendRpc: suspend (RpcMessage) -> Unit = { message -> + val fbb = FlatBufferBuilder(256) + fbb.finish( + MessageBundle(rpcMsgs = listOf(RpcMessageHeader(message = message))).encode(fbb), + ) + onSend(fbb.dataBuffer().moveToByteArray()) + } + val conn = SolarXRConnection( context = context, serverContext = serverContext, dataFeedDispatcher = PacketDispatcher(), rpcDispatcher = PacketDispatcher(), - onSend, + send = onSend, + sendRpc = sendRpc, ) behaviours.map { it.observer }.forEach { it?.invoke(conn) } diff --git a/server/core/src/main/java/dev/slimevr/solarxr/ws-server.kt b/server/core/src/main/java/dev/slimevr/solarxr/ws-server.kt index c83d146d7..40439beb7 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/ws-server.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/ws-server.kt @@ -2,47 +2,40 @@ package dev.slimevr.solarxr import dev.slimevr.AppLogger import dev.slimevr.VRServer -import io.ktor.server.application.* +import io.ktor.server.application.install import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.server.routing.routing -import io.ktor.server.websocket.* +import io.ktor.server.websocket.WebSockets +import io.ktor.server.websocket.webSocket import io.ktor.websocket.Frame +import kotlinx.coroutines.awaitCancellation import solarxr_protocol.MessageBundle import solarxr_protocol.rpc.ResetRequest import java.nio.ByteBuffer const val SOLARXR_PORT = 21110 - suspend fun onSolarXRMessage(message: ByteBuffer, context: SolarXRConnection) { val messageBundle = MessageBundle.fromByteBuffer(message) messageBundle.dataFeedMsgs?.forEach { - val msg = it.message ?: return; + val msg = it.message ?: return context.dataFeedDispatcher.emit(msg) } - // FIXME: temporary test - context.rpcDispatcher.on { - println("RESET $it") - } - messageBundle.rpcMsgs?.forEach { - val msg = it.message ?: return; + val msg = it.message ?: return context.rpcDispatcher.emit(msg) } - } - -fun createSolarXRWebsocketServer(serverContext: VRServer) { - embeddedServer(Netty, port = SOLARXR_PORT) { +suspend fun createSolarXRWebsocketServer(serverContext: VRServer) { + val engine = embeddedServer(Netty, port = SOLARXR_PORT) { install(WebSockets) routing { webSocket { - val solarxrConnection = createSolarXRConnection(serverContext, scope = this, onSend = { send(Frame.Binary(fin = true, data = it)) @@ -52,7 +45,7 @@ fun createSolarXRWebsocketServer(serverContext: VRServer) { when (frame) { is Frame.Binary -> onSolarXRMessage( frame.buffer, - solarxrConnection + solarxrConnection, ) is Frame.Close -> { @@ -61,10 +54,14 @@ fun createSolarXRWebsocketServer(serverContext: VRServer) { else -> {} } - } } } - }.start(wait = true) + } + engine.start(wait = false) + try { + awaitCancellation() + } finally { + engine.stop() + } } - diff --git a/server/core/src/main/java/dev/slimevr/tracker/device.kt b/server/core/src/main/java/dev/slimevr/tracker/device.kt index 11575d07c..d8cc19b05 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/device.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/device.kt @@ -14,6 +14,7 @@ enum class DeviceOrigin { FEEDER, UDP, HID, + SERIAL, } data class DeviceState( @@ -31,15 +32,13 @@ sealed interface DeviceActions { data class Update(val transform: DeviceState.() -> DeviceState) : DeviceActions } - - val DeviceStatsBehaviour = DeviceBehaviour( reducer = { s, a -> if (a is DeviceActions.Update) a.transform(s) else s }, observer = { it.state.onEach { state -> -// AppLogger.device.info("Device state changed", state) +// AppLogger.device.info("Device state changed", state) }.launchIn(it.scope) - } + }, ) typealias DeviceContext = Context diff --git a/server/core/src/main/java/dev/slimevr/tracker/tracker.kt b/server/core/src/main/java/dev/slimevr/tracker/tracker.kt index f1042ce93..616af4263 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/tracker.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/tracker.kt @@ -24,7 +24,7 @@ data class TrackerState( val customName: String?, val rawRotation: Quaternion, val deviceId: Int, - val origin: DeviceOrigin + val origin: DeviceOrigin, ) sealed interface TrackerActions { @@ -35,17 +35,16 @@ typealias TrackerContext = Context typealias TrackerBehaviour = BasicBehaviour data class Tracker( - val context: TrackerContext + val context: TrackerContext, ) - val TrackerInfosBehaviour = TrackerBehaviour( reducer = { s, a -> if (a is TrackerActions.Update) a.transform(s) else s }, observer = { it.state.onEach { state -> -// AppLogger.tracker.info("Tracker state changed {State}", state) +// AppLogger.tracker.info("Tracker state changed {State}", state) }.launchIn(it.scope) - } + }, ) fun createTracker( @@ -55,7 +54,7 @@ fun createTracker( sensorType: ImuType, hardwareId: String, origin: DeviceOrigin, - serverContext: VRServer + serverContext: VRServer, ): Tracker { val trackerState = TrackerState( id = id, @@ -67,7 +66,7 @@ fun createTracker( origin = origin, deviceId = deviceId, customName = null, - sensorType = sensorType + sensorType = sensorType, ) val behaviours = listOf(TrackerInfosBehaviour) diff --git a/server/core/src/main/java/dev/slimevr/tracker/udp/connection.kt b/server/core/src/main/java/dev/slimevr/tracker/udp/connection.kt index a8981bda4..0fd84fe99 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/udp/connection.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/udp/connection.kt @@ -6,9 +6,6 @@ import dev.slimevr.VRServerActions import dev.slimevr.context.Context import dev.slimevr.context.CustomBehaviour import dev.slimevr.context.createContext -import dev.slimevr.solarxr.SolarXRConnection -import dev.slimevr.solarxr.SolarXRConnectionActions -import dev.slimevr.solarxr.SolarXRConnectionState import dev.slimevr.tracker.Device import dev.slimevr.tracker.DeviceActions import dev.slimevr.tracker.DeviceOrigin @@ -41,22 +38,20 @@ data class UDPConnectionState( val address: String, val port: Int, val deviceId: Int?, - val trackerIds: List + val trackerIds: List, ) sealed interface UDPConnectionActions { data class StartPing(val startTime: Long) : UDPConnectionActions data class ReceivedPong(val id: Int, val duration: Long) : UDPConnectionActions data class Handshake(val deviceId: Int) : UDPConnectionActions - data class LastPacket(val packetNum: Long? = null, val time: Long) : - UDPConnectionActions + data class LastPacket(val packetNum: Long? = null, val time: Long) : UDPConnectionActions data class AssignTracker(val trackerId: TrackerIdNum) : UDPConnectionActions } typealias UDPConnectionContext = Context typealias UDPConnectionBehaviour = CustomBehaviour - data class UDPConnection( val context: UDPConnectionContext, val serverContext: VRServer, @@ -91,8 +86,8 @@ val PacketBehaviour = UDPConnectionBehaviour( it.context.dispatch( UDPConnectionActions.LastPacket( packetNum = 0, - time = now - ) + time = now, + ), ) AppLogger.udp.info("Reconnecting") } else if (packet.packetNumber < state.lastPacketNum) { @@ -151,12 +146,14 @@ val PingBehaviour = UDPConnectionBehaviour( it.context.dispatch( UDPConnectionActions.ReceivedPong( id = packet.data.pingId, - duration = ping - ) + duration = ping, + ), + ) + device.context.dispatch( + DeviceActions.Update { + copy(ping = ping) + }, ) - device.context.dispatch(DeviceActions.Update { - copy(ping = ping) - }) } }, ) @@ -166,8 +163,9 @@ val HandshakeBehaviour = UDPConnectionBehaviour( when (a) { is UDPConnectionActions.Handshake -> s.copy( didHandshake = true, - deviceId = a.deviceId + deviceId = a.deviceId, ) + else -> s } }, @@ -189,8 +187,8 @@ val HandshakeBehaviour = UDPConnectionBehaviour( it.serverContext.context.dispatch( VRServerActions.NewDevice( deviceId = deviceId, - context = newDevice - ) + context = newDevice, + ), ) it.context.dispatch(UDPConnectionActions.Handshake(deviceId)) it.send(Handshake()) @@ -206,22 +204,26 @@ val DeviceStatsBehaviour = UDPConnectionBehaviour( it.packetEvents.on { event -> val device = it.getDevice() ?: return@on - device.context.dispatch(DeviceActions.Update { - copy( - batteryLevel = event.data.level, - batteryVoltage = event.data.voltage - ) - }) + device.context.dispatch( + DeviceActions.Update { + copy( + batteryLevel = event.data.level, + batteryVoltage = event.data.voltage, + ) + }, + ) } it.packetEvents.on { event -> val device = it.getDevice() ?: return@on - device.context.dispatch(DeviceActions.Update { - copy(signalStrength = event.data.signal) - }) + device.context.dispatch( + DeviceActions.Update { + copy(signalStrength = event.data.signal) + }, + ) } - } + }, ) val SensorInfoBehaviour = UDPConnectionBehaviour( @@ -260,28 +262,27 @@ val SensorInfoBehaviour = UDPConnectionBehaviour( deviceId = deviceState.id, origin = DeviceOrigin.UDP, serverContext = observerContext.serverContext, - scope = observerContext.serverContext.context.scope + scope = observerContext.serverContext.context.scope, ) observerContext.serverContext.context.dispatch( VRServerActions.NewTracker( trackerId = trackerId, - context = newTracker - ) + context = newTracker, + ), ) observerContext.context.dispatch( UDPConnectionActions.AssignTracker( trackerId = TrackerIdNum( id = trackerId, - trackerNum = event.data.sensorId - ) - ) + trackerNum = event.data.sensorId, + ), + ), ) newTracker.context.dispatch(action) } - } - } + }, ) val SensorRotationBehaviour = UDPConnectionBehaviour( @@ -292,14 +293,14 @@ val SensorRotationBehaviour = UDPConnectionBehaviour( tracker.context.dispatch( TrackerActions.Update { copy(rawRotation = event.data.rotation) - } + }, ) } } - } + }, ) -fun createUDPConnectionContext( +fun createUDPConnection( id: String, socket: BoundDatagramSocket, remoteAddress: InetSocketAddress, @@ -312,7 +313,7 @@ fun createUDPConnectionContext( PingBehaviour, DeviceStatsBehaviour, SensorInfoBehaviour, - SensorRotationBehaviour + SensorRotationBehaviour, ) val context = createContext( @@ -325,7 +326,7 @@ fun createUDPConnectionContext( address = remoteAddress.hostname, port = remoteAddress.port, deviceId = null, - trackerIds = listOf() + trackerIds = listOf(), ), reducers = behaviours.map { it.reducer }, scope = scope, @@ -347,14 +348,20 @@ fun createUDPConnectionContext( }, getDevice = { val deviceId = context.state.value.deviceId - if (deviceId != null) serverContext.getDevice(deviceId) - else null + if (deviceId != null) { + serverContext.getDevice(deviceId) + } else { + null + } }, getTracker = { id -> val trackerId = context.state.value.trackerIds.find { it.trackerNum == id } - if (trackerId != null) serverContext.getTracker(trackerId.id) - else null - } + if (trackerId != null) { + serverContext.getTracker(trackerId.id) + } else { + null + } + }, ) behaviours.map { it.observer }.forEach { it?.invoke(conn) } diff --git a/server/core/src/main/java/dev/slimevr/tracker/udp/packets.kt b/server/core/src/main/java/dev/slimevr/tracker/udp/packets.kt index a3eb7d8ae..7aa0941bb 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/udp/packets.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/udp/packets.kt @@ -33,7 +33,6 @@ private fun Source.readSafeQuat(): Quaternion { } } - enum class PacketType(val id: Int) { HEARTBEAT(0), ROTATION(1), @@ -57,7 +56,8 @@ enum class PacketType(val id: Int) { SET_CONFIG_FLAG(25), FLEX_DATA(26), POSITION(27), - PROTOCOL_CHANGE(200); + PROTOCOL_CHANGE(200), + ; companion object { private val map = entries.associateBy { it.id } @@ -81,7 +81,7 @@ data class Handshake( val mcuType: Int = 0, val protocolVersion: Int = 0, val firmware: String? = null, - val macString: String? = null + val macString: String? = null, ) : UDPPacket { override fun write(dst: Sink) { dst.writeByte(PacketType.HANDSHAKE.id.toByte()) @@ -94,38 +94,52 @@ data class Handshake( val b = if (remaining >= 4) readInt() else 0 val i = if (remaining >= 4) readInt() else 0 val m = if (remaining >= 4) readInt() else 0 - if (remaining >= 12) { readInt(); readInt(); readInt() } + if (remaining >= 12) { + readInt() + readInt() + readInt() + } val p = if (remaining >= 4) readInt() else 0 val f = if (remaining >= 1) readString(readByte().toLong()) else null val mac = if (remaining >= 6) { val bytes = readByteArray(6) bytes.joinToString(":") { "%02X".format(it) }.takeIf { it != "00:00:00:00:00:00" } - } else null + } else { + null + } Handshake(b, i, m, p, f, mac) } } } data class Rotation(override val sensorId: Int = 0, val rotation: Quaternion = Quaternion.IDENTITY) : SensorSpecificPacket { - companion object { fun read(src: Source) = Rotation(0, src.readSafeQuat()) } + companion object { + fun read(src: Source) = Rotation(0, src.readSafeQuat()) + } } data class Accel(val acceleration: Vector3 = Vector3.NULL, override val sensorId: Int = 0) : SensorSpecificPacket { companion object { fun read(src: Source) = Accel( Vector3(src.readSafeFloat(), src.readSafeFloat(), src.readSafeFloat()), - if (src.remaining > 0) src.readU8() else 0 + if (src.remaining > 0) src.readU8() else 0, ) } } data class PingPong(val pingId: Int = 0) : UDPPacket { - override fun write(dst: Sink) { dst.writeInt(pingId) } - companion object { fun read(src: Source) = PingPong(src.readInt()) } + override fun write(dst: Sink) { + dst.writeInt(pingId) + } + companion object { + fun read(src: Source) = PingPong(src.readInt()) + } } data class Serial(val serial: String = "") : UDPPacket { - companion object { fun read(src: Source) = Serial(src.readString(src.readInt().toLong())) } + companion object { + fun read(src: Source) = Serial(src.readString(src.readInt().toLong())) + } } data class BatteryLevel(val voltage: Float = 0f, val level: Float = 0f) : UDPPacket { @@ -138,11 +152,15 @@ data class BatteryLevel(val voltage: Float = 0f, val level: Float = 0f) : UDPPac } data class Tap(override val sensorId: Int = 0, val tap: Int = 0) : SensorSpecificPacket { - companion object { fun read(src: Source) = Tap(src.readU8(), src.readU8()) } + companion object { + fun read(src: Source) = Tap(src.readU8(), src.readU8()) + } } data class ErrorPacket(override val sensorId: Int = 0, val errorNumber: Int = 0) : SensorSpecificPacket { - companion object { fun read(src: Source) = ErrorPacket(src.readU8(), src.readU8()) } + companion object { + fun read(src: Source) = ErrorPacket(src.readU8(), src.readU8()) + } } data class SensorInfo( @@ -152,7 +170,7 @@ data class SensorInfo( val sensorConfig: UShort? = null, val hasCompletedRestCalibration: Boolean? = null, val trackerPosition: Int? = null, - val trackerDataType: Int? = null + val trackerDataType: Int? = null, ) : SensorSpecificPacket { companion object { fun read(src: Source) = with(src) { @@ -169,14 +187,16 @@ data class SensorInfo( } data class Rotation2(override val sensorId: Int = 1, val rotation: Quaternion = Quaternion.IDENTITY) : SensorSpecificPacket { - companion object { fun read(src: Source) = Rotation2(1, src.readSafeQuat()) } + companion object { + fun read(src: Source) = Rotation2(1, src.readSafeQuat()) + } } data class RotationData( override val sensorId: Int = 0, val dataType: Int = 0, val rotation: Quaternion = Quaternion.IDENTITY, - val calibrationInfo: Int = 0 + val calibrationInfo: Int = 0, ) : SensorSpecificPacket { companion object { fun read(src: Source): RotationData = with(src) { @@ -190,7 +210,9 @@ data class RotationData( } data class MagnetometerAccuracy(override val sensorId: Int = 0, val accuracy: Float = 0f) : SensorSpecificPacket { - companion object { fun read(src: Source) = MagnetometerAccuracy(src.readU8(), src.readSafeFloat()) } + companion object { + fun read(src: Source) = MagnetometerAccuracy(src.readU8(), src.readSafeFloat()) + } } data class SignalStrength(override val sensorId: Int = 0, val signal: Int = 0) : SensorSpecificPacket { @@ -214,17 +236,21 @@ data class Temperature(override val sensorId: Int = 0, val temp: Float = 0f) : S } data class UserActionPacket(val type: Int = 0) : UDPPacket { - companion object { fun read(src: Source) = UserActionPacket(src.readU8()) } + companion object { + fun read(src: Source) = UserActionPacket(src.readU8()) + } } data class FeatureFlags(val firmwareFeatures: ByteArray = byteArrayOf()) : UDPPacket { - companion object { fun read(src: Source) = FeatureFlags(src.readByteArray(src.remaining.toInt())) } + companion object { + fun read(src: Source) = FeatureFlags(src.readByteArray(src.remaining.toInt())) + } } data class RotationAndAccel( override val sensorId: Int = 0, val rotation: Quaternion = Quaternion.IDENTITY, - val acceleration: Vector3 = Vector3.NULL + val acceleration: Vector3 = Vector3.NULL, ) : SensorSpecificPacket { companion object { fun read(src: Source): RotationAndAccel { @@ -242,7 +268,9 @@ data class RotationAndAccel( } data class AckConfigChange(override val sensorId: Int = 0, val configType: UShort = 0u) : SensorSpecificPacket { - companion object { fun read(src: Source) = AckConfigChange(src.readU8(), src.readShort().toUShort()) } + companion object { + fun read(src: Source) = AckConfigChange(src.readU8(), src.readShort().toUShort()) + } } data class SetConfigFlag(override val sensorId: Int = 255, val configType: UShort = 0u, val state: Boolean = false) : SensorSpecificPacket { @@ -254,7 +282,9 @@ data class SetConfigFlag(override val sensorId: Int = 255, val configType: UShor } data class FlexData(override val sensorId: Int = 0, val flexData: Float = 0f) : SensorSpecificPacket { - companion object { fun read(src: Source) = FlexData(src.readU8(), src.readSafeFloat()) } + companion object { + fun read(src: Source) = FlexData(src.readU8(), src.readSafeFloat()) + } } data class PositionPacket(override val sensorId: Int = 0, val position: Vector3 = Vector3.NULL) : SensorSpecificPacket { @@ -268,32 +298,57 @@ data class ProtocolChange(val targetProtocol: Int = 0, val targetVersion: Int = dst.writeUByte(targetProtocol.toUByte()) dst.writeUByte(targetVersion.toUByte()) } - companion object { fun read(src: Source) = ProtocolChange(src.readU8(), src.readU8()) } + companion object { + fun read(src: Source) = ProtocolChange(src.readU8(), src.readU8()) + } } fun readPacket(type: PacketType, src: Source): UDPPacket = when (type) { PacketType.HEARTBEAT -> Heartbeat + PacketType.HANDSHAKE -> Handshake.read(src) + PacketType.ROTATION -> Rotation.read(src) + PacketType.ACCEL -> Accel.read(src) + PacketType.PING_PONG -> PingPong.read(src) + PacketType.SERIAL -> Serial.read(src) + PacketType.BATTERY_LEVEL -> BatteryLevel.read(src) + PacketType.TAP -> Tap.read(src) + PacketType.ERROR -> ErrorPacket.read(src) + PacketType.SENSOR_INFO -> SensorInfo.read(src) + PacketType.ROTATION_2 -> Rotation2.read(src) + PacketType.ROTATION_DATA -> RotationData.read(src) + PacketType.MAGNETOMETER_ACCURACY -> MagnetometerAccuracy.read(src) + PacketType.SIGNAL_STRENGTH -> SignalStrength.read(src) + PacketType.TEMPERATURE -> Temperature.read(src) + PacketType.USER_ACTION -> UserActionPacket.read(src) + PacketType.FEATURE_FLAGS -> FeatureFlags.read(src) + PacketType.ROTATION_AND_ACCEL -> RotationAndAccel.read(src) + PacketType.ACK_CONFIG_CHANGE -> AckConfigChange.read(src) - PacketType.SET_CONFIG_FLAG -> SetConfigFlag() // Usually outbound + + PacketType.SET_CONFIG_FLAG -> SetConfigFlag() + + // Usually outbound PacketType.FLEX_DATA -> FlexData.read(src) + PacketType.POSITION -> PositionPacket.read(src) + PacketType.PROTOCOL_CHANGE -> ProtocolChange.read(src) } @@ -308,7 +363,6 @@ fun writePacket(dst: Sink, packet: UDPPacket) { else -> error("Outbound support not implemented for ${packet::class.simpleName}") } - if (type != PacketType.HANDSHAKE) { dst.writeInt(type.id) dst.writeLong(0) diff --git a/server/core/src/main/java/dev/slimevr/tracker/udp/server.kt b/server/core/src/main/java/dev/slimevr/tracker/udp/server.kt index 49fd00783..6c48d31c6 100644 --- a/server/core/src/main/java/dev/slimevr/tracker/udp/server.kt +++ b/server/core/src/main/java/dev/slimevr/tracker/udp/server.kt @@ -48,7 +48,7 @@ suspend fun createUDPTrackerServer( if (connContext !== null) { connContext.packetEvents.emit(event) } else { - val newContext = createUDPConnectionContext( + val newContext = createUDPConnection( id = address.hostname, remoteAddress = address, socket = serverSocket, diff --git a/server/core/src/main/java/dev/slimevr/vrserver.kt b/server/core/src/main/java/dev/slimevr/vrserver.kt index 98cc98a95..2a50b6741 100644 --- a/server/core/src/main/java/dev/slimevr/vrserver.kt +++ b/server/core/src/main/java/dev/slimevr/vrserver.kt @@ -1,15 +1,19 @@ package dev.slimevr -import dev.slimevr.context.BasicBehaviour import dev.slimevr.context.Context +import dev.slimevr.context.CustomBehaviour import dev.slimevr.context.createContext +import dev.slimevr.firmware.FirmwareManager +import dev.slimevr.serial.SerialServer import dev.slimevr.tracker.Device import dev.slimevr.tracker.Tracker import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.distinctUntilChangedBy import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach -import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.atomics.AtomicInt +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlin.concurrent.atomics.incrementAndFetch data class VRServerState( val trackers: Map, @@ -22,7 +26,7 @@ sealed interface VRServerActions { } typealias VRServerContext = Context -typealias VRServerBehaviour = BasicBehaviour +typealias VRServerBehaviour = CustomBehaviour val BaseBehaviour = VRServerBehaviour( reducer = { s, a -> @@ -32,24 +36,32 @@ val BaseBehaviour = VRServerBehaviour( } }, observer = { context -> - context.state.distinctUntilChangedBy { state -> state.trackers.size }.onEach { + context.context.state.distinctUntilChangedBy { state -> state.trackers.size }.onEach { println("tracker list size changed") - }.launchIn(context.scope) + }.launchIn(context.context.scope) + + context.serialServer.context.state.distinctUntilChangedBy { state -> state.availablePorts.size }.onEach { + println("Avalable ports $it") + }.launchIn(context.context.scope) }, ) +@OptIn(ExperimentalAtomicApi::class) data class VRServer( val context: VRServerContext, + val serialServer: SerialServer, + val firmwareManager: FirmwareManager, + // Moved this outside of the context to make this faster and safer to use - private val handleCounter: AtomicInteger, + private val handleCounter: AtomicInt, ) { - fun nextHandle() = handleCounter.incrementAndGet() + fun nextHandle() = handleCounter.incrementAndFetch() fun getTracker(id: Int) = context.state.value.trackers[id] fun getDevice(id: Int) = context.state.value.devices[id] companion object { - fun create(scope: CoroutineScope): VRServer { - val server = VRServerState( + fun create(scope: CoroutineScope, serialServer: SerialServer, firmwareManager: FirmwareManager): VRServer { + val state = VRServerState( trackers = mapOf(), devices = mapOf(), ) @@ -57,17 +69,21 @@ data class VRServer( val behaviours = listOf(BaseBehaviour) val context = createContext( - initialState = server, + initialState = state, reducers = behaviours.map { it.reducer }, scope = scope, ) - behaviours.map { it.observer }.forEach { it?.invoke(context) } - - return VRServer( + val server = VRServer( context = context, - handleCounter = AtomicInteger(0), + serialServer = serialServer, + firmwareManager = firmwareManager, + handleCounter = AtomicInt(0), ) + + behaviours.map { it.observer }.forEach { it?.invoke(server) } + + return server } } } 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 4b5a6a886..42e388aad 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -5,16 +5,20 @@ package dev.slimevr.desktop import dev.slimevr.VRServer import dev.slimevr.config.createAppConfig import dev.slimevr.desktop.ipc.createIpcServers +import dev.slimevr.desktop.serial.createDesktopSerialServer +import dev.slimevr.firmware.createFirmwareManager +import dev.slimevr.resolveConfigDirectory import dev.slimevr.solarxr.createSolarXRWebsocketServer import dev.slimevr.tracker.udp.createUDPTrackerServer -import dev.slimevr.resolveConfigDirectory import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking fun main(args: Array) = runBlocking { val configFolder = resolveConfigDirectory() ?: error("Unable to resolve config folder") val config = createAppConfig(this, configFolder = configFolder.toFile()) - val server = VRServer.create(this) + val serialServer = createDesktopSerialServer(this) + val firmwareManager = createFirmwareManager(serialServer = serialServer, scope = this) + val server = VRServer.create(this, serialServer, firmwareManager) launch { createUDPTrackerServer(server, config) diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt index 81649da94..14d8e1bf9 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt @@ -1,8 +1,8 @@ package dev.slimevr.desktop.ipc -import dev.slimevr.VRServer import dev.slimevr.CURRENT_PLATFORM import dev.slimevr.Platform +import dev.slimevr.VRServer import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch @@ -21,11 +21,13 @@ suspend fun createIpcServers(server: VRServer) = coroutineScope { launch { createUnixFeederSocket(server) } launch { createUnixSolarXRSocket(server) } } + Platform.WINDOWS -> { launch { createWindowsDriverPipe(server) } launch { createWindowsFeederPipe(server) } launch { createWindowsSolarXRPipe(server) } } + else -> Unit } } diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/linux.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/linux.kt index 73467db7c..05fd369ee 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/linux.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/linux.kt @@ -16,39 +16,38 @@ import java.nio.channels.ServerSocketChannel import java.nio.channels.SocketChannel import kotlin.io.path.Path -suspend fun createUnixDriverSocket(server: VRServer) = - acceptUnixClients(DRIVER_SOCKET_NAME) { channel -> - handleDriverConnection( - server = server, - messages = readFramedMessages(channel), - send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } }, - ) - } +suspend fun createUnixDriverSocket(server: VRServer) = acceptUnixClients(DRIVER_SOCKET_NAME) { channel -> + handleDriverConnection( + server = server, + messages = readFramedMessages(channel), + send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } }, + ) +} -suspend fun createUnixFeederSocket(server: VRServer) = - acceptUnixClients(FEEDER_SOCKET_NAME) { channel -> - handleFeederConnection( - server = server, - messages = readFramedMessages(channel), - send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } }, - ) - } +suspend fun createUnixFeederSocket(server: VRServer) = acceptUnixClients(FEEDER_SOCKET_NAME) { channel -> + handleFeederConnection( + server = server, + messages = readFramedMessages(channel), + send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } }, + ) +} -suspend fun createUnixSolarXRSocket(server: VRServer) = - acceptUnixClients(SOLARXR_SOCKET_NAME) { channel -> - handleSolarXRConnection( - server = server, - messages = readFramedMessages(channel), - send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } }, - ) - } +suspend fun createUnixSolarXRSocket(server: VRServer) = acceptUnixClients(SOLARXR_SOCKET_NAME) { channel -> + handleSolarXRConnection( + server = server, + messages = readFramedMessages(channel), + send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } }, + ) +} private fun isSocketInUse(socketPath: String): Boolean = try { SocketChannel.open(StandardProtocolFamily.UNIX).use { it.connect(UnixDomainSocketAddress.of(socketPath)) true } -} catch (_: Exception) { false } +} catch (_: Exception) { + false +} // Length field is LE u32 and includes the 4-byte header itself private fun readFramedMessages(channel: SocketChannel) = flow { @@ -92,4 +91,4 @@ private suspend fun acceptUnixClients( launch { handle(client) } } } -} \ No newline at end of file +} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/windows.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/windows.kt index 5622cd6e9..4c89afb74 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/windows.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/windows.kt @@ -19,32 +19,29 @@ import java.nio.ByteOrder private val k32 = Kernel32.INSTANCE private val adv32 = Advapi32.INSTANCE -suspend fun createWindowsDriverPipe(server: VRServer) = - acceptWindowsClients(DRIVER_PIPE) { handle -> - handleDriverConnection( - server = server, - messages = readFramedMessages(handle), - send = { bytes -> withContext(Dispatchers.IO) { writeFramedPipe(handle, bytes) } }, - ) - } +suspend fun createWindowsDriverPipe(server: VRServer) = acceptWindowsClients(DRIVER_PIPE) { handle -> + handleDriverConnection( + server = server, + messages = readFramedMessages(handle), + send = { bytes -> withContext(Dispatchers.IO) { writeFramedPipe(handle, bytes) } }, + ) +} -suspend fun createWindowsFeederPipe(server: VRServer) = - acceptWindowsClients(FEEDER_PIPE) { handle -> - handleFeederConnection( - server = server, - messages = readFramedMessages(handle), - send = { bytes -> withContext(Dispatchers.IO) { writeFramedPipe(handle, bytes) } }, - ) - } +suspend fun createWindowsFeederPipe(server: VRServer) = acceptWindowsClients(FEEDER_PIPE) { handle -> + handleFeederConnection( + server = server, + messages = readFramedMessages(handle), + send = { bytes -> withContext(Dispatchers.IO) { writeFramedPipe(handle, bytes) } }, + ) +} -suspend fun createWindowsSolarXRPipe(server: VRServer) = - acceptWindowsClients(SOLARXR_PIPE) { handle -> - handleSolarXRConnection( - server = server, - messages = readFramedMessages(handle), - send = { bytes -> withContext(Dispatchers.IO) { writeFramedPipe(handle, bytes) } }, - ) - } +suspend fun createWindowsSolarXRPipe(server: VRServer) = acceptWindowsClients(SOLARXR_PIPE) { handle -> + handleSolarXRConnection( + server = server, + messages = readFramedMessages(handle), + send = { bytes -> withContext(Dispatchers.IO) { writeFramedPipe(handle, bytes) } }, + ) +} // Length field is LE u32 and includes the 4-byte header itself private fun readFramedMessages(handle: WinNT.HANDLE) = flow { @@ -92,7 +89,10 @@ private fun createSecurePipe(pipeName: String): WinNT.HANDLE { WinBase.PIPE_ACCESS_DUPLEX, WinBase.PIPE_TYPE_BYTE or WinBase.PIPE_READMODE_BYTE or WinBase.PIPE_WAIT, WinBase.PIPE_UNLIMITED_INSTANCES, - 65536, 65536, 0, attributes, + 65536, + 65536, + 0, + attributes, ) check(pipe != WinNT.INVALID_HANDLE_VALUE) { "CreateNamedPipe failed for $pipeName: ${k32.GetLastError()}" @@ -123,4 +123,4 @@ private suspend fun acceptWindowsClients( } } } -} \ No newline at end of file +} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/serial/flash.kt b/server/desktop/src/main/java/dev/slimevr/desktop/serial/flash.kt new file mode 100644 index 000000000..5fd74dd2a --- /dev/null +++ b/server/desktop/src/main/java/dev/slimevr/desktop/serial/flash.kt @@ -0,0 +1,68 @@ +package dev.slimevr.desktop.serial + +import dev.slimevr.serial.FlashingHandler +import com.fazecast.jSerialComm.SerialPort as JSerialPort + +class DesktopFlashingHandler : FlashingHandler { + private var port: JSerialPort? = null + + override fun openSerial(portObj: Any) { + val portLocation = portObj as? String ?: error("expected port location string") + val comPort = JSerialPort.getCommPorts().find { it.portLocation == portLocation } + ?: error("Unable to find port $portLocation") + if (comPort.isOpen) { + comPort.closePort() + } + if (!comPort.openPort(1000)) { + error("Unable to open port $portLocation") + } + this.port = comPort + } + + override fun closeSerial() { + port?.closePort() + port = null + } + + override fun setDTR(value: Boolean) { + val p = port ?: error("no port to set DTR") + if (value) p.setDTR() else p.clearDTR() + } + + override fun setRTS(value: Boolean) { + val p = port ?: error("no port to set RTS") + if (value) p.setRTS() else p.clearRTS() + } + + override fun write(data: ByteArray) { + val p = port ?: error("no port to write") + p.writeBytes(data, data.size) + } + + override fun read(length: Int): ByteArray { + val p = port ?: error("no port to read") + val data = ByteArray(length) + p.readBytes(data, length) + return data + } + + override fun changeBaud(baud: Int) { + val p = port ?: error("no port to set baud") + if (!p.setBaudRate(baud)) error("Unable to change baudrate to $baud") + } + + override fun setReadTimeout(timeout: Long) { + val p = port ?: error("no port to set timeout") + p.setComPortTimeouts(JSerialPort.TIMEOUT_READ_BLOCKING, timeout.toInt(), 0) + } + + override fun availableBytes(): Int { + val p = port ?: error("no port to check available bytes") + return p.bytesAvailable() + } + + override fun flushIOBuffers() { + val p = port ?: error("no port to flush") + p.flushIOBuffers() + } +} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/serial/serial.kt b/server/desktop/src/main/java/dev/slimevr/desktop/serial/serial.kt new file mode 100644 index 000000000..552e2357b --- /dev/null +++ b/server/desktop/src/main/java/dev/slimevr/desktop/serial/serial.kt @@ -0,0 +1,110 @@ +package dev.slimevr.desktop.serial + +import com.fazecast.jSerialComm.SerialPortEvent +import com.fazecast.jSerialComm.SerialPortMessageListener +import dev.slimevr.AppLogger +import dev.slimevr.serial.FlashingHandler +import dev.slimevr.serial.SerialPortHandle +import dev.slimevr.serial.SerialPortInfo +import dev.slimevr.serial.SerialServer +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.OutputStreamWriter +import com.fazecast.jSerialComm.SerialPort as JSerialPort + +private val SUPPORTED_BOARDS: Set> = setOf( + Pair(0x1A86, 0x7522), // CH340 + Pair(0x1A86, 0x7523), // CH340 + Pair(0x1A86, 0x5523), // CH341 + Pair(0x1A86, 0x55D3), // CH343 + Pair(0x1A86, 0x55D4), // CH9102x + Pair(0x10C4, 0xEA60), // CP210x + Pair(0x303A, 0x1001), // ESP32-S3 + Pair(0x303A, 0x0002), // ESP32 + Pair(0x0403, 0x6001), // FTDI FT232 +) + +private fun isKnownBoard(vid: Int, pid: Int) = SUPPORTED_BOARDS.contains(vid to pid) + +private fun openPort( + portLocation: String, + scope: CoroutineScope, + onDataReceived: suspend (String, String) -> Unit, + onPortDisconnected: suspend (String) -> Unit, +): SerialPortHandle? { + val port = JSerialPort.getCommPorts().find { it.portLocation == portLocation } ?: return null + port.baudRate = 115200 + port.clearRTS() + port.clearDTR() + if (!port.openPort(1000)) return null + + // Anonymous object is required by the jSerialComm API + port.addDataListener(object : SerialPortMessageListener { + override fun getListeningEvents() = JSerialPort.LISTENING_EVENT_DATA_RECEIVED or JSerialPort.LISTENING_EVENT_PORT_DISCONNECTED + + override fun getMessageDelimiter() = byteArrayOf(0x0A) + override fun delimiterIndicatesEndOfMessage() = true + + override fun serialEvent(event: SerialPortEvent) { + when (event.eventType) { + JSerialPort.LISTENING_EVENT_DATA_RECEIVED -> { + val line = event.receivedData.toString(Charsets.UTF_8).trimEnd() + scope.launch { onDataReceived(portLocation, line) } + } + + JSerialPort.LISTENING_EVENT_PORT_DISCONNECTED -> + scope.launch { onPortDisconnected(portLocation) } + } + } + }) + + return SerialPortHandle( + portLocation = portLocation, + descriptivePortName = port.descriptivePortName, + writeCommand = { text -> + OutputStreamWriter(port.outputStream).append(text).append("\n").flush() + }, + close = { + port.removeDataListener() + port.closePort() + }, + ) +} + +private suspend fun runSerialPoller(server: SerialServer) { + var lastKnown: Set = emptySet() + + while (true) { + val current = withContext(Dispatchers.IO) { + JSerialPort.getCommPorts() + .filter { isKnownBoard(it.vendorID, it.productID) } + .associate { port -> + port.portLocation to SerialPortInfo( + portLocation = port.portLocation, + descriptivePortName = port.descriptivePortName, + vendorId = port.vendorID, + productId = port.productID, + ) + } + } + + val added = current.keys - lastKnown + val removed = lastKnown - current.keys + + added.forEach { loc -> server.onPortDetected(current.getValue(loc)) } + removed.forEach { loc -> server.onPortLost(loc) } + + lastKnown = current.keys + delay(3000) + } +} + +fun createDesktopSerialServer(scope: CoroutineScope): SerialServer { + val server = SerialServer.create(openPort = ::openPort, openFlashingPort = { DesktopFlashingHandler() }, scope = scope) + scope.launch { runSerialPoller(server) } + return server +}