proper leasing of serial ports, automatic port closing when not in use

This commit is contained in:
loucass003 committed 2026-10-05 21:47:38 +02:00
1 parent 753fdb527e
commit ff296ce924
11 files changed
+402 -61

No files matched your search

@@ -5,6 +5,7 @@ import dev.slimevr.config.Settings
import dev.slimevr.config.SettingsActions
import dev.slimevr.serial.FlashingHandler
import dev.slimevr.serial.MAC_REGEX
import dev.slimevr.serial.SerialConsole
import dev.slimevr.serial.SerialServer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -124,12 +125,29 @@ internal suspend fun doSerialFlashPostFlash(
)
// The port re-enumerates after the flash, so it may take a moment to come back
val serialConn = serialServer.awaitConsole(portLocation, POST_FLASH_PORT_TIMEOUT)
if (serialConn == null) {
val lease = serialServer.awaitConsole(portLocation, POST_FLASH_PORT_TIMEOUT)
if (lease == null) {
onStatus(FirmwareUpdateStatus.ERROR_DEVICE_NOT_FOUND, 0)
return
}
try {
provisionFlashedPort(lease.console, needManualReboot, ssid, password, settings, server, onStatus)
} finally {
lease.release()
}
}
/** Reads the MAC off the freshly flashed tracker, hands it Wi-Fi credentials and waits for it to connect */
private suspend fun provisionFlashedPort(
serialConn: SerialConsole,
needManualReboot: Boolean,
ssid: String?,
password: String?,
settings: Settings,
server: VRServer,
onStatus: suspend (FirmwareUpdateStatus, Int) -> Unit,
) {
if (needManualReboot) {
// wait for the device to reboot
val rebooted = withTimeoutOrNull(60_000) {
@@ -132,29 +132,33 @@ data class ProvisioningManager(
if (!selectScanPort(context, serialServer)) continue
val portLocation = context.state.value.scan.portLocation ?: return@launch
val serialConn = serialServer.awaitConsole(portLocation, 3.seconds)
val lease = serialServer.awaitConsole(portLocation, 3.seconds)
if (serialConn == null) {
if (lease == null) {
context.dispatch(ProvisioningActions.ScanStatusChanged(WifiScanStatus.NO_SERIAL_DEVICE_FOUND))
return@launch
}
coroutineScope {
val work = async {
if (context.state.value.scan.networks.isEmpty()) {
scanWifiNetworks(context, serialConn)
try {
coroutineScope {
val work = async {
if (context.state.value.scan.networks.isEmpty()) {
scanWifiNetworks(context, lease.console)
}
awaitCancellation()
}
awaitCancellation()
val disconnect = async {
serialServer.context.state.map { it.ports }.first { portLocation !in it }
}
select {
work.onAwait {}
disconnect.onAwait {}
}
work.cancel()
disconnect.cancel()
}
val disconnect = async {
serialServer.context.state.map { it.ports }.first { portLocation !in it }
}
select {
work.onAwait {}
disconnect.onAwait {}
}
work.cancel()
disconnect.cancel()
} finally {
lease.release()
}
if (context.state.value.scan.networks.isEmpty()) {
@@ -195,14 +195,18 @@ internal suspend fun runProvisioningForPort(
) {
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.SERIAL_INIT))
val serialConn = serialServer.awaitConsole(portLocation, 3.seconds)
val lease = serialServer.awaitConsole(portLocation, 3.seconds)
if (serialConn == null) {
if (lease == null) {
context.dispatch(ProvisioningActions.TrackerStatusChanged(portLocation, TrackerProvisioningStatus.CONNECTION_ERROR))
return
}
provisionPort(context, server, settings, serialConn, ssid, password)
try {
provisionPort(context, server, settings, lease.console, ssid, password)
} finally {
lease.release()
}
}
// Reboots the tracker and waits for a MAC address in the serial logs.
@@ -12,14 +12,38 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.rpc.SerialDeviceType
import kotlin.concurrent.atomics.AtomicBoolean
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.time.Duration
private sealed interface Claim {
class Got(val console: SerialConsole) : Claim
class Got(val lease: SerialLease) : Claim
data object Retry : Claim
data object Failed : Claim
}
/** An open port and how many leases are keeping it open */
private class ConsoleHolder(val console: SerialConsole) {
var leases = 0
}
/**
* One holder's claim on a port. The port stays open while any lease on it is alive and closes once
* the last one is released, so every holder must [release] what it took. Releasing never suspends
* and repeats harmlessly
*/
@OptIn(ExperimentalAtomicApi::class)
class SerialLease internal constructor(
val console: SerialConsole,
private val onRelease: () -> Unit,
) {
private val released = AtomicBoolean(false)
fun release() {
if (released.compareAndSet(false, true)) onRelease()
}
}
data class SerialServerState(
val ports: Map<String, SerialPortInfo>,
/** Ports a firmware flash holds. A claim outlasts the port re-enumerating mid-flash */
@@ -40,7 +64,7 @@ class SerialServer(
private val watcher: SerialPortWatcher,
) {
private val ownership = Mutex()
private val consoles = mutableMapOf<String, SerialConsole>()
private val consoles = mutableMapOf<String, ConsoleHolder>()
fun startObserving() = context.observeAll(this)
@@ -63,15 +87,16 @@ class SerialServer(
}
}
suspend fun awaitConsole(portLocation: String, timeout: Duration): SerialConsole? = withTimeoutOrNull(timeout) {
/** The caller owns the returned lease and must release it, or the port never closes */
suspend fun awaitConsole(portLocation: String, timeout: Duration): SerialLease? = withTimeoutOrNull(timeout) {
claimConsole(portLocation)
}
private suspend fun claimConsole(portLocation: String): SerialConsole? {
private suspend fun claimConsole(portLocation: String): SerialLease? {
while (true) {
context.state.map { isFree(it, portLocation) }.first { it }
when (val claim = ownership.withLock { claimOnce(portLocation) }) {
is Claim.Got -> return claim.console
is Claim.Got -> return claim.lease
is Claim.Failed -> return null
is Claim.Retry -> {}
}
@@ -81,17 +106,38 @@ class SerialServer(
private suspend fun claimOnce(portLocation: String): Claim {
if (!isFree(context.state.value, portLocation)) return Claim.Retry
consoles[portLocation]?.let { existing ->
if (existing.closed.isActive) return Claim.Got(existing)
if (existing.console.closed.isActive) return Claim.Got(lease(portLocation, existing))
// this port failed and the cleanup in [watchForClose] hasn't run yet
closeConsole(portLocation)
}
AppLogger.serial.info("Opening serial console on $portLocation")
val clearResetLines = context.state.value.ports[portLocation]?.type == SerialDeviceType.ESP_TRACKER
val console = SerialConsole.open(watcher, portLocation, clearResetLines) ?: return Claim.Failed
consoles[portLocation] = console
val holder = ConsoleHolder(console)
consoles[portLocation] = holder
AppLogger.serial.info("Opened serial console on $portLocation")
watchForClose(console)
return Claim.Got(console)
return Claim.Got(lease(portLocation, holder))
}
/**
* Hands out a lease on [holder]. Call under [ownership] and with no suspension before the lease
* reaches its holder, so a cancelled claim can't leave the count raised
*/
private fun lease(portLocation: String, holder: ConsoleHolder): SerialLease {
holder.leases++
return SerialLease(holder.console) {
context.scope.launch {
ownership.withLock {
holder.leases--
// A claim that landed while this release was queued keeps the port open
if (holder.leases == 0 && consoles[portLocation] === holder) {
AppLogger.serial.info("Last holder of $portLocation released it")
closeConsole(portLocation)
}
}
}
}
}
suspend fun openForFlashing(portLocation: String): FlashingHandler? = ownership.withLock {
@@ -112,17 +158,17 @@ class SerialServer(
}
private suspend fun closeConsole(portLocation: String) {
val console = consoles.remove(portLocation) ?: return
val holder = consoles.remove(portLocation) ?: return
AppLogger.serial.info("Closing serial console on $portLocation")
console.close()
holder.console.close()
}
private fun watchForClose(console: SerialConsole) {
context.scope.launch {
console.closed.join()
if (consoles[console.portLocation] === console) AppLogger.serial.warn("Serial port ${console.portLocation} reported itself closed")
if (consoles[console.portLocation]?.console === console) AppLogger.serial.warn("Serial port ${console.portLocation} reported itself closed")
ownership.withLock {
if (consoles[console.portLocation] === console) closeConsole(console.portLocation)
if (consoles[console.portLocation]?.console === console) closeConsole(console.portLocation)
}
}
}
@@ -3,6 +3,7 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.VRServer
import dev.slimevr.device.Device
import dev.slimevr.firmware.isOnlineStatus
import dev.slimevr.logging.AppLogger
import dev.slimevr.provisioning.ProvisioningManager
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
@@ -12,6 +13,8 @@ import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.rpc.StartWifiProvisioningRequest
import solarxr_protocol.rpc.StartWifiScanRequest
@@ -27,9 +30,25 @@ class ProvisioningBehaviour(
private val provisioningManager: ProvisioningManager,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
// The manager is shared by every client, so only the one that started a session stops it on
// its way out. A client that crashes or reloads never sends the stop itself, and provisioning
// holds serial ports
var startedProvisioning = false
var startedScan = false
receiver.context.scope.coroutineContext.job.invokeOnCompletion {
if (!startedProvisioning && !startedScan) return@invokeOnCompletion
provisioningManager.context.scope.launch {
AppLogger.solarxr.info("Client left while provisioning, stopping it")
if (startedProvisioning) provisioningManager.stopProvisioning()
if (startedScan) provisioningManager.stopWifiScan()
}
}
receiver.rpcDispatcher.on<StartWifiProvisioningRequest> { event ->
val ssid = event.ssid ?: return@on
startedProvisioning = true
provisioningManager.startProvisioning(
server,
ssid,
@@ -38,14 +57,17 @@ class ProvisioningBehaviour(
}.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<StopWifiProvisioningRequest> {
startedProvisioning = false
provisioningManager.stopProvisioning()
}.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<StartWifiScanRequest> {
startedScan = true
provisioningManager.startWifiScan()
}.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<StopWifiScanRequest> {
startedScan = false
provisioningManager.stopWifiScan()
}.launchIn(receiver.context.scope)
@@ -2,12 +2,14 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.logging.AppLogger
import dev.slimevr.serial.SerialConsole
import dev.slimevr.serial.SerialLease
import dev.slimevr.serial.SerialServer
import dev.slimevr.serial.SerialServerState
import dev.slimevr.serial.sortPorts
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
@@ -20,13 +22,16 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.rpc.CloseSerialRequest
import solarxr_protocol.rpc.OpenSerialRequest
import solarxr_protocol.rpc.SerialConsoleStatus
import solarxr_protocol.rpc.SerialDevice
import solarxr_protocol.rpc.SerialDevicesRequest
import solarxr_protocol.rpc.SerialDevicesResponse
import solarxr_protocol.rpc.SerialKeepaliveRequest
import solarxr_protocol.rpc.SerialTrackerCustomCommandRequest
import solarxr_protocol.rpc.SerialTrackerFactoryResetRequest
import solarxr_protocol.rpc.SerialTrackerGetInfoRequest
@@ -39,9 +44,29 @@ import kotlin.time.Duration.Companion.seconds
// Wait before reopening a port whose console dropped while the port stayed plugged in
private val REOPEN_DELAY = 1.seconds
// How long the client has to renew its hold before the server takes the ports back
private val KEEPALIVE_GRACE = 15.seconds
private const val LOG_QUEUE_CAPACITY = 2000
private const val MAX_BATCH_CHARS = 16_000
/**
* Reuses the lease this client already holds on the port, replacing it when the port died under it.
* Leases stay in [leases] for as long as the client keeps its console open
*/
private suspend fun claimForClient(
serialServer: SerialServer,
leases: MutableMap<String, SerialLease>,
portLocation: String,
): SerialLease? {
leases[portLocation]?.let { held ->
if (held.console.closed.isActive) return held
held.release()
leases -= portLocation
}
return serialServer.awaitConsole(portLocation, Duration.INFINITE)?.also { leases[portLocation] = it }
}
/**
* Follows one port: streams its console while open, reports why it isn't otherwise, and opens it
* again when it comes back or a flash releases it
@@ -51,6 +76,7 @@ private suspend fun runConsoleSession(
serialServer: SerialServer,
portLocation: String,
activeConsole: MutableStateFlow<SerialConsole?>,
leases: MutableMap<String, SerialLease>,
) = coroutineScope {
launch {
serialServer.context.state
@@ -65,8 +91,8 @@ private suspend fun runConsoleSession(
if (isPortFree(serialServer.context.state.value, portLocation)) {
receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPENING))
}
val console = serialServer.awaitConsole(portLocation, Duration.INFINITE)
if (console == null) {
val lease = claimForClient(serialServer, leases, portLocation)
if (lease == null) {
// The port refused to open, so there is nothing to do until something changes
val before = serialServer.context.state.value
receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPEN_FAILED))
@@ -74,6 +100,7 @@ private suspend fun runConsoleSession(
continue
}
val console = lease.console
activeConsole.value = console
val device = serialServer.context.state.value.ports[portLocation]?.toSerialDevice()
receiver.sendRpc(SerialUpdateResponse(status = SerialConsoleStatus.OPEN, device = device))
@@ -118,9 +145,29 @@ class SerialBehaviour(private val serialServer: SerialServer) : SolarXRBridgeBeh
override fun observe(receiver: SolarXRBridge) {
val scope = receiver.context.scope
// A client has one console open at a time
var session: Job? = null
var watchdog: Job? = null
val activeConsole = MutableStateFlow<SerialConsole?>(null)
val leases = mutableMapOf<String, SerialLease>()
val renewals = Channel<Unit>(Channel.CONFLATED)
fun releaseLeases() {
leases.values.forEach { it.release() }
leases.clear()
}
suspend fun endSession() {
session?.cancelAndJoin()
session = null
watchdog?.cancel()
watchdog = null
activeConsole.value = null
releaseLeases()
}
// A client that crashes, reloads or loses its socket never sends CloseSerialRequest, so the
// scope dying has to drop its claims too
scope.coroutineContext.job.invokeOnCompletion { releaseLeases() }
// The full list goes out on every change. Clients replace their list, so removals need no event
serialServer.context.state
@@ -139,15 +186,27 @@ class SerialBehaviour(private val serialServer: SerialServer) : SolarXRBridgeBeh
receiver.rpcDispatcher.on<OpenSerialRequest> { req ->
val portLocation = req.port ?: return@on
AppLogger.solarxr.info("Serial console requested on $portLocation")
session?.cancel()
// Joining keeps the old session from adding a lease after this one took over the map
session?.cancelAndJoin()
activeConsole.value = null
session = scope.launch { runConsoleSession(receiver, serialServer, portLocation, activeConsole) }
session = scope.launch { runConsoleSession(receiver, serialServer, portLocation, activeConsole, leases) }
if (watchdog == null) {
watchdog = scope.launch {
while (withTimeoutOrNull(KEEPALIVE_GRACE) { renewals.receive() } != null) continue
AppLogger.solarxr.warn("Serial keepalive stopped, taking the client's consoles back")
watchdog = null
endSession()
}
}
}.launchIn(scope)
receiver.rpcDispatcher.on<SerialKeepaliveRequest> {
renewals.trySend(Unit)
}.launchIn(scope)
receiver.rpcDispatcher.on<CloseSerialRequest> {
session?.cancel()
session = null
activeConsole.value = null
AppLogger.solarxr.info("Serial consoles released by the client")
endSession()
}.launchIn(scope)
receiver.rpcDispatcher.on<SerialTrackerRebootRequest> {